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.