SQL ยท Chapter 7 of 42

SQL INSERT INTO

INSERT adds new rows to a table. You can list columns explicitly or rely on the table's column order.

Best practice: always list columns.

Syntax
INSERT INTO table (col1, col2) VALUES (val1, val2);

Single & multiple rows

One VALUES clause per row; separate with commas to insert many rows in a single statement.

INSERT ... SELECT

Copy rows from another query: `INSERT INTO t (a) SELECT a FROM other;`

Example 1 (sql)
INSERT INTO users (name, age, country)
VALUES ('Ana', 25, 'India');
Output
1 row inserted

Add a single row.

Example 2 (sql)
INSERT INTO products (name, price) VALUES
('Book', 250),
('Pen', 20),
('Bag', 900);
Output
3 rows inserted

Bulk insert.

Key points

  • Always name your target columns.
  • Bulk insert with multiple VALUES.
  • INSERT INTO ... SELECT copies from another query.
  • Auto-increment PKs are usually omitted from the column list.
๐Ÿ’ก Note: Missing columns default to NULL (or the column's DEFAULT value). Required NOT NULL columns must be included.

๐Ÿ“ Quick Quiz

1. Which command adds new rows?

2. Can INSERT add multiple rows in one statement?

3. What happens if you skip a NOT NULL column without a DEFAULT?