SQL Replace NULL When Joining 3 Tables

Simon Huang

Simon Huang

@simon

Here to note one way to replace the NULL values in SQL with other specified values.

Given 3 Tables A, B, C as follows:

Table A

idname
1Mike
2Cathy
3Paul

Table B

idage
116
232

Table C

idheight
1180
3168

As you can see, Table B and Table C have missing records for id = 2 and id = 3, if we LEFT JOIN them to Table A there will be 2 missing cells shown as NULL:

SELECT A.id,name,age,height
FROM (A LEFT JOIN B on A.id = b.id) LEFT JOIN C ON A.id=C.id;
idnameageheight
1Mike16180
2Cathy32==NULL==
3Paul==NULL==168

There is a way that we can replace the NULLs to other values, in our case 0s.

SELECT A.id,name,(CASE WHEN age IS NULL THEN '0' ELSE age END) AS age,
(CASE WHEN height IS NULL THEN '0' ELSE height END) AS height
FROM (A LEFT JOIN B on A.id = b.id) LEFT JOIN C ON A.id=C.id;

Now we have replaced all NULL to 0

idnameageheight
1Mike16180
2Cathy32==0==
3Paul==0==168
Fizzy

© 2025 Fizzy All Rights Reserved.