SQL INSERT Statement
The INSERT statement in SQL is used to add new rows of data into a table. It allows you to populate a database with meaningful information that can later be retrieved, updated, or deleted.
π Syntax
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
π Example Table: users
id | name | age | city ---+---------+-----+--------- 1 | Alice | 22 | New York 2 | Bob | 30 | London 3 | Charlie | 18 | Sydney 4 | Diana | 27 | Toronto 5 | Ethan | 35 | Paris
π Example 1: Insert New User
Letβs insert a new user into the table:
INSERT INTO users (name, age, city) VALUES ('Frank', 28, 'Berlin');π Example 2: Insert Without Column Names
If you insert values for all columns in the correct order, you can omit column names:
INSERT INTO users VALUES (6, 'Grace', 24, 'Rome');
π Example 3: Insert Multiple Rows
SQL allows inserting multiple rows in a single query:
INSERT INTO users (name, age, city)
VALUES
('Henry', 29, 'Madrid'),
('Isla', 26, 'Dubai'),
('Jack', 32, 'Tokyo');π Example 4: Insert with SELECT
You can copy data from one table into another using INSERT INTO ... SELECT:
INSERT INTO employees (name, age, city) SELECT name, age, city FROM users WHERE age > 25;
β‘ Best Practices
- Always specify column names for clarity and safety.
- Validate data types before inserting (e.g., numbers vs. text).
- Use transactions when inserting multiple rows for data integrity.
- Ensure primary keys are unique to avoid conflicts.
π Summary
The INSERT statement is used to add new data into a table. You can insert single rows, multiple rows, or even use SELECT to copy data between tables. Mastering INSERT is crucial for building and maintaining databases.
π Next Steps
In the next lesson, we will cover the SQL UPDATE Statement, which allows modifying existing records in a table.