diesel::dsl

Function case_when

Source
pub fn case_when<C, T, ST>(condition: C, if_true: T) -> case_when<C, T, ST>
Expand description

Creates a SQL CASE WHEN ... END expression

§Example

use diesel::dsl::case_when;

let users_with_name: Vec<(i32, Option<i32>)> = users
    .select((id, case_when(name.eq("Sean"), id)))
    .load(connection)
    .unwrap();

assert_eq!(&[(1, Some(1)), (2, None)], users_with_name.as_slice());

§ELSE clause

use diesel::dsl::case_when;

let users_with_name: Vec<(i32, i32)> = users
    .select((id, case_when(name.eq("Sean"), id).otherwise(0)))
    .load(connection)
    .unwrap();

assert_eq!(&[(1, 1), (2, 0)], users_with_name.as_slice());

Note that the SQL types of the case_when and else expressions should be equal. This includes whether they are wrapped in Nullable, so you may need to call nullable on one of them.

§More WHEN branches

use diesel::dsl::case_when;

let users_with_name: Vec<(i32, Option<i32>)> = users
    .select((id, case_when(name.eq("Sean"), id).when(name.eq("Tess"), 2)))
    .load(connection)
    .unwrap();

assert_eq!(&[(1, Some(1)), (2, Some(2))], users_with_name.as_slice());