SQL — Insert Into
Basic INSERT
INSERT INTO users (name, email, age)
VALUES ('Alice', 'alice@example.com', 30);
Multiple rows
INSERT INTO users (name, email, age)
VALUES
('Alice', 'alice@example.com', 30),
('Bob', 'bob@example.com', 25),
('Charlie', 'charlie@example.com', 35);
INSERT with SELECT
INSERT INTO backup_users (name, email)
SELECT name, email
FROM users
WHERE age > 30;
Default values
CREATE TABLE orders (
id INT PRIMARY KEY,
status VARCHAR(20) DEFAULT 'pending'
);
INSERT INTO orders (id) VALUES (1);
-- status is 'pending'
INSERT with NULL
INSERT INTO users (name, email, phone)
VALUES ('Alice', 'alice@example.com', NULL);
ON CONFLICT (UPSERT)
-- PostgreSQL
INSERT INTO users (id, name, email)
VALUES (1, 'Alice', 'alice@example.com')
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name;
-- MySQL
INSERT INTO users (id, name, email)
VALUES (1, 'Alice', 'alice@example.com')
ON DUPLICATE KEY UPDATE name = VALUES(name);
Returning inserted data
-- PostgreSQL
INSERT INTO users (name, email)
VALUES ('Alice', 'alice@example.com')
RETURNING id, name;
Mini Practice
Write SQL code that:
- Inserts a single row
- Inserts multiple rows
- Uses ON CONFLICT for upsert
- Inserts with default values
Up Next
In the next lesson, you'll learn about Update — modifying existing data.
Related Topics
Frequently Asked Questions about Insert Into
What is Insert Into in SQL?
Insert Into is a fundamental concept in SQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Insert Into?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Insert Into.
Why is Insert Into important in SQL?
Insert Into is essential for SQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.