Return a value if no record is found
Solution 1:
Encapsulate the query in a sub-query to transform "no row" to a NULL value.
I tested and verified this with PostgreSQL, SQL Server and MySQL. Also works with SQLite.
SELECT (SELECT id FROM tbl WHERE id = 9823474) AS id;
In Oracle you have to select from the dummy 1-row table DUAL
like this:
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;
Alternative with UNION ALL
SELECT id FROM tbl WHERE id = 9823474
UNION ALL
SELECT NULL -- FROM DUAL -- for Oracle
FETCH FIRST 1 ROW ONLY;
Standard SQL, but I only tested this with Postgres, which evaluates like this:
If a row is found in the first SELECT
, it is returned. Postgres stops looking for more rows, as soon as the first is found due to LIMIT 1
(FETCH FIRST 1 ROW ONLY
).
The second SELECT
is only even executed if the first returns nothing. The data type of the NULL value is determined by the data type of tbl.id
automatically.
About the LIMIT
clause:
- ANSI/ISO plans for LIMIT standardization?
Solution 2:
To make it more simplier, this should work fine. If you assign this to a variable based on the datatype of your idnumber than you would be able to evaluate whether the value is null or the actual idnumber return.
SELECT ISNULL(
(
SELECT idnumber
FROM dbo.database
WHERE number = '9823474'
), NULL)
Solution 3:
Select isnull(sum(Amount),0) as Amt from BeginningBalance where CustomerID = @CustomerID
Union all
Select isnull(sum(Amount),0) as Amt from SalesOrders where CustomerID = @CustomerID
Union all
Select isnull(sum(Amount),0) as Amt from SalesInvoices where CustomerID = @CustomerID
//Data Row Result if no data is present at Beginning Balance Table
// example
Amt
2000 // amount from sales orders
1000 // amount from sales invoices
// if the 1st select statement return no data use this
SELECT (select sum(Amount) from BeginningBalance
where CustomerID = @CustomerID) as Amt
Union all
Select sum(Amount) as Amt from SalesOrders where CustomerID = @CustomerID
Union all
Select sum(Amount) as Amt from SalesInvoices where CustomerID = @CustomerID
Result :
Amt
NULL // amount from BeginningBalance
2000 // amount from sales orders
1000 // amount from sales invoices
Solution 4:
I use this for MySql
SELECT IFNULL(ColumnA,"1") AS ColumnA , COUNT(1) AS Total FROM table
WHERE ID = 1 LIMIT 0, 1;