< Prev: ORDER BY
Up: SQL Expressions
Next: UNION, INTERSECT, EXCEPT >

SQL Expressions: IN

Contents

Overview

  contents
.In() is a method that exists on all Fields and also sq.RowValue (see Tuple IN). It returns a Predicate, which means it can be used anywhere where a Predicate is expected. Note that when literal values are passed into it (for example in a slice) the values are parameterized, not literally interpolated (IN ($1, $2, $3) and not IN (1, 2, 3)).

In list

  contents
u := tables.USERS().As("u")

// u.user_id IN (u.name, u.email, u.password)
u.USER_ID.In(sq.RowValue{u.NAME, u.EMAIL, u.PASSWORD})

// u.user_id IN (1, 2, 3)
u.USER_ID.In(sq.RowValue{1, 2, 3})

In slice

  contents
In follows the slice expansion rules, so slices are viable arguments.
u := tables.USERS().As("u")

// u.user_id IN (1, 2, 3)
userIDs := []int{1, 2, 3}
u.USER_ID.In(userIDs)

// u.name IN ("tom", "dick", "harry")
names := []int{"tom", "dick", "harry"}
u.NAME.In(names)

In subquery

  contents
u := tables.USERS().As("u")

// u.user_id IN (
//     SELECT u.user_id
//     FROM public.users AS u
//     WHERE u.name IS NOT NULL
// )
u.USER_ID.In(sq.
    Select(u.USER_ID).
    From(u).
    Where(u.Name.IsNotNull()),
)

Tuple IN (Row Value Expressions)

  contents
u := tables.USERS().As("u")

// (u.user_id, u.name) IN ((1, "tom"), (2, "dick"), (3, "harry"))
sq.RowValue{u.USER_ID, u.NAME}.In{sq.RowValues{
    sq.RowValue{1, "tom"},
    sq.RowValue{2, "dick"},
    sq.RowValue{3, "harry"},
}}

// (u.user_id, u.name, u.email) IN (
//     SELECT u.user_id, u.name, u.email
//     FROM public.users AS u
//     WHERE u.name IS NOT NULL
// )
sq.RowValue{u.USER_ID, u.NAME, u.EMAIL}.In(sq.
    Select(u.USER_ID, u.NAME, u.EMAIL).
    From(u).
    Where(u.NAME.IsNotNull()),
)
< Prev: ORDER BY
Up: SQL Expressions
Next: UNION, INTERSECT, EXCEPT >