0

I want to write a query that returns all rows when a given parameter in a where condition is null but when the parameter is not null return rows that match the condition, i am using postgres 9.6 and here is what i have so far but no dice...

Edit

let me clarify the question

i have a prepared statement like this

select * from students where first_name like $1

what i want to do is when $1 is null ignore the where and return all students

Thanks

Vao Tsun
  • 47,234
  • 13
  • 100
  • 132
zola
  • 5,737
  • 8
  • 33
  • 48

2 Answers2

1

You can achieve this as below:

@FirstName is a parameter passed to the query:

select * from students where first_name like @FirstName or @FirstName is null;
Mittal Patel
  • 2,732
  • 14
  • 23
0

here is example of prepared statement with explicitly defined logic:

t=# prepare st(text) as select oid,datname 
from pg_database 
where case when $1 is null then true else datname like '%'||$1||'%' end;
PREPARE
t=# execute st('post');
  oid  | datname
-------+----------
 13505 | postgres
(1 row)

t=# execute st(null);
  oid  |  datname
-------+-----------
 13505 | postgres
 16384 | t
     1 | template1
 13504 | template0
 16419 | o
 16816 | db
(6 rows)
Vao Tsun
  • 47,234
  • 13
  • 100
  • 132