patternsqlMajor
Getting SELECT to return a constant value even if zero rows match
Viewed 0 times
rowsconstantreturnmatchgettingvalueevenselectzero
Problem
Consider this select statement:
It returns the column
How would one make the above SQL return at least the
BTW, it's PostgreSQL 8.4.
SELECT *,
1 AS query_id
FROM players
WHERE username='foobar';It returns the column
query_id with value 1 along with a player's other columns.How would one make the above SQL return at least the
query_id of 1 even if the select finds no rows that match?BTW, it's PostgreSQL 8.4.
Solution
SELECT col1,
col2,
col3,
1 AS query_id
FROM players
WHERE username='foobar'
union all
select null,
null,
null,
1
where not exists (select 1 from players where username = 'foobar');Or as an alternative (might be faster as no second subselect is required):
with qid (query_id) as (
values (1)
)
select p.*,
qid.query_id
from qid
left join players as p on (p.useranme = 'foobar');You can re-write the above to a more "compact" representation:
select p.*,
qid.query_id
from (values (1)) as qid (query_id)
left join players as p on (p.useranme = 'foobar');But I think the explicit CTE (
with...) is more readable (although that is always in the eyes of the beholder).Code Snippets
SELECT col1,
col2,
col3,
1 AS query_id
FROM players
WHERE username='foobar'
union all
select null,
null,
null,
1
where not exists (select 1 from players where username = 'foobar');with qid (query_id) as (
values (1)
)
select p.*,
qid.query_id
from qid
left join players as p on (p.useranme = 'foobar');select p.*,
qid.query_id
from (values (1)) as qid (query_id)
left join players as p on (p.useranme = 'foobar');Context
StackExchange Database Administrators Q#41067, answer score: 26
Revisions (0)
No revisions yet.