Re: [SQL] Single SQL to find if any record exists across several tables - Mailing list pgsql-sql

From Feike Steenbergen
Subject Re: [SQL] Single SQL to find if any record exists across several tables
Date
Msg-id CAK_s-G068-xbLTr3U9LzE1_bfYKQSvZaFphkQkFqkWaSDiLtag@mail.gmail.com
Whole thread Raw
In response to [SQL] Single SQL to find if any record exists across several tables  (Ertan Küçükoğlu <ertan.kucukoglu@1nar.com.tr>)
List pgsql-sql
On 21 September 2017 at 14:45, Ertan Küçükoğlu <ertan.kucukoglu@1nar.com.tr> wrote:
>
> Before deleting any company code row, I would like to be sure that it is not
> used in anywhere.

If you don't actually care about the count, but only if the value exists (like the
subject suggests) you could do something like:

SELECT EXISTS (
    SELECT FROM cari WHERE fk = $1
    UNION ALL
    SELECT FROM sipbaslik WHERE fk = $1
    [UNION ALL ...]
);

This will stop executing as soon as it finds a record matching fk, it does
not have to scan subsequent tables if it hits on the first table.
Depending on your data set that might be very useful.

=# EXPLAIN ANALYZE
SELECT EXISTS (
    SELECT FROM cari WHERE fk = 'a'
    UNION ALL
    SELECT FROM sipbaslik WHERE fk = 'a'
);
                                                 QUERY PLAN
-------------------------------------------------------------------------------------------------------------
 Result  (cost=3.87..3.88 rows=1 width=1) (actual time=0.010..0.010 rows=1 loops=1)
   InitPlan 1 (returns $0)
     ->  Append  (cost=0.00..54.14 rows=14 width=0) (actual time=0.009..0.009 rows=1 loops=1)
           ->  Seq Scan on cari  (cost=0.00..27.00 rows=7 width=0) (actual time=0.009..0.009 rows=1 loops=1)
                 Filter: (fk = 'a'::text)
           ->  Seq Scan on sipbaslik  (cost=0.00..27.00 rows=7 width=0) (never executed)
                 Filter: (fk = 'a'::text)

pgsql-sql by date:

Previous
From: "Vishwanath M.C"
Date:
Subject: [SQL] Not able to find the postgres version in stack builder
Next
From: athinivas
Date:
Subject: [SQL] Static variable inside PL/pgSQL (or) native C function