Tuesday, October 7, 2008

How to find the N th highest row in a table ?

One of most common requirements in a SQL query is to find the 2nd ..3rd ..Nth highest Value in a particular column of a table.

Common Interview Question as well.

There are various ways to do find the second highest.
eg:
1. select MAX(Column) from TABLE
where Column NOT IN
(select Max(Column) from TABLE)


2. select MAX(Column) from TABLE
where Column <
(select Max(Column) from TABLE)

3. Using Minus in SQL Server

However, when we want to find the 3rd / 4th highest the query gets complicated and performance would take a hit.

A generic of doing the same would be:


SELECT
FROM (
select ROW_NUMBER() OVER (ORDER BY Column DESC) A,
from table
) TAB
WHERE A = N

(where N is the required value)

If you know more efficient ways then please put in a comment.

Tuesday, July 1, 2008

Books on Database Design Patterns

I was studing about of Database design patterns and find these books interesting:

Refactoring Databases : Evolutionary Database Design
By Martin Flower
Book site:
http://databaserefactoring.com/
You can buy it from:
http://www.amazon.com/exec/obidos/ASIN/0321293533

SQL Design Patterns
The Expert Guide to SQL Programming
By Vadim Tropashko
http://www.rampant-books.com/book_2006_1_sql_coding_styles.htm