Re: Single SQL to find if any record exists across several tables

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(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" <pgsql-sql(at)postgresql(dot)org>
Subject: Re: Single SQL to find if any record exists across several tables
Date: 2017-09-21 15:06:14
Message-ID: CAKFQuwbVLvU_wPCtQ35+2DyJjMrLmzrMKRuQF4JfRsKQkC8sTw@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Thu, Sep 21, 2017 at 5:45 AM, Ertan Küçükoğlu <
ertan(dot)kucukoglu(at)1nar(dot)com(dot)tr> wrote:

>
> Is it possible to build a single SQL statement and include all tables in it
> so that I receive single "count(fk)" sum across all tables?
>
> Several sample SQLs run at the moment are as follows:
> Select count(fk) from cari
> Select count(fk) from sipbaslik
> Select count(fk) from stkdepo
> Select count(fk) from stkkart
> Select count(fk) from stkhar
>

​Without delving into dynamic SQL you can do either:

SELECT sum(count) FROM
(
SELECT count(fk) FROM can
UNION ALL
SELECT count(fk) FROM sipbaslik
)​ src

OR

SELECT
(SELECT count(fk) FROM can)
+
(SELECT count(fk) FROM sipbaslik)

David J.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Vishwanath M.C 2017-09-22 06:43:30 Not able to find the postgres version in stack builder
Previous Message Ertan Küçükoğlu 2017-09-21 12:45:02 Single SQL to find if any record exists across several tables