Reputation: 13517
I have seen many posts about this in SO. But I could not get an answer. I want to the query to check if a particular row exists or not in a table. If it exists, it should return me a string true and stop the search there itself and if not return false.
Upvotes: 21
Views: 48880
Reputation: 23890
select
case when exists (select true from table_name where table_column=?)
then 'true'
else 'false'
end;
But it would be better to just return boolean instead of string:
select exists (select true from table_name where table_column=?);
Upvotes: 61
Reputation: 44230
Spoiler:
-- EXPLAIN ANALYZE
WITH magic AS (
WITH lousy AS ( SELECT * FROM one WHERE num = -1)
SELECT 'True'::text AS truth
WHERE EXISTS (SELECT * FROM lousy)
UNION ALL
SELECT 'False'::text AS truth
WHERE NOT EXISTS (SELECT * FROM lousy)
)
SELECT *
FROM magic
;
Upvotes: -17