INSERT
Add rows with INSERT, see what happens to columns you leave out, and read the errors when a new row breaks a rule.
INSERT adds rows
INSERT INTO table (columns) VALUES (values) adds a new row. List the columns you are filling, then the values in the same order. The column list can be in any order, as long as the values match it.
You can add several rows in one statement by repeating the brackets after VALUES, and you can copy rows from a query with INSERT INTO ... SELECT ....
How data gets in
Every row in every table started as an INSERT. Writing the column list out, instead of relying on the table's column order, keeps your statement working when someone later adds a column.
Left-out columns and rejected rows
INSERT INTO members (name, email)
VALUES ('Dara', 'dara@mail.test');The members table has an id that numbers itself. Because id is not in the column list, it takes its default, the next number from its sequence, so Dara gets 4. A column with no default that you leave out becomes NULL.
PostgreSQL answers with a command tag: INSERT 0 1 means one row was inserted. The 0 is a leftover and is always 0.
If a row breaks a rule, the whole statement fails and nothing is added. A repeated id or email gives duplicate key value violates unique constraint, and a NULL in a NOT NULL column gives null value in column "name" ... violates not-null constraint.
Insert good and bad rows
Run a few good inserts, then try the repeated id, the repeated email and the missing name. Watch the next id after each one.
| idinteger | nametext | emailtext |
|---|---|---|
| 1 | Asha | asha@mail.test |
| 2 | Ben | ben@mail.test |
| 3 | Chen | NULL |
Pick a statement and press Run statement. Try the three bad ones, then look at the next id and run a good one.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- INSERT INTO table (columns) VALUES (...) adds rows, and one statement can add several.
- A left-out column gets its default, or NULL when it has none.
- A row that breaks a rule makes the whole statement fail, and nothing is added.
- Sequence numbers are not given back, so ids can have gaps. Always name the columns.
Done with this concept?
Mark it complete to track your progress. No login needed.