Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If field is null, pull certain fields; otherwise, pull other fields

I have the following table:

TestTable  
  ColumnA  
  Column1  
  Column2  
  Column3  
  Column4 

I want to write a simple SQL statement that checks ColumnA and depending on whether it is null or not returns certain columns.

Something like (pseudo):

If ColumnA Is Null
  SELECT ColumnA, Column1, Column2 
  FROM TestTable
Else
  SELECT ColumnA, Column3, Column4
  FROM TestTable

Any ideas?

like image 512
Sesame Avatar asked Apr 18 '12 17:04

Sesame


People also ask

How do you check if a field is NULL?

SELECT * FROM yourTableName WHERE yourSpecificColumnName IS NULL OR yourSpecificColumnName = ' '; The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value.

How do you handle blank values in SQL?

I identified three ways to handle them: replace the null value by a neutral value, e.g. “N/A” or “-” replace the null value by a meaningful value. let the null value be null.


3 Answers

One more way to skin this particular cat:

SELECT ColumnA,
       NVL2(ColumnA, Column3, Column1),
       NVL2(ColumnA, Column4, Column2)
  FROM TestTable

Share and enjoy.

like image 124

Use SQL CASE expressions:

SELECT
    ColumnA,
    CASE WHEN ColumnA IS NULL THEN Column1 ELSE Column3 END AS ColumnB,
    CASE WHEN ColumnA IS NULL THEN Column2 ELSE Column4 END AS ColumnC
FROM
    TestTable

See:
CASE (SQL-Server Transact-SQL)
CASE Expressions (Oracle)

like image 30
Olivier Jacot-Descombes Avatar answered Oct 13 '22 08:10

Olivier Jacot-Descombes


I can think of a couple of routes, none are necessarily pretty...

People often find the first one, then look for something better. I'm not sure that there really is anything better.

SELECT
  ColumnA,
  CASE WHEN ColumnA IS NULL THEN Column1 ELSE Column2 END AS ColumnB,
  CASE WHEN ColumnA IS NULL THEN Column3 ELSE Column4 END AS ColumnC
FROM
  yourTable

Or...

SELECT
  yourTable.ColumnA,
  subTable.ColumnB,
  subTable.ColumnC
FROM
  yourTable
CROSS APPLY
(
  SELECT yourTable.Column1 AS ColumnB, yourTable.Column3 AS ColumnC WHERE yourTable.ColumnA IS NULL
  UNION ALL
  SELECT yourTable.Column2 AS ColumnB, yourTable.Column4 AS ColumnC WHERE yourTable.ColumnA IS NOT NULL
)
  AS subTable

Or...

SELECT
  ColumnA,
  Column1 AS ColumnB,
  Column2 AS ColumnC
FROM
  yourTable
WHERE
  ColumnA IS NULL

UNION ALL

SELECT
  ColumnA,
  Column2 AS ColumnB,
  Column4 AS ColumnC
FROM
  yourTable
WHERE
  ColumnA IS NOT NULL
like image 24
MatBailie Avatar answered Oct 13 '22 08:10

MatBailie