SELECT * FROM permlog WHERE id = ( SELECT MAX(id) FROM permlog ) ; This would return all rows with highest id , in case id column is not constrained to be unique.
If employee_id is an IDENTITY column and you are sure that rows aren't manually inserted out of order, you should be able to use this variation of your query to select the data in sequence, newest first: SELECT ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID DESC) AS ID, EMPLOYEE_ID, EMPLOYEE_NAME FROM dbo.
To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.
You can use ORDER BY clause or aggregate function MAX() to select the maximum value.
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
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)
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With