2

How can I replace all null values in the result set with values from another row of the same table? (like a fallback query)

Example schema:

CREATE TABLE parent (
    id INTEGER NOT NULL AUTO_INCREMENT,
    int1 INTEGER,
    int2 INTEGER,
    int3 INTEGER,
    PRIMARY KEY (id)
)

The query:

SELECT * FROM table1
WHERE id = ?

But I need to replace all null values with those of another row. I am looking for something like this:

SELECT * FROM table1 WHERE id = ?
   REPLACE ALL NULL VALUES WITH (
       SELECT * FROM table1 WHERE id = ?
   )

Example:

id    int1    int2   int3
---------------------------
 1     1      null    1
 2     null   null    1
 3     1       4      0

When I query for id 1 first and id 3 as fallback, I expect the result to be:

id    int1   int2   int3
---------------------------
 1     1      4      1
2
  • Could a CASE statement help you? Commented May 12, 2017 at 14:38
  • I don't know, that's the reason I asked ;) Commented May 12, 2017 at 14:39

3 Answers 3

4

You can do this using join and coalesce():

select t1.id,
       coalesce(t1.int1, tt1.int1) as int1,
       coalesce(t1.int2, tt1.int2) as int2,
       coalesce(t1.int3, tt1.int3) as int3
from table1 t1 join
     table1 tt1
     on tt1.id = 3
where t1.id = 1;
Sign up to request clarification or add additional context in comments.

Comments

1

join and ISNULL() (for MS SQL and IFNULL for MySql) function will be helpful in this case:

select t1.id, ISNULL(main.int1, fallback.int1) as int1,
       ISNULL(main.int2, fallback.int2) as int2,
       ISNULL(main.int3, fallback.int3) as int3
from table1 as main join table1 as fallback on fallback.id = 3
where main.id = 1;

1 Comment

As far as I know isnull does not exist for MySQL. It is an MS SQL function.
0

Take a look at case.

select case mycolumn is null
       when 1 then myothercolumn
       else mycolumn
       end
from mytable

You can also embed case-when into another. This should be sufficient for you to solve the problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.