From: | Feike Steenbergen <feikesteenbergen(at)gmail(dot)com> |
---|---|
To: | Ertan Küçükoğlu <ertan(dot)kucukoglu(at)1nar(dot)com(dot)tr> |
Cc: | pgsql-sql(at)postgresql(dot)org |
Subject: | Re: Single SQL to find if any record exists across several tables |
Date: | 2017-09-27 12:07:12 |
Message-ID: | CAK_s-G068-xbLTr3U9LzE1_bfYKQSvZaFphkQkFqkWaSDiLtag@mail.gmail.com |
Views: | Whole Thread | Raw Message | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-sql |
On 21 September 2017 at 14:45, Ertan Küçükoğlu <ertan(dot)kucukoglu(at)1nar(dot)com(dot)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)
From | Date | Subject | |
---|---|---|---|
Next Message | athinivas | 2017-09-29 13:46:19 | Static variable inside PL/pgSQL (or) native C function |
Previous Message | Vishwanath M.C | 2017-09-22 06:43:30 | Not able to find the postgres version in stack builder |