6.6.1. Inserts
Adding data to a table is one of the more straightforward concepts in
SQL. You have already seen several examples of it in this book. Both
MySQL and mSQL support the standard SQL INSERT
syntax:
INSERT INTO table_name (column1, column2, ..., columnN)
VALUES (value1, value2, ..., valueN)
When inserting data into numeric fields, you can insert the value as
is; for all other fields, you must wrap them in single quotes. For
example, to insert a row of data into a table of addresses, you might
issue the following command:
INSERT INTO addresses (name, address, city, state, phone, age)
VALUES('Irving Forbush', '123 Mockingbird Lane', 'Corbin', 'KY',
'(800) 555-1234', 26)
# Insert info for the directory Stacie's Directory which
# is in c:\Personal\Stacie
INSERT INTO files (description, location)
VALUES ('Stacie\'s Directory', 'C:\\Personal\\Stacie')
MySQL allows you to leave out the column names as long as you specify
a value for every single column in the table in the exact same order
they were specified in the table's CREATE
call. If you want to use the default values for a column, however,
you must specify the names of the columns for which you intend to
insert nondefault data. If you do not have a default value set up for
a column and that column is NOT NULL, you must
include that column in the INSERT statement with a
non-NULL value. If the earlier files table had
contained a column called size, then the default
value would be used. Under mSQL, the default value is always
NULL. MySQL allows you to specify a custom default
value in the table's CREATE.
Newer versions of MySQL support a nonstandard
INSERT call for inserting multiple rows at once:
INSERT INTO foods VALUES (NULL, 'Oranges', 133, 0, 2, 39),
(NULL, 'Bananas', 122, 0, 4, 29),
(NULL, 'Liver', 232, 3, 15, 10)
MySQL supports the SQL2 syntax for inserting the values of a
SELECT call into a table:
INSERT INTO foods (name, fat)
SELECT food_name, fat_grams FROM recipes
You should note that the number of columns in the
INSERT matches the number of columns in the
SELECT. In addition, the datatypes for the
INSERT columns must match the datatypes for the
corresponding SELECT columns. Finally, the
SELECT clause in an INSERT
statement cannot contain an ORDER BY modifier and
cannot be selected from the same table where the
INSERT is occurring.