views:

116

answers:

3

How to select 1st, 3rd, 11th and nth row from a table?

+2  A: 

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
use-full, thanks.
YuriKolovsky
+1  A: 

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
so fancy and complicated :P
YuriKolovsky
A: 

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
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.
YuriKolovsky
@Downvoter: It'd be nice to know why
OMG Ponies