richie
richie

Reputation: 18648

Fetch first 5 and last 5 records through a single statement

I am working on python sqlite3.

This statement gets records 5 - 14;

SELECT * FROM something LIMIT 5, 10;

But how do I get, lets say the first five and last five records through a single statement?

Upvotes: 2

Views: 573

Answers (2)

Hamidreza
Hamidreza

Reputation: 3128

Maybe the better way is using rowid in your order by clause to get the first and last rows based on inserting the rows:

select test from
(select test,rowid from table1 order by rowid asc limit 0,5)t1
union all
select test from
(select test,rowid from table1 order by rowid desc limit 0,5)t2;

Here is a sample in SQL Fiddle

Upvotes: 1

Ravi Dhoriya ツ
Ravi Dhoriya ツ

Reputation: 4414

You can combine output of two select statement like this:

(SELECT * FROM `something` order by some_column_name
limit 0,5)
union
(SELECT * FROM `something` order by some_column_name desc
limit 0,5
)

Specify some ordering of rows, so that it will select rows accordingly.

Upvotes: 8

Related Questions