Ediolot
Ediolot

Reputation: 521

Sqlite get max id not working (?)

Im using this:

SELECT * 
WHERE id=MAX(id) 
FROM history;

But my query is empty. I have also tried this (This one works):

SELECT MAX(id) AS max_id 
FROM history;

But obviusly my query only contains the max_id key. What am I doing wrong with the first one?

Upvotes: 10

Views: 19809

Answers (3)

Satish Asok
Satish Asok

Reputation: 41

Actually most simple query to get the max value of a column in sqlite is:

select MAX(id) from table;

Upvotes: 4

Jonas
Jonas

Reputation: 193

SELECT top 1 FROM history ORDER BY id DESC

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

You need to add another level of select for the MAX, like this:

SELECT * 
WHERE id=(SELECT MAX(id) from history)
FROM history;

A better approach would be to order by id in descending order, and limit the output to a single row:

SELECT *
FROM history
ORDER BY id DESC
LIMIT 1

Upvotes: 32

Related Questions