< Prev: Building off a common query builder >
Up: Query Building

Query Building: Reusing the same WHERE predicate across SELECT/UPDATE/DELETE

If you want to use the same WHERE predicate across SELECT, UPDATE or DELETE the most straightforward way would be to build the predicates independently as a Predicate slice and pass it into the query as needed.
u := tables.USERS()
// Declaring a reusable slice of predicates
predicates := []sq.Predicate{
    u.IS_ACTIVE,
    u.USER_ID.EqInt(userID),
    u.NAME.ILikeString(name),
    u.EMAIL.ILikeString(emailProvider),
}
// WHERE u.is_active AND u.user_id = :userID
//  AND u.name ILIKE :name AND u.email ILIKE :emailProvider

// Reusing predicates in a SelectQuery
sq.Select(u.NAME, u.EMAIL).From(u).Where(predicates...)
// SELECT u.name, u.email FROM users AS u
// WHERE u.is_active AND u.user_id = :userID
//  AND u.name ILIKE :name AND u.email ILIKE :emailProvider

// Reusing predicates in an UpdateQuery
sq.Update(u).Set(u.PASSWORD.Set("1234")).Where(predicates...)
// UPDATE users AS u SET password = 1234
// WHERE u.is_active AND u.user_id = :userID
//  AND u.name ILIKE :name AND u.email ILIKE :emailProvider

// Reusing predicates in a DeleteQuery
sq.DeleteFrom(u).Where(predicates...)
// DELETE FROM users AS u WHERE u.is_active
// WHERE u.is_active AND u.user_id = :userID
//  AND u.name ILIKE :name AND u.email ILIKE :emailProvider
Predicates are implicitly ANDed together. If you need to join predicates using OR, wrap the predicates in sq.Or().
< Prev: Building off a common query builder >
Up: Query Building