Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove conditions from WHERE clause if parameters are NULL

I'm passing 2 parameters to a PL/pgSQL function. Here's the query:

SELECT * 
FROM table 
WHERE col1 = param1 
  AND col2 = param2

Both parameters can be NULL, in which case the respective expression should be removed from the WHERE clause.

How can I do that? With IF conditions?

like image 738
user3339988 Avatar asked Apr 30 '14 10:04

user3339988


People also ask

Can we use null in WHERE clause?

Null values can be used as a condition in the WHERE and HAVING clauses. For example, a WHERE clause can specify a column that, for some rows, contains a null value.

Can you use coalesce in WHERE clause?

You can use coalesce anywhere, including the where clause, yes.

How do you return all records if parameter is null?

Inside the stored procedure, the parameter value is first tested for Null using the ISNULL function and then checked whether it is Blank (Empty). If the parameter has value then only matching records will be returned, while if the parameter is Null or Blank (Empty) then all records from the table will be returned.


Video Answer


2 Answers

Maybe this is doing the trick:

SELECT * 
FROM table 
WHERE col1 = param1 
  AND (param2 is null or col2 = param2);

This is not removing the AND condition, but should make the unimportant in case of param2 is null. So not clearly answering your question but going around... ;)

like image 75
frlan Avatar answered Oct 22 '22 16:10

frlan


The simplest (though probably not the most efficient) way is to handle the null inside the SQL statement itself, e.g.:

SELECT * 
FROM table 
WHERE col1 = param1 
AND (param2 IS NULL OR col2 = param2)

This by-passes the clause for all rows if the parameter is null.

Or with this trick:

SELECT * 
FROM table 
WHERE col1 = param1 
AND col2 = COALESCE(param2, col2)

When param2 is NULL, the condition is equivalent to col2 = col2, which will always be true as long as col2 doesn't itself contain NULL values.

A quick test using hard-coded values rather than a function parameter gave me the same query plan for both approaches - the OR and COALESCE parts are seemingly optimised away before planning the query, so it's as though the second AND were indeed being conditionally removed.

like image 29
IMSoP Avatar answered Oct 22 '22 18:10

IMSoP