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?
According to the execution plan, the two queries are different. For example, the query:
Will give me:
As you can see, we hit USER_PK which is the primary key of that table.
If I sort by a non-indexed column:
I’ll get:
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:
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.