Inserting Rows
The table exists and it is empty. Everything so far has been structure; this is the first command that puts actual data in. It is also where three small rules — about order, quotes and dates — account for most of the errors beginners meet.
1The syntax
insert into <table name> values (<v1>, <v2>, …, <vN>);
1 row affected — unlike create table, this one really does affect a row, because a row is exactly what it made.
(id, name, grade, percent, dob, city), so the values must arrive in that order. Swap two of them and you either get an error or, worse, a row that is quietly wrong.2Many rows in one query
Rather than repeating the command, separate the bracketed groups with commas:
The extra line is worth reading. Records: 2 is how many rows you offered, Duplicates: 0 how many clashed with an existing key, and Warnings: 0 how many were accepted but altered on the way in. All three at their expected values means the insert did exactly what you asked.
3Naming the columns
Sometimes you only have some of the data. List the columns you are supplying, in brackets, before values:
Asha's row exists, and the three columns nobody supplied were filled with NULL — the missing-value marker from the concepts chapter, doing its job. Had one of those columns carried a default, the default would have been used instead.
(name, id, grade) works just as well, as long as the values line up with the names you gave. It is also self-documenting: a reader can see what each value is without going to look at the table.4Quotes, and the date format
char, varchar and date values.
int and float values.
And the date format is fixed — year first, four digits, hyphens, in quotes. Writing it the way you would by hand is refused:
5Three refusals worth recognising
The wrong number of values. The table has six columns and only two were given:
The same error appears if you name three columns and supply four values. MySQL is counting the two lists and finding they disagree — so either supply every column, or name the ones you are supplying.
A duplicate primary key. Student 1099 is already in the table:
A NULL primary key. Every row must be identifiable:
6Recap
Values in the table's column order. One row.
Several rows in one query, groups separated by commas.
Supply only some columns; the rest get their default or NULL.
Text and dates yes, numbers no. Dates are 'YYYY-MM-DD'.
A table has 6 columns. You run insert into students values (5001,'X'); What happens?
How must the date 20 November 2010 be written?
insert into students (id, name, grade) values (4001, 'Asha', 11); — what goes into the percent column?
What does 'Records: 2 Duplicates: 0 Warnings: 0' tell you?