Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1iyImC-0003kD-Mo for pgsql-performance@arkaria.postgresql.org; Sun, 02 Feb 2020 17:11:16 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1iyImB-0000Kq-95 for pgsql-performance@arkaria.postgresql.org; Sun, 02 Feb 2020 17:11:15 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1iyImA-0000Kj-Vq for pgsql-performance@lists.postgresql.org; Sun, 02 Feb 2020 17:11:15 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1iyIm4-0006gQ-Kq for pgsql-performance@lists.postgresql.org; Sun, 02 Feb 2020 17:11:14 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.4/8.14.4) with ESMTP id 012HB5BE002662; Sun, 2 Feb 2020 12:11:06 -0500 From: Tom Lane To: Marco Colli cc: pgsql-performance@lists.postgresql.org Subject: Re: Statistics on array values In-reply-to: References: Comments: In-reply-to Marco Colli message dated "Sun, 02 Feb 2020 15:18:19 +0100" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <2660.1580663465.1@sss.pgh.pa.us> Date: Sun, 02 Feb 2020 12:11:05 -0500 Message-ID: <2661.1580663465@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Marco Colli writes: > Let's say that you have a simple query like the following on a large table > (for a multi-tenant application): > SELECT "subscribers".* FROM "subscribers" WHERE "subscribers"."project_id" > = 123 AND (tags @> ARRAY['de']::varchar[]); > If you run EXPLAIN ANALYZE you can see that stats are completely wrong. > For example I get an expected count of 3,500 rows whereas the actual > result is 20 rows. This also results in bad query plans... > In a previous discussion someone said that this wrong estimate is because > @> uses a fixed selectivity of 0.001, **regardless of actual data**!! > Is that true? Hasn't been true since 9.2. You might get some insight from looking into the most_common_elems, most_common_elem_freqs, and elem_count_histogram fields of the pg_stats view. It seems likely to me that increasing the statistics target for this array column would help. IIRC, estimates for values that don't show up in most_common_elems are going to depend on the lowest frequency that *does* show up there ... so if you want better resolution for non-common values, you need more entries. regards, tom lane