Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT COUNT(*) with an ORDER BY

Tags:

sql

count

oracle

Will the following two queries be executed in the same way?

SELECT COUNT(*) from person ORDER BY last_name;

and

SELECT COUNT(*) from person;

Either way they should display the same results, so I was curious if the ORDER BY just gets ignored.

The reason I am asking is because I am displaying a paginated table where I will get 20 records at a time from the database and then firing a second query that counts the total number of records. I want to know if I should use the same criteria that the first query used, or if I should be removing all sorting from the criteria?

like image 789
Danny Avatar asked Jan 30 '12 20:01

Danny


3 Answers

According to the execution plan, the two queries are different. For example, the query:

select count(*) from USER

Will give me:

INDEX (FAST FULL SCAN)  3.0 3   453812  3457        1   TPMDBO  USER_PK FAST FULL SCAN  INDEX (UNIQUE)  ANALYZED

As you can see, we hit USER_PK which is the primary key of that table.

If I sort by a non-indexed column:

select count(*) from USER ORDER BY FIRSTNAME --No Index on FIRSTNAME

I'll get:

TABLE ACCESS (FULL) 19.0    19  1124488 3457    24199   1   TPMDBO  USER    FULL    TABLE   ANALYZED    1

Meaning we did a full table scan (MUCH higher node cost)

If I sort by the primary key (which is already index,) Oracle is smart enough to use the index to do that sort:

INDEX (FAST FULL SCAN)  3.0 3   453812  3457    13828   1   TPMDBO  USER_PK FAST FULL SCAN  INDEX (UNIQUE)  ANALYZED

Which looks very similar to the first execution plan.

So, the answer to your question is absolutely not - they are not the same. However, ordering by an index that Oracle is already seeking anyway will probably result in the same query plan.

like image 56
Mike Christensen Avatar answered Oct 22 '22 13:10

Mike Christensen


Of course not. Unless last name is the primary key and you are already ordered by that.

like image 42
Sid Avatar answered Oct 22 '22 13:10

Sid


The Oracle query optimizer actually does perform a sort (I verified this looking at the explain plan) for the first version, but since both queries only return one row, the performance difference will be very small.

EDIT:

Mike's answer is correct. The performance difference can possibly be significant.

like image 1
GriffeyDog Avatar answered Oct 22 '22 14:10

GriffeyDog