SQL INSERT Check Answers
Answers to INSERT - check your progress questions
There are several versions of the syntax for the INSERT statement and they all work slightly differently. Your task is to think about how and when they work, write down your answer and only then compare with the suggested answer/solution. We suggest that you answer all questions in the "check your progress" before looking at any answers.
The first syntax is the most classic one:
sqlite> CREATE TABLE customer(customer_id INTEGER PRIMARY KEY, name TEXT, email TEXT); sqlite> INSERT INTO customer(name, email) VALUES('Rikard', 'email@example.com');
In this syntax, you list the column names and then provide the values.
- Check 1 a) What happens if you provide the values as follows instead:
INSERT INTO customer(name, email) VALUES('firstname.lastname@example.org', 'Rikard');
Answer: The email string will be inserted into the
name column and the name string will be inserted into the
- Check 1 b) What happens to the customer_id field if you use the above syntax? Hint: We talked about it when we introduced primary keys - INTEGER primary keys are special in SQLite3
customer_id is both INTEGER and PRIMARY KEY, in SQLite3, the value for the
customer_id will be calculated by the database engine. It will be one larger than the last number, in order to guarantee a unique number - primary keys must be unique. This is rather convenient, since the id is more of a technicality than something which exists "in the real world".
A slightly shorter syntax for accomplishing an INSERT is:
sqlite> INSERT INTO customer VALUES(2, 'Henrik', 'email@example.com'); sqlite> SELECT * FROM customer; customer_id|name|email 1|Rikardfirstname.lastname@example.org 2|Henrikemail@example.com
- Check 1 c) The column names weren't listed in the shorter syntax version. What must we think about and do in order for this shorter version to work?
Answer: In order to skip the column names in the INSERT statement, you need to provide values for every column in the table, and do so in the same column order as was used when the table was created.
Finally, here's a third syntax version. What do you think it does? Try it out and use SELECT to figure out the result:
sqlite> INSERT INTO customer(name, email) VALUES('Alan', 'firstname.lastname@example.org'), ('Lennart', 'email@example.com'), ('Juho', 'firstname.lastname@example.org'), ('Aida', 'email@example.com'), ('Dina', 'firstname.lastname@example.org');
- Check 1 d) Explain in your own words how the above syntax works. Can you combine it with the shorter syntax without the column names?
Answer: It inserts five rows, and each row will have its
customer_id calulated for you by the SQLite3 engine. It is possible to skip the column names, but then, as said above, you need to provide all column values and in the same order as the table was created with.