How to select 1st, 3rd, 11th and nth row from a table?
Asked
Active
Viewed 5,606 times
1
-
1Some additional info would be helpful. Does the table have a primary key that is properly seeded? If so that is all you need to use. – shookdiesel Aug 16 '10 at 11:38
-
And you need it to work in both sqllite and mysql? If not which one? – Martin Smith Aug 16 '10 at 11:45
-
keep in mind, this is not a talk about best practices, the reason for this type of selection is not for a list. – Timo Huovinen Sep 02 '10 at 20:45
-
just one: http://stackoverflow.com/questions/3419626/sqlite3-or-general-sql-retrieve-nth-row-of-a-query-result – Ciro Santilli OurBigBook.com Dec 06 '15 at 10:40
4 Answers
2
First of all, you should never ever rely on the order of the rows in your database. Rows have no natural ordering. However, you can add an attribute (unsigned int with auto increment, for instance) which indicates the order of the rows. Be sure that whenever the table is edited, the field is updated accordingly.
You can now select the first, third and eleventh row
SELECT * FROM table t
WHERE t.order IN (1, 3, 11)
ORDER BY t.order ASC;

Martijn
- 5,471
- 4
- 37
- 50
2
For MySQL
SET @rows_count = NULL;
select col_list,rn from
(
select col_list, @rows_count := IFNULL(@rows_count, 0) + 1 as rn
from table_name
order by col_list
limit 11) top_n
WHERE rn IN (1,3,11)

Martin Smith
- 438,706
- 87
- 741
- 845
1
If there is a primary key defined for the table that is an integer based data type--both MySQL and SQLite have auto_increment for example--then you can use:
SELECT t.*
FROM TABLE t
WHERE t.id IN (1,3, 11)
...where id
is the auto_increment column.
There's very little detail to go on, but MySQL and SQLite do not have analytic query support, making queries rather complicated:
SELECT y.*
FROM (SELECT t.*,
(SELECT COUNT(*)
FROM TABLE x
WHERE x.col <= t.col) AS rank
FROM TABLE t) y
WHERE y.rank IN (1, 3, 11)

OMG Ponies
- 325,700
- 82
- 523
- 502
-
haven't checked on actual server, but I get the idea behind it and that there is no select separate row support in mysql or sqlite. this answer has both answer + alternative option. – Timo Huovinen Aug 16 '10 at 12:32
0
try this way
Select *
From ( Select Row_Number() OVER (Order by empno) rno,
e.* From scott.emp e )
Where rno in (1, 3, 11)

Mukesh Kalgude
- 4,814
- 2
- 17
- 32

Art
- 31
- 1