I have a MYSQL statement which inserts data into a row. The row id would be automatically incremented.
But how do I get back that row of data which got inserted and executed? That row of data should includes the row id which I no idea of what that is..
I want the whole row $row, not just the id. I don't know the id because it's autoincremented.
Since you have an autoincremented id you can use LAST_INSERT_ID()
E.g.
INSERT INTO supportContacts
(type, details)
VALUES
('Twitter', '#sqlfiddle');
SELECT * FROM
supportContacts
WHERE id = LAST_INSERT_ID();
DEMO
If you have an auto-incrementing column for the id, the following will work in any database:
select *
from table
where id = (select max(id) from table)
Under the assumption that no one else is inserting rows.
In SQL Server, you can do the following:
declare #id int;
insert . . .
select #id = ##Identity;
select *
from table
where id = #id;
Just note that the line with ##Identity needs to follow immediately after the insert.
Related
I want to get the value of the last id insert in a table. How i can do this in mysql?
For eg : in db2 we have
SET var_ID = (SELECT ID FROM NEW TABLE (INSERT INTO val_CLIENT(E_VER, NAME, TYPE) VALUES(0, val_NAME, 502)));
The above statement needs to be converted into mysql. How can i do this?
You can use the LAST_INSERT_ID() function.
Do your insert statement:
INSERT INTO val_CLIENT(E_VER, NAME, TYPE) VALUES(0, val_NAME, 502);
Depending if you're doing it in a stored procedure, you will have to modify this, but if you're looking to select it.
SELECT LAST_INSERT_ID() AS `ID`;
To store it as a variable, you can use the SET statement.
SET #VarID = (SELECT LAST_INSERT_ID());
If your ID column is of type AUTO_INCREMENT, Use LAST_INSERT_ID() after the INSERT statement
SELECT LAST_INSERT_ID() as ID
However, for concurrent requests using same connection, this will lead into inconsistent result. In that case, the following query is a safe bet:
SELECT ID FROM val_CLIENT
ORDER BY ID DESC
LIMIT 1
A possible query:
SELECT id FROM tableORDER BY id DESC LIMIT 1
how can i get the ID of the last insert statement
im using trigger to create a ID for every record
INSERT INTO table1_seqdocument VALUES (NULL);
SET NEW.tracknum = CONCAT('DOC', LPAD(LAST_INSERT_ID(), 3, '0'));
and i need that ID for other table
this is this my insert statement
INSERT INTO tble_transaction
(
tracknum
,signatoryid
,signed
,status
,signatorylevel
)
VALUES
(?,?,?,?,? )
what i want is to retrieve the ID and use it for another insert statement but using other table. is it possible? thank you
You can use ##identity
SELECT ##IDENTITY AS [##IDENTITY];
LAST_INSERT_ID() can only tell you the ID of the most recently auto-generated ID for that entire database connection, not for each individual table, which is also why the query should only read SELECT LAST_INSERT_ID() - without specifying a table. As soon as you fire off another INSERT query on that connection, it gets overwritten. If you want the generated ID when you insert to some table, you must run SELECT LAST_INSERT_ID() immediately after doing that (or use some API function which does this for you).
If you want the newest ID currently in an arbitrary table, you have to do a SELECT MAX(id) on that table, where id is the name of your ID column. However, this is not necessarily the most recently generated ID, in case that row has been deleted, nor is it necessarily one generated from your connection, in case another connection manages to perform an INSERT between your own INSERT and your selection of the ID.
(For the record, your query actually returns N rows containing the most recently generated ID on that database connection, where N is the number of rows in table1.)
In Mysql I am inserting a row with Insert command in a table of mysql , now I want the Id of last row Inserted , I am using
SELECT LAST_INSERT_ID() ;
But it gives me 0 as output every time .
Please help me in this.
LAST_INSERT_ID() only returns values that have been auto-generated by the MySQL server for an AUTO_INCREMENT column; when you insert a specific value, no auto-generation takes place and no value will be returned by LAST_INSERT_ID().
You could assign a value to LAST_INSERT_ID yourself:
INSERT INTO table (uuid) VALUES (LAST_INSERT_ID(12345));
LAST_INSERT_ID(value) assigns value to be returned by subsequent calls to LAST_INSERT_ID(), and returns that same value. Unfortunately, this only works for integer values, and will not be useful with UUIDs.
Why would you want to select something that is not autogenerated by insert, but passed to it? The reason is that you are using UUID() in the insert statement. I'd suggest you first to select the UUID, and then pass it to the insert
SELECT #id := UUID();
INSERT INTO tablename(id, value) VALUES(#id, somevalue)
you are assigning autoincrement an uuid this is what you are doing wrong
autoincrement field will be inserted automatically
other than that you will be getting 0 result in LAST_INSERT_ID()
First you have to use one auto incremented line.
if you are using php then use this method :
$foo = mysql_insert_id();
take a look http://php.net/manual/en/function.mysql-insert-id.php
in c# i use like this:
connection.Open();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.Connection = connection;
cmd.CommandText = "INSERT INTO o_test(game_id, user_id, date) values(?game_id, ?uid, ?date)";
cmd.Prepare();
cmd.Parameters.AddWithValue("?game_id", null);
cmd.Parameters.AddWithValue("?uid", words[1]);
cmd.Parameters.AddWithValue("?date", words[2]);
cmd.ExecuteNonQuery();
int game_id;
cmd.Parameters.Add(new MySqlParameter("newId", cmd.LastInsertedId));
game_id = Convert.ToInt32(cmd.Parameters["#newId"].Value);
If you want to select all columns from the last inserted id, you can go that way:
SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table)
SELECT LAST_INSERT_ID() as id FROM table1
Why does this query sometimes return the last inserted id of another table other than table1?
I call it in Node.js (db-mysql plugin) and I can only do queries.
LAST_INSERT_ID() can only tell you the ID of the most recently auto-generated ID for that entire database connection, not for each individual table, which is also why the query should only read SELECT LAST_INSERT_ID() - without specifying a table.
As soon as you fire off another INSERT query on that connection, it gets overwritten. If you want the generated ID when you insert to some table, you must run SELECT LAST_INSERT_ID() immediately after doing that (or use some API function which does this for you).
If you want the newest ID currently in an arbitrary table, you have to do a SELECT MAX(id) on that table, where id is the name of your ID column. However, this is not necessarily the most recently generated ID, in case that row has been deleted, nor is it necessarily one generated from your connection, in case another connection manages to perform an INSERT between your own INSERT and your selection of the ID.
(For the record, your query actually returns N rows containing the most recently generated ID on that database connection, where N is the number of rows in table1.)
SELECT id FROM tableName ORDER BY id DESC LIMIT 1
I usually select the auto-incremented ID field, order by the field descending and limit results to 1. For example, in a wordpress database I can get the last ID of the wp_options table by doing:
SELECT option_id FROM wp_options ORDER BY option_id DESC LIMIT 1;
Hope that helps.
Edit - It may make sense to lock the table to avoid updates to the table which may result in an incorrect ID returned.
LOCK TABLES wp_options READ;
SELECT option_id FROM wp_options ORDER BY option_id DESC LIMIT 1;
Try this. This is working
select (auto_increment-1) as lastId
from information_schema.tables
where table_name = 'tableName'
and table_schema = 'dbName'
Most easy way:
select max(id) from table_name;
I only use auto_increment in MySQL or identity(1,1) in SQL Server if I know I'll never care about the generated id.
select last_insert_id() is the easy way out, but dangerous.
A way to handle correlative ids is to store them in a util table, something like:
create table correlatives(
last_correlative_used int not null,
table_identifier varchar(5) not null unique
);
You can also create a stored procedure to generate and return the next id of X table
drop procedure if exists next_correlative;
DELIMITER //
create procedure next_correlative(
in in_table_identifier varchar(5)
)
BEGIN
declare next_correlative int default 1;
select last_correlative_used+1 into next_correlative from correlatives where table_identifier = in_table_identifier;
update correlatives set last_correlative_used = next_correlative where table_identifier = in_table_identifier;
select next_correlative from dual;
END //
DELIMITER ;
To use it
call next_correlative('SALES');
This allows you to reserve ids before inserting a record. Sometimes you want to display the next id in a form before completing the insertion and helps to isolate it from other calls.
Here's a test script to mess around with:
create database testids;
use testids;
create table correlatives(
last_correlative_used int not null,
table_identifier varchar(5) not null unique
);
insert into correlatives values(1, 'SALES');
drop procedure if exists next_correlative;
DELIMITER //
create procedure next_correlative(
in in_table_identifier varchar(5)
)
BEGIN
declare next_correlative int default 1;
select last_correlative_used+1 into next_correlative from correlatives where table_identifier = in_table_identifier;
update correlatives set last_correlative_used = next_correlative where table_identifier = in_table_identifier;
select next_correlative from dual;
END //
DELIMITER ;
call next_correlative('SALES');
If you want to use these workarounds:
SELECT id FROM tableName ORDER BY id DESC LIMIT 1
SELECT MAX(id) FROM tableName
It's recommended to use a where clause after inserting rows. Without this you are going to have inconsistency issues.
in my table inv_id is auto increment
for my purpose this is worked
select `inv_id` from `tbl_invoice`ORDER BY `inv_id` DESC LIMIT 1;
I'm trying to retrieve the id of one table A to insert into another table B. I cannot use last_insert_id() as i have not inserted anything into A. Any ideas on how to do this nicely?
$n = mysql_query("SELECT max(id) FROM tablename"); doesn't seem to work, nor does
$n = mysql_query("SELECT max(id) FROM tablename GROUP BY id");
In MySQL, this does return the highest value from the id column:
SELECT MAX(id) FROM tablename;
However, this does not put that id into $n:
$n = mysql_query("SELECT max(id) FROM tablename");
To get the value, you need to do this:
$result = mysql_query("SELECT max(id) FROM tablename");
if (!$result) {
die('Could not query:' . mysql_error());
}
$id = mysql_result($result, 0, 'id');
If you want to get the last insert ID from A, and insert it into B, you can do it with one command:
INSERT INTO B (col) SELECT MAX(id) FROM A;
You could descendingly order the tabele by id and limit the number of results to one:
SELECT id FROM tablename ORDER BY id DESC LIMIT 1
BUT: ORDER BY rearranges the entire table for this request. So if you have a lot of data and you need to repeat this operation several times, I would not recommend this solution.
I have different solution:
SELECT AUTO_INCREMENT - 1 as CurrentId FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbname' AND TABLE_NAME = 'tablename'
You can get maximum column value and increment it:
InnoDB uses the following algorithm to
initialize the auto-increment counter
for a table t that contains an
AUTO_INCREMENT column named ai_col:
After a server startup, for the first
insert into a table t, InnoDB executes
the equivalent of this statement:
SELECT MAX(ai_col) FROM t FOR UPDATE;
InnoDB increments by one the value
retrieved by the statement and assigns
it to the column and to the
auto-increment counter for the table.
If the table is empty, InnoDB uses the
value 1.
Also you can use SHOW TABLE STATUS and its "Auto_increment" value.
I think to add timestamp to every record and get the latest. In this situation you can get any ids, pack rows and other ops.