Summary: In the previous tutorials you learn different ways to query data from database table by using SQL SELECT statement. Are you wonder that how data is added into those table? In this tutorial, you will learn do it by using SQL INSERT statement.
INSERT Statement
INSERT statement allows you to insert one or more rows to the table. In MySQL, the INSERT statement forms are listed as follows:
1 |
INSERT [LOW_PRIORITY | DELAYED] [IGNORE] |
2 |
[INTO] table_name [(column_name,...)] |
3 |
VALUES ((expression | DEFAULT),...),(...),... |
1 |
INSERT [LOW_PRIORITY | DELAYED] [IGNORE] |
2 |
[INTO] table_name [(column_name,...)] |
1 |
INSERT [LOW_PRIORITY | DELAYED] [IGNORE] |
3 |
SET column_name=(expression | DEFAULT), ... |
As you can see INTO in the INSERT statement is optional. In the first form, you insert a new data row into an existing table by specifying the column name and data for each. As an example to insert a new office to the offices table in the sample database you can do as follows:
01 |
INSERT INTO classicmodels.offices |
In the second form, instead of providing explicit data, you select it from other table by using SELECT statement. This form allows you to copy some or some part of data from other table to the inserted table. As an example, we can create a temporary table and insert all offices which locate in US into that one by using this query:
2 |
SELECT * FROM offices WHERE country = 'US' |
The third form enables you to specify the column you want to insert the data. For example, we have the query like this:
1 |
INSERT INTO productlines |
2 |
SET productLine = 'Luxury Cars' |
It means we only insert the data into productLine column in productLines table.
Related posts:
- Working with Tables – Part II
- Managing Database Index in MySQL
- Working with Database Table – Part I
- Using MySQL SELECT Statement to Query Data
- Changing Table Structure Using MySQL ALTER TABLE