SQL - How to find the highest number in a column?
Solution 1:
You can do
SELECT MAX(ID) FROM Customers;
Solution 2:
If you've just inserted a record into the Customers table and you need the value of the recently populated ID field, you can use the SCOPE_IDENTITY
function. This is only useful when the INSERT
has occurred within the same scope as the call to SCOPE_IDENTITY
.
INSERT INTO Customers(ID, FirstName, LastName)
Values
(23, 'Bob', 'Smith')
SET @mostRecentId = SCOPE_IDENTITY()
This may or may not be useful for you, but it's a good technique to be aware of. It will also work with auto-generated columns.