Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a default row for a query that returns no rows?

Tags:

sql

sql-server

I need to know how to return a default row if no rows exist in a table. What would be the best way to do this? I'm only returning a single column from this particular table to get its value.

Edit: This would be SQL Server.

like image 503
John Baughman Avatar asked Nov 12 '08 22:11

John Baughman


People also ask

How do I restrict the number of rows returned by a selection?

Which of the following clause is used to limit the number of rows retrieved from a SELECT query? Answer: B. The WHERE clause is used to restrict the number of rows returned from a SELECT query.

How do I exclude a row in SQL query?

Use the relational operators != or <> to exclude rows in a WHERE clause.


1 Answers

One approach for Oracle:

SELECT val FROM myTable UNION ALL SELECT 'DEFAULT' FROM dual WHERE NOT EXISTS (SELECT * FROM myTable) 

Or alternatively in Oracle:

SELECT NVL(MIN(val), 'DEFAULT') FROM myTable 

Or alternatively in SqlServer:

SELECT ISNULL(MIN(val), 'DEFAULT') FROM myTable 

These use the fact that MIN() returns NULL when there are no rows.

like image 79
WW. Avatar answered Sep 20 '22 09:09

WW.