Top 10 Results using SQL on DB2

Most developers would have problem trying to find the correct syntax for their SQL on different responding machines. This is where we see how are we going to do some SQL on the DB2. Some users are so acclimatized with mySQL that they are so used to having this syntax in order to get the first top 10 records.

SELECT * FROM [tablename] LIMIT 10

The above SQL statement was just an excerpt from my previous blog post here.

The above few statements are all short SQL statements. Wait till you see how we can do that on DB2.

DB2 SQL

SELECT * FROM [tablename] FETCH FIRST 10 ROWS ONLY

Simple yet efficient. Supposedly one wants to get the last 10 rows? How is it done then?

SELECT * FROM [tablename] WHERE CTRY = 'MY' ORDER BY ID DESC FETCH FIRST 10 ROWS ONLY

As for added bonus, I have even included the above WHERE inside the statement. Finally, you will now be able to fetch the latest 10 records from [tablename] with country code ‘MY‘.

2 Comments

  1. danielctw January 19, 2011
  2. Charmaine January 19, 2011

Leave a Reply to danielctw Cancel reply