MySQL INSERT Statement Explained: Syntax, Examples, Multiple Rows, INSERT SELECT, and Best Practices
The MySQL INSERT statement is one of the most commonly used SQL commands for adding data to database tables. Whether you’re building a web application, managing customer records, maintaining inventory, or importing datasets, understanding how to use the INSERT statement efficiently is essential.
From inserting a single record to bulk loading multiple rows and copying data between tables, the INSERT statement provides flexible ways to populate your database.
In this comprehensive guide, you’ll learn the syntax of the MySQL INSERT statement, practical examples, common errors, performance tips, and best practices.
What Is the MySQL INSERT Statement?
The INSERT statement is used to add one or more new rows into an existing MySQL table.
Unlike SELECT, which retrieves data, INSERT permanently stores new records in the database.
Typical use cases include:
- Adding new customers
- Recording product information
- Creating employee records
- Importing inventory
- Storing application data
- Migrating data between tables
Basic MySQL INSERT Syntax
The standard syntax for inserting data is:
INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3);Here:
table_namespecifies the destination table.- The column list identifies where each value should be inserted.
- Values must match the corresponding column data types.
Example
INSERT INTO products (product_name, price, quantity)
VALUES ('Notebook', 10.99, 150);This query inserts one new product into the products table.
Inserting Data into All Columns
If you’re providing values for every column in the correct order, you can omit the column names.
INSERT INTO products
VALUES ('Notebook', 10.99, 150);Although this works, explicitly specifying column names is generally recommended because it makes your SQL easier to read and protects your queries if the table structure changes.
Inserting Data into Selected Columns
Sometimes you don’t have values for every column. In this case, specify only the columns you want to populate.
INSERT INTO products (product_name, quantity)
VALUES ('Notebook', 150);If omitted columns allow NULL values or have default values, MySQL automatically fills them.
For example:
| product_name | price | quantity |
|---|---|---|
| Notebook | NULL | 150 |
Inserting Multiple Rows
One of the fastest ways to add several records is by inserting multiple rows with a single statement.
INSERT INTO products (product_name, price, quantity)
VALUES
('Notebook', 10.99, 150),
('Pencil', 2.49, 300),
('Marker', 4.25, 120),
('Eraser', 1.99, 200);Benefits
- Faster execution
- Fewer database connections
- Reduced network overhead
- Cleaner SQL code
This approach is ideal when importing product catalogs or loading application data.
Copying Data with INSERT SELECT
The INSERT ... SELECT statement copies data from one table into another without manually entering each value.
Basic syntax:
INSERT INTO destination_table (column1, column2)
SELECT column1, column2
FROM source_table;Example:
INSERT INTO products (product_name, price, quantity)
SELECT product_name,
price,
quantity
FROM sales_products
WHERE price > 5;This query imports products priced above $5 from the sales_products table into the products table.
This method is commonly used for:
- Data migration
- Database backups
- Archiving records
- ETL (Extract, Transform, Load) workflows
Using Default Values
Suppose your table has default values.
CREATE TABLE products (
product_id INT AUTO_INCREMENT PRIMARY KEY,
product_name VARCHAR(100),
quantity INT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);You can insert only the required data.
INSERT INTO products (product_name)
VALUES ('Notebook');MySQL automatically assigns:
quantity = 0created_at = current timestamp
Inserting NULL Values
If a column allows NULL, you can insert it explicitly.
INSERT INTO employees (employee_name, phone)
VALUES ('John Smith', NULL);Common INSERT Errors
1. Duplicate Entry Error
This occurs when inserting a value that already exists in a column with a PRIMARY KEY or UNIQUE constraint.
Example:
INSERT INTO employees (employee_id, employee_name)
VALUES (101, 'John');If employee ID 101 already exists, MySQL returns a duplicate key error.
Possible solutions:
- Change the duplicate value.
- Use
INSERT IGNORE. - Use
ON DUPLICATE KEY UPDATE. - Use
REPLACE INTOif replacing existing rows is appropriate.
2. Data Type Mismatch
This happens when the supplied value doesn’t match the column’s data type.
Example:
INSERT INTO products (price)
VALUES ('Ten Dollars');If price is a numeric column, MySQL will generate an error or warning depending on SQL mode.
3. Column Count Doesn’t Match
Every value must correspond to a specified column.
Incorrect:
INSERT INTO products
VALUES ('Notebook', 10.99);If the table contains three columns, this statement fails.
Correct:
INSERT INTO products
VALUES ('Notebook', 10.99, 150);Or explicitly specify the columns:
INSERT INTO products (product_name, price)
VALUES ('Notebook', 10.99);Best Practices for Using INSERT
Always Specify Column Names
Instead of:
INSERT INTO products
VALUES ('Notebook', 10.99, 150);Use:
INSERT INTO products (product_name, price, quantity)
VALUES ('Notebook', 10.99, 150);This makes your queries easier to maintain.
Use Multi-Row INSERT for Bulk Data
Instead of executing hundreds of individual INSERT statements, combine them into one query whenever possible.
Validate Input Data
Before inserting user input:
- Check required fields.
- Validate numeric values.
- Verify date formats.
- Remove invalid characters.
Input validation improves data quality and reduces errors.
Use Transactions for Large Imports
When inserting thousands of records, wrap your statements inside a transaction.
START TRANSACTION;
INSERT INTO products (...);
COMMIT;Transactions improve reliability and make it easier to roll back changes if an error occurs.
Prevent SQL Injection
Never concatenate user input directly into SQL queries.
Instead, use:
- Prepared statements
- Parameterized queries
- ORM frameworks
This protects your database from SQL injection attacks.
Real-World Applications
The MySQL INSERT statement is widely used in:
- E-commerce websites
- Banking systems
- Healthcare applications
- Customer Relationship Management (CRM)
- Inventory management
- Student information systems
- Business intelligence platforms
- Financial reporting
- SaaS applications
- Data warehousing
INSERT vs INSERT IGNORE vs REPLACE INTO
| Statement | Purpose |
|---|---|
INSERT | Adds new records and returns an error if a duplicate key exists. |
INSERT IGNORE | Skips rows that would violate unique constraints without stopping the query. |
REPLACE INTO | Deletes the existing row with the same key (if any) and inserts the new row. |
Choose the appropriate statement based on your application’s data integrity requirements.
Conclusion
The MySQL INSERT statement is a fundamental SQL command for adding new records to database tables. Whether you’re inserting a single row, loading thousands of records, or copying data from another table using INSERT ... SELECT, mastering this command is essential for effective database management.
By explicitly specifying column names, validating data before insertion, using multi-row inserts for better performance, and following security best practices such as prepared statements, you can build reliable, scalable, and maintainable MySQL applications. As your SQL skills progress, the INSERT statement will become a core part of creating efficient data-driven solutions.