Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TOP and ORDER BY sql error

Tags:

sql

mysql

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.

like image 309
markasoftware Avatar asked Jun 18 '12 03:06

markasoftware


People also ask

Why ORDER BY does not work in subquery?

An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery. Subqueries that return more than one row can only be used with multiple value operators such as the IN operator.

What can I use instead of top in SQL?

There is an alternative to TOP clause, which is to use ROWCOUNT. Use ROWCOUNT with care, as it can lead you into all sorts of problems if it's not turned off.

Why do we use ORDER BY 1 in SQL?

it simply means sorting the view or table by 1st column of the query's result.


2 Answers

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.

like image 50
John Woo Avatar answered Oct 15 '22 20:10

John Woo


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) 
like image 36
Zane Bien Avatar answered Oct 15 '22 19:10

Zane Bien