Databases Reference
In-Depth Information
We can see that the
SORT
UNIQUE
and
SORT
GROUP
BY
operations are performed in both
situations against the corresponding
HASH
UNIQUE
and
HASH
GROUP
BY
. The previous
operations don't return the rows ordered, so a subsequent
SORT
pass would be required,
using
SORT
UNIQUE
and
SORT
GROUP
BY
. The
SORT
operation is executed to obtain the
unique and group-by functions, so the rows are already ordered.
Here, we can also see that the index
IX_CUST_CITY
will be used to avoid the full table
scan operation on the table, but it won't be useful in avoiding the sort operation.
Some developers overuse the
DISTINCT
keyword to ensure
a unique set of results. We can avoid this situation by using
the correct
JOINS
operations and
FOREIGN
KEY
constraints,
resulting in an optimal execution plan.
See also
F
See
Chapter
3
,
Optimizing Storage Structures
for recipes on indexing
F
Full Table Scan operation was explained in
Chapter 4
,
Optimizing SQL Code
in the
Avoiding
Full
Table
Scans
recipe
Writing top n queries and ranking
One common problem when developing database applications is to show the first
n
rows of a
set, ordering the data in a specific manner. For example, if we want to see the last 10 articles
submitted in a web application.
In this recipe, we will see how to obtain this scope and how to obtain it faster.
How to do it...
The following steps will demonstrate how to get the top
n
queries and their ranking:
1.
Connect to the
SH
schema:
CONNECT sh@TESTDB/sh
2. Select the first 10 customers, ordered by their age, from youngest to oldest:
SELECT CUST_ID, CUST_FIRST_NAME, CUST_LAST_NAME,
CUST_YEAR_OF_BIRTH
FROM CUSTOMERS
WHERE ROWNUM < 11
ORDER BY CUST_YEAR_OF_BIRTH DESC;