MySQL Insert Techniques
Standard INSERT Techniques
Basic Single Row Insertion
INSERT INTO users (username, email, age)
VALUES ('johndoe', '[email protected]', 25);
Multiple Row Insertion
INSERT INTO users (username, email, age)
VALUES
('johndoe', '[email protected]', 25),
('janedoe', '[email protected]', 30),
('bobsmith', '[email protected]', 35);
Advanced Insertion Methods
INSERT IGNORE
Skips rows that would cause duplicate key errors:
INSERT IGNORE INTO users (username, email, age)
VALUES
('johndoe', '[email protected]', 25),
('johndoe', '[email protected]', 25); ## Duplicate will be ignored
INSERT ... ON DUPLICATE KEY UPDATE
Updates existing records if a unique key conflict occurs:
INSERT INTO users (username, email, age)
VALUES ('johndoe', '[email protected]', 25)
ON DUPLICATE KEY UPDATE
age = VALUES(age);
Bulk Insertion Techniques
LOAD DATA INFILE
High-performance method for large dataset imports:
LOAD DATA INFILE '/path/to/users.csv'
INTO TABLE users
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
Technique |
Performance |
Use Case |
Single INSERT |
Slowest |
Small datasets |
Multiple Row INSERT |
Medium |
Moderate datasets |
LOAD DATA INFILE |
Fastest |
Large datasets |
Workflow Visualization
graph TD
A[Data Source] --> B{Insertion Method}
B -->|Single Row| C[Standard INSERT]
B -->|Multiple Rows| D[Bulk INSERT]
B -->|Large Dataset| E[LOAD DATA INFILE]
C --> F[Database Storage]
D --> F
E --> F
Best Practices
- Use transactions for large insertions
- Batch your insert operations
- Disable indexes before bulk insert
- Choose appropriate insertion technique
By mastering these techniques on LabEx, developers can optimize MySQL data insertion processes efficiently.