Previously we selected certain both columns or
rows. Now we would like to sort the results. This is
done by adding ORDER BY clause to the query. After
this the query can look like:
In the previous queries we added alias for the
table "a". From now we can reference to the columns
of the certain table using this alias. Now we will
try to select 2 middle rows when sorted by user name
descending. For this purpose we will use analytical
function row_number(). This function calculate and
apply internal sort in the inner query. Then we will
give alias to the inner query "b". And finally we
will apply filter to select only rows with row number
between 2 and 3.
select rn, user_key, user_name from (
select
row_number() over (order by user_name desc) rn,
a.user_key,
a.user_name
from users a
) b
where b.rn between 2 and 3;