Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL sort with limit? (non trivial)

Tags:

java

sql

table {
  id: long
  name: string
}

1235 Fred
1902 Trever
5123 George
6467 Derek
7868 Joe
8972 Bob
9272 Alf
9842 Hank

I want to return 2 records prior to that of Joes, in ascending order.

i.e The correct values should be:

5123 George
6467 Derek

Any thoughts? FYI:

  1. Returns incorrect rows:

    select * from table with id<7868 order by id asc limit 2

  2. Returns incorrect sort order:

    select * from table with id<7868 order by id desc limit 2

like image 247
Matt Avatar asked May 25 '09 23:05

Matt


People also ask

Can we use limit with group by?

No, you can't LIMIT subqueries arbitrarily (you can do it to a limited extent in newer MySQLs, but not for 5 results per group). This is a groupwise-maximum type query, which is not trivial to do in SQL.

How to SKIP the first n rows in SQL query?

The OFFSET FETCH clause allows you to skip N first rows in a result set before starting to return any rows. In this syntax: The ROW and ROWS , FIRST and NEXT are the synonyms. Therefore, you can use them interchangeably.

How to use SKIP in SQL query?

Using SKIP and ORDER BYWhen you use the SKIP option in a query with an ORDER BY clause, you can exclude the first offset rows that have the lowest values according to the ORDER BY criteria. You can also use SKIP to exclude rows with the highest values, if the ORDER BY clause includes the DESC keyword.


2 Answers

SELECT * FROM
  (select * from table where id<7868 order by id desc limit 2) AS foo
ORDER BY ID ASC
like image 50
Alex Martelli Avatar answered Oct 25 '22 20:10

Alex Martelli


Try:

Select * from (
    select * from table with id<7868 
    order by id desc limit 2
) as t order by id asc

Doing the subquery lets you first get the correct rows, then you can re-order them afterwards

like image 45
Jonathan Fingland Avatar answered Oct 25 '22 19:10

Jonathan Fingland