How would I do something like this?
SQL SELECT row FROM table WHERE id=max(id)
You could use a subselect:
SELECT row
FROM table
WHERE id=(
SELECT max(id) FROM table
)
Note that if the value of max(id)
is not unique, multiple rows are returned.
If you only want one such row, use @MichaelMior's answer,
SELECT row from table ORDER BY id DESC LIMIT 1
id
is just a column in a table. There is no guarantee that the values in the id
column have to be unique.
id
is not a primary or unique key :) Given the name, there's a reasonable chance that it is. It's also worth noting that depending on the DBMS you're using, the approach with the subselect may be much less efficient.
Feb 7, 2014 at 16:25
id
could be a foreign key, in which case it may not be unique. I did some benchmarking using set profiling = 1; ...; show profiles
and it appears our solutions have the same performance using MySQL. For my own knowledge, do you know what DBMS has poorer performance for subselects?
You could also do
SELECT row FROM table ORDER BY id DESC LIMIT 1;
This will sort rows by their ID in descending order and return the first row. This is the same as returning the row with the maximum ID. This of course assumes that id
is unique among all rows. Otherwise there could be multiple rows with the maximum value for id
and you'll only get one.
SELECT *
FROM table
WHERE id = (SELECT MAX(id) FROM TABLE)
SELECT entry_time FROM users_unverified WHERE num_id = (SELECT MAX(num_id) FROM users_unverified WHERE account_email = :account_email)
whereby i just need the entry_time
of the most recent entry in the database. Is that statement sufficient or should it be: SELECT entry_time FROM users_unverified WHERE num_id = (SELECT MAX(num_id) FROM users_unverified) AND account_email = :account_email
You can not give order by
because order by
does a "full scan" on a table.
The following query is better:
SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table);
ORDER BY
will not do a full scan if you assume that id
is the primary key of the table. (And if it isn't, it's rather poorly named.) If it's not, how do you expect MAX(id)
to work without a full table scan? If there's no index, every value must still be checked to find the maximum.
May 4, 2015 at 21:47
One can always go for analytical functions as well which will give you more control
select tmp.row from ( select row, rank() over(partition by id order by id desc ) as rnk from table) tmp where tmp.rnk=1
If you face issue with rank() function depending on the type of data then one can choose from row_number() or dense_rank() too.
Try with this
SELECT top 1 id, Col2, row_number() over (order by id desc) FROM Table