Database Reference
In-Depth Information
The Syntax
The
INSERT
statementadds rows of data into a table. It can add a single row or multiple
rows at a time. The basic syntax of this SQL statement is:
INSERT INTO
table
[(
column
, …)]
VALUES (
value
, …), (…), …;
The keywords
INSERT INTO
are followed by the name of the table and an optional list of
columns in parentheses. (Square brackets in asyntax indicate that the bracketed material is
optional.) Then comes the keyword
VALUES
and apair of parentheses containing a list of
values for each column. There are several deviations of the syntax, but this is the basic one.
Commas separate the column names within the first list, and the values within the second.
Let's go through some examples that will show a few of the simpler syntaxes for the
INSERT
statement. Don't try to enter these on your system. These are generic examples
using
INSERT
to add data to nonexistent tables.
Here's a generic example of the
INSERT
statement with the minimum required syntax:
INSERT INTO
books
VALUES
(
'The Big Sleep'
,
'Raymond Chandler'
,
'1934'
);
This example adds text to a table called
books
. This table happens to contain only three
columns, so we don't bother to list the columns. But because there are three columns, we
have to specify three values, which will go into the columns in the order that the columns
were defined in
CREATE TABLE
. So in our example,
The Big Sleep
will be inserted into
the first column of the table,
Raymond Chandler
will go into the second column, and
1934
will go into the third.
For columns that have a default value set, you can rely on the server to use that value and
omit the column from your
INSERT
statement. One way to do this is by entering avalue of
DEFAULT
orNULL, as shown in the following example:
INSERT INTO
books
VALUES
(
'The Thirty-Nine Steps'
,
'John Buchan'
,
DEFAULT
);
MySQL will use the default value for the third column. If the default value is NULL — the
usual default value if none is specified — that's what the statement will put in the column
for the row. For a column defined with
AUTO_INCREMENT
, the serverwill put the next
number in the sequence for that column.
Another way to use defaults is to list just the columns into which you want to enter non-de-
fault data, like so: