sqlpostgresqlgosqlc

Is it possible to omit field in where clause in postgresql?


In SQL I have following code:

-- name: FilterRecords :many
SELECT *
FROM records
WHERE industry_id = $3 and region_code = $4 and city_code = $5
OFFSET $1 LIMIT $2;

What I'm trying to achieve is to exclude industry_id from where clause if provided value for it is blank string. Because when I'm making query it's counting blank strings, but I want to omit it if it's blank and select only records where they match region_code and city_code.


Solution

  • This is the one made for me and worked correctly.

    -- name: FilterApz :many
    SELECT *
    FROM apz
    WHERE industry_id LIKE COALESCE(NULLIF($3, ''), '%%') and region_code = $4 and city_code = $5
    OFFSET $1 LIMIT $2;