VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
INSERT writes it. From here on a statement
changes what is in the table, so the rest of the tutorial works in a database
of its own rather than in the sample data.
A practice database
Sakila is the reference every reading lesson describes, so leave it alone. Make a small database beside it instead, and run this again whenever you want to start over.mysql -u root -p sakila_practice before you start, and run the block again
between lessons.
How INSERT works
TABLE_NAME with the table you are writing to, COLUMN_LIST with the
columns you are supplying, and VALUE_LIST with 1 value for each of those
columns, in the same order.
The server adds a row and reports how many it wrote. It prints no rows back,
so a SELECT afterwards is how you see the result.
Examples
1) Add a row
Query OK and 1 row affected is the whole report. Ask for the table to see
what landed.
member_id counted itself up
because the column is AUTO_INCREMENT, and active took the DEFAULT 1 the
table declares.
2) Read back the id the server chose
AnAUTO_INCREMENT value is decided during the insert, so the only way to
learn it is to ask. Ask in the same session that did the insert.
LAST_INSERT_ID() answers for your connection alone, so a busy server cannot
hand you another session’s id. A fresh connection has no answer to give and
returns 0.
ERROR 1062 means the row is already there
AUNIQUE column refuses a second row carrying a value it already holds. Here
email is unique, and Mary Smith’s address is taken.
ERROR 1364 means a required column is missing
Leave out a column that isNOT NULL and has no default, and the server has
nothing to write.
DESCRIBE member; and supply everything marked NO under
Null that has no default.
A column that accepts NULL is a different case. Leave it out and the row gets
NULL.
A duplicate key still uses up an id
Ask for the ids now and 6 is missing.ERROR 1364 attempt took nothing, because it was refused
before it reached the table. Gaps like this are normal and mean nothing is
lost. Treat the column as an identifier, never as a count of the rows or as a
promise that the numbers run without a break.
Summary
- Write
INSERT INTO table (columns) VALUES (values)to add a row. - Expect a count of rows written rather than the row itself.
- Leave out a column with a default or
AUTO_INCREMENTand let the server fill it. - Read
ERROR 1062as a value aUNIQUEcolumn already holds. - Read
ERROR 1364as a required column you did not supply. - Expect gaps in an
AUTO_INCREMENTcolumn, because a duplicate-key failure keeps its number.
See also
- Insert multiple rows — 1 statement, many rows
- INSERT SELECT — rows from a query rather than typed out
- Upsert — insert, or update the row that is in the way
- UPDATE — changing a row that is already there

