Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first/top row of the table in Sqlite via Sql Query

Tags:

sql

sqlite

I need to fetch the first/top row of a table in a Sqlite database.

But my program throws an SQLException "Sqlite Syntax Error: Syntax error near '1' " for the query that I am using:

SELECT TOP 1 * 
FROM SAMPLE_TABLE

That I guess is a syntax particularly for MS SQL SERVER and MS ACCESS. Right now I am using.

SELECT *
FROM SAMPLE_TABLE
LIMIT 1

What is the best solution for this problem?

like image 512
Omayr Avatar asked Mar 23 '11 16:03

Omayr


People also ask

How do I get the first row in a query?

To get the first row use LIMIT 1 . To get the 2nd row you can use limit with an offset: LIMIT 1, 1 . To get the last row invert the order (change ASC to DESC or vice versa) then use LIMIT 1 .


2 Answers

Use the following query:

SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1

Note: Sqlite's row id references are detailed here.

like image 113
Achim Avatar answered Sep 25 '22 19:09

Achim


LIMIT 1 is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order clause in an outer query).

like image 29
Jordan Parmer Avatar answered Sep 22 '22 19:09

Jordan Parmer