-1

These queries return the same result, which is better performance?

Subquery in SELECT

SELECT
    books.id,
    books.title,
    (SELECT COUNT(*) FROM subscriptions WHERE books.id = subscriptions.book_id) AS subscription_count,
    (SELECT COUNT(*) FROM books) AS book_count
FROM books
ORDER BY id;

Subquery in FROM

SELECT
    *
FROM
    (SELECT
        books.id,
        books.title,
        (SELECT COUNT(*) FROM subscriptions WHERE books.id = subscriptions.book_id) AS subscription_count,
        (SELECT COUNT(*) FROM books) AS book_count
    FROM books) AS tmp
ORDER BY id;

And I should get book_count from other sql in this case?

akm
  • 65
  • 1
  • 7

1 Answers1

0

What you are using is called a derived table and for modern DBMS there is no performance difference whatsoever. So

select * 
from some_table
order by some_column;

will have exactly the same performance as:

select *
from (
  select *
  from some_table
) t
order by some_column;