markasoftware
markasoftware

Reputation: 12662

TOP and ORDER BY sql error

I am trying to select the last record from a table in MySQL using PHP. I believe I have an SQL error. Here is my SQL code:

SELECT TOP 1 id FROM `table` ORDER BY id DESC

If this is valid and I actually have a PHP error, tell me.

Upvotes: 28

Views: 82834

Answers (3)

Faizal R
Faizal R

Reputation: 19

This will work To find the last record if you are not looking to use limit

SELECT TOP 1 * FROM Products ORDER BY id desc

This will work To find the last record specifying column name if you are not looking to use limit

SELECT TOP 1 id FROM Products ORDER BY id desc

Else

SELECT * FROM Products ORDER BY id DESC LIMIT 1

Upvotes: 0

Zane Bien
Zane Bien

Reputation: 23125

A simpler and more DBMS-agnostic approach would be:

SELECT MAX(id) AS id
FROM table

That's only if you want just the id field, otherwise if you tried to SELECT other columns, it wouldn't return matching data to the id field and you would instead have to use:

SELECT id, otherfields, ..., ...
FROM table
WHERE id = (SELECT MAX(id) FROM table)

Upvotes: 12

John Woo
John Woo

Reputation: 263723

you have an invalid sql syntax. use LIMIT instead

try this:

SELECT id 
FROM table 
ORDER BY id DESC
LIMIT 1

the TOP clause works on MSSQL server.

Upvotes: 59

Related Questions