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?
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.
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.
One more way to skin this particular cat:
SELECT ColumnA,
NVL2(ColumnA, Column3, Column1),
NVL2(ColumnA, Column4, Column2)
FROM TestTable
Share and enjoy.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With