Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1ryeTi-00HLTM-Cg for pgsql-general@arkaria.postgresql.org; Sun, 21 Apr 2024 21:12:02 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.94.2) (envelope-from ) id 1ryeTh-00GCUa-4k for pgsql-general@arkaria.postgresql.org; Sun, 21 Apr 2024 21:12:01 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1ryeTg-00GCUN-Q7 for pgsql-general@lists.postgresql.org; Sun, 21 Apr 2024 21:12:00 +0000 Received: from sss.pgh.pa.us ([68.162.161.243]) by makus.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1ryeTe-003y7S-Ej for pgsql-general@lists.postgresql.org; Sun, 21 Apr 2024 21:11:59 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 43LLBu4J2857959; Sun, 21 Apr 2024 17:11:56 -0400 From: Tom Lane To: Steve Baldwin cc: =?UTF-8?Q?Norbert_S=C3=A1ndor?= , pgsql-general@lists.postgresql.org Subject: Re: query multiple schemas In-reply-to: References: <30b10437-647c-48c9-8bd8-0f45b4af2d7b@erinors.com> Comments: In-reply-to Steve Baldwin message dated "Mon, 22 Apr 2024 06:35:41 +1000" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <2857957.1713733916.1@sss.pgh.pa.us> Date: Sun, 21 Apr 2024 17:11:56 -0400 Message-ID: <2857958.1713733916@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Steve Baldwin writes: > If the number of tenant schemas is reasonably static, you could write a > plpgsql function to create a set of UNION ALL views with one view for each > table in all tenant schemas. You could re-run the function each time a > tenant schema is added. Having the set of views would allow you to query > them as you would any of the underlying tables, and the query planner could > likely optimise the query better. With your current function, if you needed > to add a WHERE clause and the underlying tables were large, it would likely > not perform as well as the UNION ALL view. Another idea is to build a partitioned table comprising all the individual tables. This might require the tables to have all the same owner (not sure about that) and it'd require you to store the partition key, ie tenant, explicitly in every table which might seem a bit wasteful. But it'll likely outperform any other solution for the union queries. Notably, adding or deleting a partition would be much less painful than redefining a UNION ALL view. regards, tom lane