Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write "Order By" clause before "Where" clause

Tags:

sql

oracle

I want to write an ORDER BY clause before my WHERE condition because I need to truncate my results to just 10, but I need to sort them in alphabetical order first.

I know that you can't put ORDER BY before WHERE so how can I do it?

I need to do something like the following:

SELECT *
FROM myTable
ORDER BY TOP10
WHERE ROWNUM <=10
like image 598
Keven Avatar asked Aug 14 '13 21:08

Keven


People also ask

Which comes first GROUP BY or WHERE?

The GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.

Should GROUP BY come before WHERE?

GROUP BY clause is used with the SELECT statement. In the query, GROUP BY clause is placed after the WHERE clause.

What is the correct order of GROUP BY ORDER BY and WHERE clauses in SELECT?

The correct answer is Select, where, group by, having.

Does order matter in WHERE clause?

No, that order doesn't matter (or at least: shouldn't matter). Any decent query optimizer will look at all the parts of the WHERE clause and figure out the most efficient way to satisfy that query.


2 Answers

You can use an inline view for this

SELECT * 
FROM (
 SELECT *
 FROM myTable
 ORDER BY TOP10) T
WHERE ROWNUM <=10
like image 59
Conrad Frix Avatar answered Oct 06 '22 00:10

Conrad Frix


SELECT * 
FROM (SELECT * FROM myTable RANK() OVER (ORDER BY TOP10) rank) 
WHERE rank <= 10;

For more see this

Edited: Thanks Wolf for correction:

select * from (select mt.*, rank() over (order by top10) rank from mytable mt) 
WHERE rank <= 10
like image 44
Karel Frajták Avatar answered Oct 06 '22 00:10

Karel Frajták