INSERT is an SQL command for inserting data into a table in a (relational) database. Here is an example:
INSERT INTO example (nickname, firstname, lastname, age) VALUES ('hax0r', 'John', 'Doe', 17)
The statement above tells the database to add one row to the table called
example. The field
nickname is given the value
'hax0r' (a string) and so on.
INSERT INTO example (nickname, firstname, lastname) SELECT username, firstname, lastname FROM users
As the example above shows, it is also possible to use a SELECT statement to get data to insert. In this case, multiple rows can be inserted by one INSERT statement.
It is possible to only give values to some of the fields in the table. For each of the unmentioned fields the following rules apply:
- If there is a default value for the field specified in the table definition, then the field will get that value.
- Otherwise, if the field allows NULL values, it will be set to NULL.
- Otherwise, the insert fails.
There are other reasons an insert may fail:
- There is a primary key or a unique index defined on one or more of the fields, and there is already a row in the table with the same values as the row that is about to be inserted. See also: Key violation
- There are one ore more foreign keys defined on one or more of the fields, and there is no record with the specified key in the referenced table.
- The user does not have permission to insert data into the table.
- The table is full and is not allowed to grow.