1

We have a PosgtreSQL DB table with lots of data. I wonder what type of query is faster / has a better performance and why?

  1. select * from table
  2. select count (*) from table
4
  • 1
    Different results. Choose the one you need. Commented Feb 10, 2023 at 10:06
  • Two different questions that give you different results. Why do you even care about the difference in time needed to get these different results? Commented Feb 10, 2023 at 10:09
  • It's possible to use them for the same purpose because clients tend to expose the ROW_COUNT variable. In the first case the app can read the row count associated with the result, in the second it can read the result. If you need both the count and the actual data, the first query can get them both at once. If you only need the row count, the contents of the table would just waste IO, weigh and slow things down, so count(*) is enough. Commented Feb 10, 2023 at 10:24
  • I know what they do, I just need to count at first and later, in some rare cases, use the result data. That's why I wonder if doing count at first and then select is better than doing select at the beggining. If the select has a worse performance, I'll use count Commented Feb 10, 2023 at 15:06

1 Answer 1

3

While both queries do iterate over the entire table, the first query will perform generally much worse at an application level versus the second one. This is because the select * query will need to send the entire table across the network to the application which is executing the query. The count(*) query, on the other hand, only needs to send across a single integer count.

Sign up to request clarification or add additional context in comments.

1 Comment

In addition to the network time, query #2 could skip the heap and count entries in the index, something that is much faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.