How can I get the latest ID in a table?
If you mean the latest generated ID from an insert statement with an auto-increment column, then mysql_insert_id() should help ya out
SELECT max(id) FROM table
SELECT id FROM table ORDER BY id DESC LIMIT 1 should work as well
IF you've just inserted into a table with auto_increment you can run right after your query.
SELECT last_insert_id();
Otherwise the max(id) FROM table
If the table has an auto_increment column defined - you can check by looking for "auto_increment" in the output from DESC your_table, use:
mysql_insert_id
Otherwise, you have these options:
SELECT MAX(id) FROM your_table
SELECT id FROM your_table ORDER BY id LIMIT 1
If there are no inserts being done on a table, then SELECT MAX(ID) should be fine. However, every database has a built-in function to return the most recently created primary key of a table after an insert has been performed. If that's what you're after, don't use MAX().
http://www.iknowkungfoo.com/blog/index.cfm/2008/6/1/Please-stop-using-SELECT-MAX-id
Also, for the id of the last record inserted, if you're using MySQLi, it would look like this:
$mysqli->insert_id
http://php.net/manual/en/mysqli.insert-id.php
Related
How to receive the last row id in the database without generating a new row or updating the row.
Just to read the last id?
I have the function mysql_insert_id and need something like this, but without generating a new row.
SELECT MAX(id) AS latest_id
FROM table_name
If you instead want the comming (and not yet existing) id without inserting a row, see my previous answer.
You need to use max() function like
select max(yourcol) from yourtable
You can try lot of queries for that :-
select * from TABLE_NAME order by ID desc limit 1;
"or"
SELECT *
FROM TABLE
WHERE ID = (SELECT MAX(ID) FROM TABLE);
I'm currently using:
SELECT MAX(id) FROM table
To discover the current id of a certain table, but i heard this can bring bad results. What is the proper way of doing that? Please, notice that i'm not INSERTING or DELETING anything before that query. I just want to know the current ID, without prior INSERT or DELETE.
Perform the following SQL:
SHOW TABLE STATUS LIKE 'TABLENAME'
Then check field AUTO_INCREMENT
You can use the following query:
SELECT id FROM table ORDER BY id DESC LIMIT 1;
I am trying to update fields in my DB, but got stuck with such a simple problem: I want to update just one row in the table with the biggest id number. I would do something like that:
UPDATE table SET name='test_name' WHERE id = max(id)
Unfortunatelly it doesnt work. Any ideas?
Table Structure
id | name
---|------
1 | ghost
2 | fox
3 | ghost
I want to update only last row because ID number is the greatest one.
The use of MAX() is not possible at this position. But you can do this:
UPDATE table SET name='test_name' ORDER BY id DESC LIMIT 1;
For multiple table, as #Euthyphro question, use table.column.
The error indicates that column id is ambiguous.
Example :
UPDATE table1 as t1
LEFT JOIN table2 as t2
ON t2.id = t1.colref_t2
SET t1.name = nameref_t2
ORDER BY t1.id DESC
LIMIT 1
UPDATE table SET name='test_name' WHERE id = (SELECT max(id) FROM table)
This query will return an error as you can not do a SELECT subquery from the same table you're updating.
Try using this:
UPDATE table SET name='test_name' WHERE id = (
SELECT uid FROM (
SELECT MAX(id) FROM table AS t
) AS tmp
)
This creates a temporary table, which allows using same table for UPDATE and SELECT, but at the cost of performance.
I think iblue's method is probably your best bet; but another solution might be to set the result as a variable, then use that variable in your UPDATE statement.
SET #max = (SELECT max(`id`) FROM `table`);
UPDATE `table` SET `name` = "FOO" WHERE `id` = #max;
This could come in handy if you're expecting to be running multiple queries with the same ID, but its not really ideal to run two queries if you're only performing one update operation.
UPDATE table_NAME
SET COLUMN_NAME='COLUMN_VALUE'
ORDER BY ID
DESC LIMIT 1;
Because you can't use SELECT IN DELETE OR UPDATE CLAUSE.ORDER BY ID DESC LIMIT 1. This gives you ID's which have maximum value MAX(ID) like you tried to do. But MAX(ID) will not work.
Old Question, but for anyone coming across this you might also be able to do this:
UPDATE
`table_name` a
JOIN (SELECT MAX(`id`) AS `maxid` FROM `table_name`) b ON (b.`maxid` = a.`id`)
SET a.`name` = 'test_name';
We can update the record using max() function and maybe it will help for you.
UPDATE MainTable
SET [Date] = GETDATE()
where [ID] = (SELECT MAX([ID]) FROM MainTable)
It will work the perfect for me.
I have to update a table with consecutive numbers.
This is how i do.
UPDATE pos_facturaciondian fdu
SET fdu.idfacturacompra = '".$resultado["afectados"]."',
fdu.fechacreacion = '".$fechacreacion."'
WHERE idfacturaciondian =
(
SELECT min(idfacturaciondian) FROM
(
SELECT *
FROM pos_facturaciondian fds
WHERE fds.idfacturacompra = ''
ORDER BY fds.idfacturaciondian
) as idfacturaciondian
)
Using PHP I tend to do run a mysqli_num_rows then put the result into a variable, then do an UPDATE statement saying where ID = the newly created variable. Some people have posted there is no need to use LIMIT 1 on the end however I like to do this as it doesn't cause any trivial delay but could prevent any unforeseen actions from being taken.
If you have only just inserted the row you can use PHP's mysqli_insert_id function to return this id automatically to you without needing to run the mysqli_num_rows query.
Select the max id first, then update.
UPDATE table SET name='test_name' WHERE id = (SELECT max(id) FROM table)
I am trying to perform a SQL query that acts in two parts.
First, I have a query that returns a list of 10 Ids.
But then I want to have a SELECT statement which has a WHERE clause for each of these 10 ids.
Is this possible?
I tried:
SELECT * FROM tablenameWHERE id= (SELECT id FROM table_of_ids WHERE
tableid='1a177de1-3f25c9b7910b' OR
tableid='64faecca-133af807a65a' OR
... up to 10 Ids)
but it returns with an error stating the subquery returns more than 1 row.
Note, the tableid and id columns of table_of_ids are different values.
Does anyone know how to accomplish this?
I seem to be at a loss myself.
If it matters, I am using mySQL and PHP.
Cheers,
Brett
Not a very optimized query, but you could use IN instead of =
SELECT * FROM tablename WHERE id IN (SELECT id FROM table_of_ids WHERE
tableid='1a177de1-3f25c9b7910b' OR
tableid='64faecca-133af807a65a' OR
... up to 10 Ids)
Change it to in()
WHERE id IN (SELECT id ...)
Replace the = with the IN keyword.
select * from sometable where key in (subselect that returns one column)
Looks like you can;
SELECT *
FROM tablename
INNER JOIN table_of_ids ON table_of_ids.id = tablename.id
WHERE table_of_ids.tableid IN (
'1a177de1-3f25c9b7910b',
'64faecca-133af807a65a',
... )
Don't use the "=" operator, use the "IN" operator.
See this tutorial for examples.
Use IN keyword.
SELECT * FROM user WHERE Id IN(SELECT userId FROM table).
Id is primary key of your first table and userId is foreign key in second table of coz.
I need to get next id from table (auto_increment).
I could just use SELECT * from table ORDER BY id DESC LIMIT 1;
For example I get 50. But if we delete from table two items I will get 48 but correct one
will be 51. How get correct value even we something delete from table ?
You can only use SHOW TABLE STATUS LIKE 'tablename' to fetch the auto_increment value. A simpler solution might be: SELECT MAX(id) + 1 FROM table, but this is buggy if the last entry was deleted.
show table status like 'table_name'
next id value is in 'Auto_increment' field
SHOW TABLE STATUS LIKE 'table'
The value you want is in the Auto_increment field.
Be careful about concurrency though: by the time you get around to using this value, some other client could have inserted into the table and thus your value is out of date. It's usually best to try to not need this.
SELECT LAST_INSERT_ID() + 1;
gets the last ID used in an insert in an autoincrement column + 1
I see two solutions for the next ID:
1) Select bigger value of a column with max function. Example: select max( id ) from table;
2) Using the command SHOW STATUS LIKE and get the correct index of array. Take a look: http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html
Seems to me you're creating a race condition here.
Why exactly can you not insert the row you want to insert and then use LAST_INSERT_ID() to find it's ID?