In SQL, what function do I use to return the first non-null column per row?
- User
In SQL, what function do I use to return the first non-null column per row?
Assistant
In SQL, you use the COALESCE function to return the first non-null value from a list of columns or expressions.
Here's how it works:
SELECT COALESCE(column1, column2, column3, ...) AS result FROM your_table;For example, if you have a table with contact information where people might have provided different phone numbers:
SELECT name, COALESCE(mobile_phone, work_phone, home_phone, 'No phone') AS primary_phone FROM contacts;In this example:
- If
mobile_phonehas a value, it returns that - If
mobile_phoneis NULL butwork_phonehas a value, it returnswork_phone - If both are NULL but
home_phonehas a value, it returns
- If
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.