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;
    
  3. The correct way to express the previously selected statement ...

Get Oracle Database 11gR2 Performance Tuning Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.