Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: select all rows if parameter is null, else only select matching rows

I have a variable coming into a stored procedure. This variable can either have a value or be null.

  • If the variable is null, I need to select all the rows in the table (some with NULL values, some with actual data).
  • If the variable is not null, I only need to select the rows where the variable matches a column.

I created this conditional statement to help explain what I would like to achieve:

if 

@status is null, select all the rows (rows with NULL for table.status, and rows with actual data for table.status)

else

select the rows where @status equals table.status

This is what I came up with (well one of them):

WHERE 
   book.book_nme LIKE @search_input AND
   book.book_desc LIKE @search_input AND 
   (book.author LIKE ISNULL(@author, book.author)) AND
   (bookStatus.status_desc LIKE ISNULL(@status, bookStatus.status_desc))

The only problem is that if bookStatus.status_desc is NULL, then it will not select that row (when @status is null)

I'm so confused, I tried looking up Coalesce too which seemed to prioritize the values, but ... I don't know what to do.

Should I just create a huge CASE in the stored procedure and have two select statements?

like image 520
Steve's a D Avatar asked Jan 16 '23 10:01

Steve's a D


2 Answers

WHERE  book.book_nme LIKE @search_input AND
book.book_desc LIKE @search_input AND 
(@author IS NULL OR book.author LIKE @author) AND
(@status IS NULL OR bookStatus.status_desc LIKE @status) ...

Update
Added both conditions, for @author and @status

like image 53
a1ex07 Avatar answered Jan 19 '23 01:01

a1ex07


If you think it about your description it breaks down as:

  • Return all rows when @status is null
  • Otherwise return rows that match @status.

You can express the last line of your sql to match this like this:

(@status is null OR bookStatus.status_desc LIKE @status)
like image 30
Jon Egerton Avatar answered Jan 18 '23 23:01

Jon Egerton