Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing the n row from the right or left of the x row

I’m trying to select the data from the left of a row.
Lets assume this table:

create table user (
   ID INT PRIMARY KEY AUTO_INCREMENT
);

The rows of this table look like that:

ID 
1
3
4
7
8
15
18
19

What I want to do, is to select data from the row which has ID = 15, to the 4th row from left of it, which has ID 3, how can I do that, without using BETWEEN in query.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What I want to do, is to select data from the row which has ID = 15, to the 4th row from left of it

SELECT *
FROM tablename
WHERE id < 15
ORDER BY id DESC LIMIT 4

If you need the 4th row only then use above querry as subquery, and in outer query use backward sorting + LIMIT 1.


If MySQL version is 8+ then use ROW_NUMBER() in CTE.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading