50

Let's say I have the following data in the Customers table: (nothing more)

ID   FirstName   LastName
-------------------------------
20   John        Mackenzie
21   Ted         Green
22   Marcy       Nate

What sort of SELECT statement can get me the number 22, in the ID column?

I need to do something like this to generate a unique ID. Sure I can let the system do this via auto-increment, but then how would I get the auto generated ID?

I thought of SELECT ID FROM Customers and counting the rows returned but this seems horribly inefficient, and in this case, it will incorrectly return "3", though I need a unique ID of 23.

10
  • Great point, but their answers don't directly answer my question. My method is safest anyways since I get a free ID and THEN add a record. Of course you could say concurrent operations could mess this up by multiple programs getting the same "free" ID and reusing it ... but this can be prevented by adding a record super quick after getting a free ID. Oct 10, 2009 at 7:42
  • msaeed and some others anwser your question exactly. Question being "SQL - How to find the highest number in a column?" and "What sort of SELECT statement can get me the number 22, in the ID column?". Correct your post to make clearer your intentions.
    – Liao
    Oct 10, 2009 at 7:55
  • Nope. I wasn't even talking about those answers, only the ones rexem pointed out. The other answers talk of inserting THEN getting the ID, which is clearly not what I asked for. I asked for 22 (max number), not 23 (recently populated ID). Oct 10, 2009 at 9:24
  • 2
    @Jeremy: No, as Brisbe42 explained your method is not safe because the database isolation level can be set to allow for reading data prior to INSERT/UPDATE commits. Should you run into errors regarding attempting to insert a non-unique primary key, I hope you remember this question.
    – OMG Ponies
    Oct 10, 2009 at 16:01
  • 3
    @Jeremy, you would be unwise to depend on your "super quick" method. Programs should be deterministic in nature otherwise they're provably incorrect. What you doing is throwing away the A from your ACID principles. If you're running a single-user database app, that's fine. Every other case should use atomic operations.
    – paxdiablo
    Oct 12, 2009 at 5:18

16 Answers 16

111

You can do

SELECT MAX(ID) FROM Customers;
17

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.

0
12
SELECT * FROM Customers ORDER BY ID DESC LIMIT 1

Then get the ID.

8
select max(id) from customers
8

To get it at any time, you can do SELECT MAX(Id) FROM Customers .

In the procedure you add it in, however, you can also make use of SCOPE_IDENTITY -- to get the id last added by that procedure.
This is safer, because it will guarantee you get your Id--just in case others are being added to the database at the same time.

7

If you're talking MS SQL, here's the most efficient way. This retrieves the current identity seed from a table based on whatever column is the identity.

select IDENT_CURRENT('TableName') as LastIdentity

Using MAX(id) is more generic, but for example I have an table with 400 million rows that takes 2 minutes to get the MAX(id). IDENT_CURRENT is nearly instantaneous...

3
  • 1
    I'll have to commit this one to memory. Good stuff. Oct 10, 2009 at 18:44
  • 1
    Really? Two minutes? Do you have an index on id? It should be near instantaneous to find min or max, even with 400 million rows.
    – paxdiablo
    Oct 12, 2009 at 5:19
  • It is a non-unique, non-clustered index on the 'identity'... not sure that's correct design for the app, but it is what it is. SQL 2005 Enterprise with a partion scheme too
    – Damon
    Oct 12, 2009 at 15:32
6
select max(id) from Customers 
4

If you are using AUTOINCREMENT, use:

SELECT LAST\_INSERT\_ID();

Assumming that you are using Mysql: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Postgres handles this similarly via the currval(sequence_name) function.

Note that using MAX(ID) is not safe, unless you lock the table, since it's possible (in a simplified case) to have another insert that occurs before you call MAX(ID) and you lose the id of the first insert. The functions above are session based so if another session inserts you still get the ID that you inserted.

1
  • Using insert with a subselect makes the max(id) safe, see my answer. But, in all honesty, autoincrement is a better choice if it's available and you're not too concerned about portability.
    – paxdiablo
    Oct 10, 2009 at 6:54
2

If you're not using auto-incrementing fields, you can achieve a similar result with something like the following:

insert into Customers (ID, FirstName, LastName)
    select max(ID)+1, 'Barack', 'Obama' from Customers;

This will ensure there's no chance of a race condition which could be caused by someone else inserting into the table between your extraction of the maximum ID and your insertion of the new record.

This is using standard SQL, there are no doubt better ways to achieve it with specific DBMS' but they're not necessarily portable (something we take very seriously in our shop).

2

You can also use relational algebra. A bit lengthy procedure, but here it is just to understand how MAX() works:

E := πID (Table_Name)
E1 := πIDID >= ID' ((ρID' E) ⋈ E)) – πIDID < ID’ ((ρID' E) ⋈ E))

Your answer: Table_Name ⋈ E1

Basically what you do is subtract set of ordered relation(a,b) in which a<b from A where a, b ∈ A.

For relation algebra symbols see: Relational algebra From Wikipedia

1
  • 8
    I don't think relational algebra solutions will be well received for SQL questions. Jan 24, 2013 at 17:52
2

Here's how I would make the next ID:

INSERT INTO table_name (
            ID,
            FIRSTNAME,
            SURNAME) 
            VALUES ((( 
                    SELECT COALESCE(MAX(B.ID)+1,1) AS NEXTID 
                        FROM table_name B
                        )), John2, Smith2);

With this you can make sure that even if the table ID is NULL, it will still work perfectly.

0

Depends on what SQL implementation you are using. Both MySQL and SQLite, for example, have ways to get last insert id. In fact, if you're using PHP, there's even a nifty function for exactly that mysql_insert_id().

You should probably look to use this MySQL feature instead of looking at all the rows just to get the biggest insert ID. If your table gets big, that could become very inefficient.

0

If you want to just select the id use select max(id) from customer.

If you want to select the entire row then use a query like this:

select c1.*
from customer c1, (select max(id) as max_id from customer )c2 
where c1.id=c2.max_id

c2 is an alias for the new temporary table which contains max id. Then its cross product is taken with customer table to get the entire row.

Here we are writing a query in the from clause, which can often be quite useful.

0

To find the next (still not used) auto-increment, I am using this function for somewhat years now.

public function getNewAI($table)
    {
        $newAI = false;

        $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
        if(mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        $sql = "SHOW TABLE STATUS LIKE '".$table."'";

        $result = $mysqli->query($sql);

        if($result) {
            $row = $result->fetch_assoc();

            $newAI = $row['Auto_increment'];
        }
        $mysqli->close();

        return $newAI;
    }
-1
select * from tablename order by ID DESC

that will give you row with id 22

1
  • 1
    This will return all rows; with the correct one at the "top" of the result-set. It will not return solely the row with the maximum id.
    – Ben
    Aug 23, 2012 at 7:07
-1

In PHP:

$sql = mysql_query("select id from customers order by id desc");
$rs = mysql_fetch_array($sql);
if ( !$rs ) { $newid = 1; } else { $newid = $rs[newid]+1; }

thus $newid = 23 if last record in column id was 22.

1
  • 1
    This is a question about SQL. May 31, 2017 at 6:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.