Explain Codes LogoExplain Codes Logo

Select one column if the other is null

sql
null-handling
sql-functions
data-integrity
Alex KataevbyAlex Kataev·Dec 27, 2024
TLDR

To select a non-null column, use SQL's lifesaver, COALESCE. It's like SQL's game of hot potato, picking the first non-null value passed to it:

SELECT COALESCE(col1, col2) AS result FROM table;

In this race, col1 gets the baton if present; else, col2 grabs it. result here is your winner.

Widening the SQL toolset

COALESCE vs IFNULL: The great divide

While COALESCE calls for an applause being an ANSI SQL standard function, the less known IFNULL keeps to its corner designed specifically for MySQL. Sticking with COALESCE ensures that your SQL queries can cruise around all SQL databases. It's all about playing the field, isn't it?

Hello, CASE: The SQL Swiss knife

When you need to juggle more balls than just picking the first non-null value, CASE comes in like a hail mary pass. It falls more into the programmer's comfort zone with its resemblance to an if-else block:

SELECT CASE WHEN col1 IS NOT NULL THEN col1 -- When col1 is not playing hide and seek ELSE col2 -- col2 saves the day END AS result FROM table;

Null handling: Better safe than sorry

High up on any SQL developer's list is maintaining data integrity. These functions are like your kid's night light, helping you overcome the fear of the 'null' darkness, picking up a reasonable value and ensuring your data selection doesn't lose its meaning.

More than just COALESCE

More ways to skin a cat

Looking beyond COALESCE, Oracle users can use NVL or SQL Server users may opt for ISNULL. They all aim to do the same thing: make NULL less scary. Here's how you would use them:

-- In Oracle's world SELECT NVL(col1, col2) AS result FROM table; -- NV-who? NVL! -- In the realm of SQL Server SELECT ISNULL(col1, col2) AS result FROM table; -- 'Cause no one likes NULL

'OR' is not the 'OR'dinary solution

You don't want to stumble into writing SELECT col1 OR col2 FROM table;. That's like asking if col1 or col2 exists, not choosing between col1 and col2. Boolean logic can be a tricky beast!

Preprocessing: A stitch in time saves nine

Browsing through dirty data? Consider preprocessing to tackle nulls upfront. Setting default values when loading or transforming your data can be like having coffee ready in the morning - it just makes everything else smoother!