Select one column if the other is null
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:
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:
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:
'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!
Was this article helpful?
