Careeroza
INSERT INTO
The SQL INSERT INTO Statement
INSERT INTO adds new records to a table. You can write it in two ways:
-- 1. Specify the columns (recommended)
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
-- 2. Values for ALL columns, in table order
INSERT INTO table_name
VALUES (value1, value2, value3, ...);Insert a Row
Example
Add a new customer:
INSERT INTO Customers (CustomerID, CustomerName, ContactName, City, Country)
VALUES (9, 'Ivy Kitchen', 'Rohan Mehta', 'Pune', 'India');Running SELECT * FROM Customers WHERE Country = 'India'; afterwards shows:
Result: 3 rows
| CustomerID | CustomerName | ContactName | City | Country |
|---|---|---|---|---|
| 1 | Aarav Traders | Aarav Shah | Mumbai | India |
| 4 | Delta Mart | Priya Nair | Bengaluru | India |
| 9 | Ivy Kitchen | Rohan Mehta | Pune | India |
Insert Data Only in Specified Columns
Example
Columns you leave out get NULL (or their DEFAULT value):
INSERT INTO Customers (CustomerID, CustomerName, Country)
VALUES (10, 'Juniper Foods', 'Norway');Running SELECT * FROM Customers WHERE Country = 'Norway'; afterwards shows:
Result: 2 rows
| CustomerID | CustomerName | ContactName | City | Country |
|---|---|---|---|---|
| 6 | Fjord Supplies | Ingrid Olsen | Oslo | Norway |
| 10 | Juniper Foods | NULL | NULL | Norway |
Insert Multiple Rows
Example
Separate each row with a comma:
INSERT INTO Products (ProductID, ProductName, Category, Price, Stock)
VALUES
(7, 'Masala Chai 250g', 'Beverages', 5.5, 60),
(8, 'Cashews 500g', 'Snacks', 11.0, 25);Running SELECT * FROM Products WHERE ProductID >= 7; afterwards shows:
Result: 2 rows
| ProductID | ProductName | Category | Price | Stock |
|---|---|---|---|---|
| 7 | Masala Chai 250g | Beverages | 5.5 | 60 |
| 8 | Cashews 500g | Snacks | 11 | 25 |
Common Mistakes
- Forgetting the column list: the statement breaks the day someone adds a column.
- Number of values does not match the number of columns.
- Inserting a duplicate primary key (error: UNIQUE constraint failed).
- Putting numbers in quotes or text without quotes.