Course outline · 0% complete

0/29 lessons0%

Course overview →

INSERT, Properly

lesson 7-1 · ~11 min · 19/29

Quiz

Warm-up from lesson 1-1: which statement adds a row to the pets table?

Naming your columns

Reading data was the first half of the course. But every signup, every message, every order your app handles arrives as an INSERT written by app code, and that code keeps running unchanged for years while the table evolves underneath it. That is why how you write an INSERT matters.

The bare INSERT INTO pets VALUES ('Rex', 'dog', 1) relies on you remembering the exact column order from CREATE TABLE. Add a column to the table later and every such INSERT silently puts values in the wrong place. The professional form names the columns:

INSERT INTO pets (name, species) VALUES ('Kiwi', 'bird');

Two benefits:

  • Order no longer matters, you match values to the names you wrote.
  • You can skip columns. Skipped ones become NULL (or a default, lesson 7-3). Kiwi's age is unknown, so we simply do not provide it.

You can also insert several rows in one statement by chaining value groups with commas.

Code exercise · sql

Run it. Kiwi gets NULL for age (the empty spot after the last |), and the second INSERT adds two rows at once.

Code exercise · sql

Your turn. Using ONE multi-row INSERT with a column list, add two more pets: Ziggy the parrot (age 2) and Rex, a dog whose age is unknown. Rex's age should be NULL.

Quiz

A table has columns name, species, age. What does `INSERT INTO pets (name, species) VALUES ('Kiwi', 'bird');` store in Kiwi's age?