tags:

views:

105

answers:

5

I have been asked in an interview to write a SQL query which fetches the first three records with highest value on some column from a table. I had written a query which fetched all the records with highest value, but didn't get how exactly i can get only first three records of those.

Could you help me in this.

Thanks.

+4  A: 

SELECT TOP 3 * FROM Table ORDER BY FieldName DESC

From here, but might be a little out of date:

Postgresql:

SELECT * FROM Table ORDER BY FieldName DESC LIMIT 3

MS SQL Server:

SELECT TOP 3 * FROM Table ORDER BY FieldName DESC

mySQL:

SELECT * FROM Table ORDER BY FieldName DESC LIMIT 3
Kyle Rozendo
That is not correct for Oracle. It applies the WHERE before the ORDER BY, so you get any 10 rows that match, then it sorts them.
WW
@WW - Going to remove the Oracle e.g. then. My understanding of it is not intricate enough to answer it fully. That was initially from the link posted in the answer.
Kyle Rozendo
In Oracle `SELECT R.* FROM (SELECT * FROM SomeTable ORDER by FieldName DESC)R WHERE rownum < 4` will do the trick for you. Ofcourse, there is another methid involving `LEAD, LAG` Oracle Analytical functions, which can't be covered here.
Guru
+1  A: 

Depending on the database engine, either

select top 3 * from table order by column desc

or

select * from table order by column desc limit 3

Carl Manaster
or something else on Oracle...
Thilo
+1  A: 

Select Top 3....

ozczecho
A: 

The syntax for TOP 3 varies widely from database to database.

Unfortunately, you need to use those constructs for the best performance. Libraries like Hibernate help here, because they can translate a common API into the various SQL dialects.

Since you are asking about Java, it is possible to just SELECT everything from the database (with an ORDER BY), but just fetch only the first three rows. Depending on how the query needs to be executed this might be good enough (especially if no sorting on the database has to happen thanks to appropriate indexes, for example when you sort by primary key fields).

But in general, you want to go with an SQL solution.

Thilo
A: 

In oracle you can also use where rownum < 4...

Also on mysql there is a Limit keyword (i think)

Karl