Skip to content
Advertisement

Default value in select – SQL

I want to select the sum of the biggest and the lowest numbers in specific column of table, I get it well but I also need to set a default value in case if the column is empty, so far I tried this:

SELECT 
(select max(col) FROM table) + (select min(col) FROM table)
AS col_sum = 0

And if my table is empty I want to get a single value with default value like this:

col_sum
-------
0

I tried to some solutions for default value but I didn’t found for exactly this case. Sorry I’m new to SQL 🙂

Advertisement

Answer

You can use COALESCE():

SELECT COALESCE( (select max(col) FROM table) + (select min(col) FROM table), 0) as col_sum

I would be inclined to use only a single subselect:

SELECT COALESCE( (SELECT MAX(col) + MIN(col) FROM table)), 0) as col_sum

And even to eliminate the subqueries entirely:

SELECT COALESCE(MAX(col) + MIN(col), 0)
FORM table;

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement