Return a value if no record is found

Encapsulate the query in a sub-query to transform “no row” to a null value.

I tested and verified this with PostgreSQL, SQLite, SQL Server, and MySQL.

SELECT (SELECT id FROM tbl WHERE id = 9823474) AS id;

In Oracle you have to select from the dummy 1-row table DUAL:

SELECT (SELECT id FROM tbl WHERE id = 9823474) AS id FROM DUAL;

You can do the same in MySQL for compatibility reasons, but you don’t have to.
Similar in Firebird:

SELECT (SELECT id FROM tbl WHERE id = 9823474) AS id FROM RDB$DATABASE;

This does it for DB2 (like Sean commented):

SELECT (SELECT id FROM tbl WHERE id = 9823474) AS id FROM SYSIBM.SYSDUMMY1;

Leave a Comment