1252748
1252748

Reputation: 15372

pgSQL: return all results, but possibly not one result

I would like to select everything in a table where the id column is not a particular value. However, is it possible to have that particular value be optional, and in that case return all the results.

It seems like case might be what I want, but it's not working for me. What I've tried

WHERE id != '' 

or

WHERE id (SELECT CASE WHEN $id IS NULL THEN '')
                            ^^ $id could be, say, 10 or NULL

is just the incorrect syntax. How can I make this query? Thanks much.

Upvotes: 1

Views: 49

Answers (2)

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125214

When you want any id then pass $id as empty or null. Otherwise pass the real id. Doing it the empty way:

where (id = $id or $id = '')

Using null:

where (id = $id or $id is null)

Upvotes: 1

Ihor Romanchenko
Ihor Romanchenko

Reputation: 28521

Try something like:

WHERE (id != v_id OR v_id IS NULL)

It will return all rows where id != v_id if v_id is not null

Or return all rows if v_id is null

Upvotes: 1

Related Questions