6

I have a database table which contains a column that records page hits for every entry.

I want to select the top 5 most hit pages from the database, but can't seem to find the right method to do so using just SQL. In particular I'm looking for one which doesn't involve selecting every entry and scanning through it afterwards using PHP.

What's the best way to do this via SQL (if there is one)?

Thanks.

1
  • WHAT database? Which version??
    – marc_s
    Feb 2, 2011 at 13:23

4 Answers 4

17

Try this approach:

SELECT column1, column2, hit_pages,...
FROM YourTable
ORDER BY hit_pages DESC
LIMIT 5
4
  • 2
    Caveat: don't use select *, just select the columns you need. Feb 2, 2011 at 13:02
  • 2
    @Jong - difficult to give a better example without provided table structure.
    – eumiro
    Feb 2, 2011 at 13:03
  • @eumiro Table structure is more or less irrelevant to Jong's point, especially considering OP's question. You should never ever be using SELECT * unless you specifically need every single column in the table.
    – arkon
    Jul 15, 2015 at 23:49
  • LIMIT will not work in T-SQL. See stackoverflow.com/a/44645065/297358 located below for T-SQL syntax
    – Chip Wood
    Jan 24, 2019 at 14:22
4

In MySQL> SELECT * FROM table ORDER BY hits DESC limit 5;

In Oralce> SELECT * FROM table ORDER BY hits DESC where rownum <5;

4
  • I think it should be ORDER BY hist DESC (not ASC) Feb 2, 2011 at 13:02
  • @Jong - yeh, the dangers of talking on the phone and typing an answer revealed ;-) Feb 2, 2011 at 13:03
  • 1
    Oracle note: it's important to put the WHERE ROWNUM clause after the ORDER BY clause. Otherwise you are taking the first 5 rows in the table as nondeterministically selected by the database, then sorting them. Feb 2, 2011 at 13:16
  • @Justin thanks - i never even thought to note that, its just one of those things that you "just do" ;-) Feb 2, 2011 at 13:17
2

SELECT TOP 10 price(column Name) from products(tablename) order by price desc;

Below is the output

price
263.5 
123.79 
97 
81 
62.5 
55 
53 
49.3 
46 
45.6 
0

for find 20th maximum value primary key with where condition:

  declare @max20Pk int=0;
  select @maxPk=min(Pk_Transaction) from(
  select top 20  Pk_Transaction from tblTransaction with(nolock)
  where  Fk_ChargeType in(2,3)
  order by Pk_Transaction desc
  ) as dtt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.