2

Let's say that I have the following two queries, getting aggregate data from two separate tables:

SELECT count(*) as count_a
FROM table_a
WHERE some_column = "some_value"
SELECT count(*) as count_b
FROM table_b
WHERE another_column = "another_value"

The queries are executed by code that uses both count_a and count_b in some sort of computation

To get count_a and count_b, I have the option of either executing both queries in parallel or combining them into a single query (below) that can be executed by itself to get both results:

SELECT (
  SELECT count(*)
  FROM table_a
  WHERE some_column = "some_value"
) as count_a,
(
  SELECT count(*)
  FROM table_b
  WHERE another_column = "another_value"
) as count_b

Am I likely to see any noticeable (or even a small) difference in performance between the two approaches? If so, which approach is more efficient?

Katie
  • 1,498
  • 1
  • 15
  • 33
  • You can refer here https://stackoverflow.com/questions/606234/select-count-from-multiple-tables – Sachin Jan 29 '20 at 03:40
  • 1
    In general, the fewer round trips to the database, the better, but there are exceptions, so the best idea is just to test this for yourself – Strawberry Jan 29 '20 at 07:08
  • You should check the query plan of each. Depending on how your indexes are, one might be more favorable than the other. All things being equal, the latter is likely more efficient (as @Strawberry mentioned); but things like incorrect row/memory estimates and even competition for read locks can make it perform worse. – Jason Jan 29 '20 at 19:22

0 Answers0