๐ What Youโll Learn
- What
INSERT INTO
is used for - Syntax to insert single and multiple rows
- Examples with real-world context
- Things to watch out for
๐งฉ What Is INSERT INTO?
The INSERT INTO
statement is used to add new records to a database table.
It allows you to populate your table with fresh data, either one row at a time or multiple rows at once.
๐งฑ Basic Syntax
Insert a single row (specifying columns):
INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3);
Insert multiple rows:
INSERT INTO table_name (column1, column2)
VALUES
(value1a, value2a),
(value1b, value2b);
๐งช Example: Adding New Users
Single user
INSERT INTO users (name, email, country)
VALUES ('Alice', 'alice@example.com', 'USA');
Multiple users
INSERT INTO users (name, email, country)
VALUES
('Bob', 'bob@example.com', 'UK'),
('Lena', 'lena@example.com', 'Canada');
โ ๏ธ Tips & Common Pitfalls
- ๐ Always specify column names to avoid order mismatch issues
- โ Data types must match the column definitions (e.g., no text in numeric fields)
- ๐ซ Missing
NOT NULL
fields without default values will cause errors - ๐ Use
RETURNING *
(PostgreSQL) to get the inserted data back
๐ Recap
INSERT INTO
adds data to a table- You can insert one or many rows at once
- Always match value types to column types
- Naming columns explicitly is a best practice