Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

like '%' does not accept NULL value

Tags:

sql

null

I have query that is build from user's inputs ( passed via html form). It looks like (simple example):

Select * From [table] Where [table].[column] like '<parameter>' 

This parameter may be optional so if user left corresponding input field empty I pass %. It worked fine until I encountered NULL values. I understand that '%' match symbols not null, but i would like to consider NULL as empty string in this case.

What should I do? Change query (how?) or pass another symbol(s) when user left empty input?

Thanks.

PS. It's real problem from existing system and i know it's far from optimal solution, but i have to deal with it.

like image 491
zgorawski Avatar asked Oct 13 '10 13:10

zgorawski


People also ask

Which does not accept NULL value?

By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.

Does not like include nulls?

NULL means the absence of a value, meaning that LIKE and NOT LIKE should actually evaluate to FALSE and TRUE, respectively, when dealing with NULL values, and not the nonsensical NULL. NULL in SQL is supposed to mean "unknown" rather than "no value".

What does LIKE '%' mean in SQL?

The SQL LIKE Operator The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

Does Count () ignores NULL?

COUNT(expression) does not count NULL values.


1 Answers

You can use coalesce to treat null like an empty string:

where COALESCE([table].[column],'') like '<parameter>' 

On SQL Server, you can also use IsNull:

where IsNull([table].[column],'') like '<parameter>' 
like image 146
Andomar Avatar answered Sep 18 '22 13:09

Andomar