Skip to content
Advertisement

Return false if no rows for select

I have next query:

SELECT 
CASE
  WHEN test_date < now() THEN true
    ELSE false
END AS "isTest"
FROM user_test_date
WHERE new_date is NULL AND login_id = 1

It works fine, if we have some records in new_date table, but if it is empty for some user, query just returns empty string. How I can return false, if there are no records also?

Advertisement

Answer

You could just selects an EXISTS expression here:

SELECT EXISTS (SELECT 1 FROM user_test_date
               WHERE test_date < NOW() AND new_date IS NULL AND login_id = 1) AS isTest;

This would always return just a single record, containing a boolean value of true or false.

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