HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlCritical

How can I use a default value in a Select query in PostgreSQL?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlcanqueryvaluedefaulthowselectuse

Problem

I would like to use a default value for a column that should be used if no rows is returned. Is that possible in PostgreSQL? How can I do it? Or is there any other way I can solve this?

E.g. something like this:

SELECT MAX(post_id) AS max_id DEFAULT 0 FROM my_table WHERE org_id = 3


And if there is no rows with org_id = 3 in the table I want to return 0.

Solution

SELECT coalesce(MAX(post_id),0) AS max_id FROM my_table WHERE org_id = 3


or

SELECT case count(*) when 0 then 0 else MAX(post_id) end AS max_id
FROM my_table 
WHERE org_id = 3;


if you want max(post_id) to be null when there is 1 row but post_id is null

dbfiddle

Code Snippets

SELECT coalesce(MAX(post_id),0) AS max_id FROM my_table WHERE org_id = 3
SELECT case count(*) when 0 then 0 else MAX(post_id) end AS max_id
FROM my_table 
WHERE org_id = 3;

Context

StackExchange Database Administrators Q#2804, answer score: 68

Revisions (0)

No revisions yet.