MySQL INSERT INTO Statement
MySQL INSERT INTO Statement
The INSERT INTO statement in MySQL is used to add new records (rows) to a table. It is one of the most commonly used SQL commands for storing data in a database.
๐ Basic Syntax
There are two ways to use the INSERT INTO statement:
ย 1. Insert values into all columns
โ Use this only when you provide values for every column in the correct order.
ย 2. Insert values into specific columns
โ This method is preferred because it is flexible and avoids errors.
๐งช Example Table
Assume a table named students:
| id | name | age | city |
|---|
๐ท Example 1: Insert All Column Values
๐ท Example 2: Insert into Selected Columns
If the id column is AUTO_INCREMENT, MySQL will automatically assign it.
๐ Insert Multiple Rows in One Query
โ This method is faster than running separate insert statements.
๐ Insert with NULL Value
If a column allows NULL, you can insert null like:
๐ง Insert with Default Values
If a table has default values:
Here, age will take its default or null value.
๐ฏ Example with AUTO_INCREMENT
Table structure:
Insert:
๐ข MySQL automatically assigns the next available id.
๐ง Best Practices
โ Always specify column names
โ Use proper data types
โ Use multiple row insert for performance
๐ Summary
| Feature | Example |
|---|---|
| Simple insert | INSERT INTO table VALUES (...); |
| Insert in selected columns | INSERT INTO table (col1, col2) VALUES (...); |
| Insert multiple rows | INSERT INTO table VALUES (...), (...); |
| Insert NULL | VALUES ('Name', NULL, 'City') |
| AUTO_INCREMENT support | No need to specify id |
