Let's say I have a simple table:
create table foo
{
id INTEGER PRIMARY KEY AUTOINCREMENT,
bar INTEGER
}
And I want to insert a new row, such that id == bar
where value for id
is chosen by the database, a.k.a. auto-increment.
Something like this:
INSERT INTO foo (id, bar) VALUES (NULL, id)
Is it possible do this in one statement?
What is the SQL syntax for that?
To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.
In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name. The name of the table whose AUTO_INCREMENT value you wish to change.
Syntax for MySQLMySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. VALUES ('Lars','Monsen'); The SQL statement above would insert a new record into the "Persons" table.
Select the first filled cell of the leftmost column in step-2, then, select the last intended cell of the rightmost column in step-3. All columns will be auto-filled at once by pressing 'Ctrl+D'. This is a very useful shortcut if you use excel a lot.
In SQLite you can
BEGIN TRANSACTION;
INSERT INTO foo (id, bar) VALUES (NULL, 0);
UPDATE foo SET bar = id WHERE _ROWID_ = last_insert_rowid();
COMMIT;
to make sure no other statement gets in the way of your two-statement expression.
You can't have two auto increment fields. You should use a single auto increment field. Given that both fields would always have the same value for every row, there's no reason to have to such fields anyway.
But you can just make trigger which will update another field equal to auto incremented value after inserting row. And delete that trigger when you don't want them to have same values.
CREATE TRIGGER update_foo AFTER INSERT ON foo
BEGIN
UPDATE foo SET bar = NEW.id ;
END;
When eventually bar will be changed to have not same value as id, then delete trigger
DROP TRIGGER update_foo
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