Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first non-null values for multiple columns

Tags:

I'm attempting to get the first non-null value in a set of many columns. I'm aware that I could accomplish this using a sub-query per column. In the name of performance, which really does count in this scenario, I'd like to do this in a single pass.

Take the following example data:

col1     col2     col3     sortCol
====================================
NULL     4        8        1
1        NULL     0        2
5        7        NULL     3

My dream query would find the first non-null value in each of the data columns, sorted on the sortCol.

For example, when selecting the magical aggregate of the first three columns, sorted by the sortCol descending.

col1     col2     col3
========================
5        7         0

Or when sorting ascending:

col1     col2     col3
========================
1        4         8

Does anyone know a solution?

like image 387
Ryan Bair Avatar asked Jan 11 '10 22:01

Ryan Bair


People also ask

How do I find the first non-NULL value in SQL?

SQL COALESCE – a function that returns the first defined, i.e. non-NULL value from its argument list. Usually one or more COALESCE function arguments is the column of the table the query is addressed to. Often a subquery is also an argument for a function.

Which function returns the first non-NULL value in a list?

MySQL COALESCE() function returns the first non-NULL value of a list, or NULL if there are no non-NULL values.

Does group by ignore nulls?

Group functions ignore the NULL values in the column. To enforce the group functions ti include the NULL value, use NVL function.


1 Answers

Have you actually performance tested this solution before rejecting it?

SELECT
    (SELECT TOP(1) col1 FROM Table1 WHERE col1 IS NOT NULL ORDER BY SortCol) AS col1,
    (SELECT TOP(1) col2 FROM Table1 WHERE col2 IS NOT NULL ORDER BY SortCol) AS col2,
    (SELECT TOP(1) col3 FROM Table1 WHERE col3 IS NOT NULL ORDER BY SortCol) AS col3

If this is slow it's probably because you don't have an appropriate index. What indexes do you have?

like image 196
Mark Byers Avatar answered Nov 07 '22 01:11

Mark Byers