Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle/PL SQL/SQL null comparison on where clause

Tags:

Just a question about dealing will null values in a query.

For example I have the following table with the following fields and values

TABLEX Column1 1         2         3       4         5       --------- Column2 null A B C null 

I'm passing a variableY on a specific procedure. Inside the procedure is a cursor like this

CURSOR c_results IS SELECT * FROM TABLEX where column2 = variableY 

now the problem is variableY can be either null, A, B or C if the variableY is null i want to select all record where column2 is null, else where column2 is either A, B or C.

I cannot do the above cursor/query because if variableY is null it won't work because the comparison should be

CURSOR c_results IS SELECT * FROM TABLEX where column2 IS NULL 

What cursor/query should I use that will accomodate either null or string variable.

Sorry if my question is a bit confusing. I'm not that good in explaining things. Thanks in advance.

like image 818
user2447740 Avatar asked Jun 03 '13 12:06

user2447740


People also ask

Is NULL in Oracle WHERE clause?

Here is an example of how to use the Oracle IS NULL condition in a SELECT statement: SELECT * FROM suppliers WHERE supplier_name IS NULL; This Oracle IS NULL example will return all records from the suppliers table where the supplier_name contains a null value.

Can null value be compared in Oracle?

Nulls with Comparison Conditions Because null represents a lack of data, a null cannot be equal or unequal to any value or to another null. However, Oracle considers two nulls to be equal when evaluating a DECODE function.

Can we use NULL in WHERE clause?

Generally, NULL data represents data does not exist or missing data or unknown data. IS NULL & IS NOT NULL in SQL is used with a WHERE clause in SELECT, UPDATE and DELETE statements/queries to validate whether column has some value or data does not exist for that column.


2 Answers

Either produce different SQL depending on the contents of that parameter, or alter your SQL like this:

WHERE (column2 = variableY) OR (variableY IS NULL AND column2 IS NULL) 
like image 168
Lasse V. Karlsen Avatar answered Oct 10 '22 05:10

Lasse V. Karlsen


Oracle's Ask Tom says:

where decode( col1, col2, 1, 0 ) = 0  -- finds differences 

or

where decode( col1, col2, 1, 0 ) = 1  -- finds sameness - even if both NULL 

Safely Comparing NULL Columns as Equal

like image 34
rghome Avatar answered Oct 10 '22 05:10

rghome