This is my mysql table
id date_created date_active
1 2014年06月07日 18:24:38 NULL
2 2014年06月07日 18:24:38 2014年06月07日 18:24:38
3 2014年06月07日 18:24:38 2014年06月07日 18:24:38
4 2014年06月07日 18:24:38 NULL
5 2014年06月07日 18:24:38 NULL
6 2014年06月07日 18:24:38 NULL
7 2014年06月07日 18:24:38 2014年06月07日 18:24:38
8 2014年06月07日 18:24:38 2014年06月07日 18:24:38
9 2014年06月07日 18:24:38 2014年06月07日 18:24:38
10 2014年06月07日 18:24:38 NULL
How to set WHERE to select another column if the column is NULL?
SELECT *
FROM TABLE
WHERE date_active = 'value'.
If date_active is NULL it should use the date_created column.
Martin Smith
88.4k15 gold badges258 silver badges357 bronze badges
asked Dec 27, 2014 at 1:14
1 Answer 1
Generally speaking you can use COALESCE
SELECT *
FROM TABLE
WHERE COALESCE(date_active,date_created) = 'value'
However this is not sargable. Depending on indexes available you may find the following
SELECT *
FROM TABLE
WHERE date_active = 'value' OR
(date_active IS NULL AND date_created = 'value')
Or even
SELECT *
FROM TABLE
WHERE date_active = 'value'
UNION ALL
SELECT *
FROM TABLE
WHERE (date_active IS NULL AND date_created = 'value')
Performs better
answered Dec 27, 2014 at 1:23
lang-sql