Please help me to write an SQL query in the Oracle database. There is table called tbl and it has 12 rows. I want to select first 4 rows first then next 4 and the last 4 rows.
Can any anyone tell me how can I do this in Informix.
EDIT: now should be fixed with 3-level select:
select * from (
select q1.*, rownum as rn from ( --get correct rownum
select * from tbl order by column --get correct order
) q1
) q2
where q2.rn between 1 and 4; -- filter
for first part.
For second and third part:
where q2.rn between 5 and 8
where q2.rn between 9 and 12
There is nothing called as first rows, last rows, "n" rows unless you explicitly specify an ORDER BY and then select the required rows.
Top-n Row Limiting feature in Oracle 12c
on ward:
SQL> select * from order_test order by val;
VAL
----------
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
10
20 rows selected.
First 4 rows :
SQL> SELECT val
2 FROM order_test
3 ORDER BY VAL
4 FETCH FIRST 4 ROWS ONLY;
VAL
----------
1
1
2
2
Next 4 rows(look at OFFSET) :
SQL> SELECT val
2 FROM order_test
3 ORDER BY VAL
4 OFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY;
VAL
----------
3
3
4
4
Finally, next 4 rows with OFFSET 8 rows :
SQL> SELECT val
2 FROM order_test
3 ORDER BY VAL
4 OFFSET 8 ROWS FETCH NEXT 4 ROWS ONLY;
VAL
----------
5
5
6
6
You can use rownum
:
select * from (select t.*, rownum rn from tbl t) where rn between 1 and 4;
/
select * from (select t.*, rownum rn from tbl t) where rn between 5 and 8;
/
select * from (select t.*, rownum rn from tbl t) where rn between 9 and 12;
/
If you're using order by
clause then use row_number()
(documentation)
select * from (select t.*, row_number() over (order by column_name) rn from tbl t) where rn between 1 and 4;
/
select * from (select t.*, row_number() over (order by column_name) rn from tbl t) where rn between 5 and 8;
/
select * from (select t.*, row_number() over (order by column_name) rn from tbl t) where rn between 9 and 12;
/