Re: [SQL] Always getting back a row, even with no results - Mailing list pgsql-sql

From Jonathan Moules
Subject Re: [SQL] Always getting back a row, even with no results
Date
Msg-id 15dd1ea396c.10c78e843106370.6070220804472515174@lightpear.com
Whole thread Raw
In response to Re: [SQL] Always getting back a row, even with no results  (Achilleas Mantzios <achill@matrix.gatewaynet.com>)
List pgsql-sql

Do smth like along the lines (might want to add additional code for ordering, this just happens to run correctly) :
select * from my_table where cat = 500 UNION select null,null LIMIT CASE WHEN (select count(*) from my_table where cat=500)>0 THEN (select count(*) from my_table where cat=500) ELSE 1 END ;
Of course you can write a function to do that for you, but what made you want this in the first place? Maybe this is bad design ?


Unfortunately this is a constraint of the environment; not good design, but SQL seems like it should be the simplest place to solve this.

I tried your example; it seems the ordering is required, otherwise the results always include the null. So the below works for anyone who finds this in the future. Thanks


select
            id
from
            my_table
where
            cat = 2
 
UNION
 
select
            null as id
ORDER BY
            id ASC
LIMIT
    CASE
            WHEN (
                select
                        count(*)
                from
                        my_table
                where
                        cat = 2
                ) > 0
            THEN (
                select count(*) from my_table where cat=2
                )
            ELSE
                1
    END;

pgsql-sql by date:

Previous
From: "David G. Johnston"
Date:
Subject: Re: [SQL] Always getting back a row, even with no results
Next
From: Jonathan Moules
Date:
Subject: Re: [SQL] Always getting back a row, even with no results