Re: Improve "select count(*)" query - takes more than 30 mins for some large tables

From: MichaelDBA Vitale <michaeldba(at)sqlexec(dot)com>
To: Mladen Gogala <gogala(dot)mladen(at)gmail(dot)com>, pgsql-admin(at)lists(dot)postgresql(dot)org
Subject: Re: Improve "select count(*)" query - takes more than 30 mins for some large tables
Date: 2022-07-12 14:31:17
Message-ID: 1221536526.20277.1657636277921@email.ionos.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-admin

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
Perhaps do an analyze on the table and then select reltuples from pg_class for that table.&nbsp; Might be faster than the select count(*).
</div>
<div class="default-style">
<br>
</div>
<div class="default-style">
Regards,
</div>
<div class="default-style">
Michael Vitale
</div>
<div class="default-style">
<br>
</div>
<blockquote type="cite">
<div>
On 07/12/2022 8:51 AM Mladen Gogala &lt;gogala(dot)mladen(at)gmail(dot)com&gt; wrote:
</div>
<div>
<br>
</div>
<div>
<br>
</div>
<div class="moz-cite-prefix">
On 7/11/22 03:23, Florents Tselai wrote:
<br>
</div>
<blockquote type="cite">
<pre class="moz-quote-pre">psql “select id from my_table" | sort -u | wc -l
</pre>
</blockquote>
<p>That will be a lot slower than just "select count(*) from my_table".&nbsp; You are delivering data to the user program (psql) and then shipping them to pipe and then processing the output with "wc". Depending on the version, PostgreSQL has very reliable parallelism and can do counting rather quickly. The speed of "select count(*) from my_table" depends on the speed of I/O. Since the table is big, it cannot be cached in the file system cache, so all that you have at your disposal is the raw disk speed. For the smaller machines, NVME is the king. For larger rigs, you should consider something like Pure, XTremIO or NetApp SolidFire. People frequently expect database to do miracles with under par hardware.<br></p>
<pre class="moz-signature">--
Mladen Gogala
Database Consultant
Tel: (347) 321-1217
<a href="https://dbwhisperer.wordpress.com" class="moz-txt-link-freetext">https://dbwhisperer.wordpress.com</a>
</pre>
</blockquote>
</body>
</html>

Attachment Content-Type Size
unknown_filename text/html 1.8 KB

In response to

Responses

Browse pgsql-admin by date

  From Date Subject
Next Message John Scalia 2022-07-12 16:58:34 Automating removal of orphaned stored procedure calls
Previous Message Mladen Gogala 2022-07-12 12:51:42 Re: Improve "select count(*)" query - takes more than 30 mins for some large tables