SQL INSERT INTO
Statement
The INSERT INTO
statement is used to insert new records into a table.
SQL INSERT INTO Statement
The INSERT INTO
statement is used to insert new records into a table.
SQL INSERT INTO Syntax
The INSERT INTO
statement can be written in two ways.
The first form does not require the column names where the data will be inserted, only the values to be inserted:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
The second form requires specifying the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Parameter Description:
- table_name: The name of the table where new records will be inserted.
- column1, column2, ...: The names of the fields where data will be inserted.
- value1, value2, ...: The values to be inserted into the fields.
Demonstration Database
In this tutorial, we will use the tutorialpro
sample database.
Below is data from the "Websites" table:
+----+--------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA |
| 2 | Taobao | https://www.taobao.com/ | 13 | CN |
| 3 | tutorialpro.org | http://www.tutorialpro.org/ | 4689 | CN |
| 4 | Weibo | http://weibo.com/ | 20 | CN |
| 5 | Facebook | https://www.facebook.com/ | 3 | USA |
+----+--------------+---------------------------+-------+---------+
INSERT INTO Example
Suppose we want to insert a new row into the "Websites" table.
We can use the following SQL statement:
Example
INSERT INTO Websites (name, url, alexa, country)
VALUES ('Baidu', 'https://www.baidu.com/', '4', 'CN');
After executing the above SQL, the "Websites" table will look like this:
| | Did you notice that we did not insert any number into the id field? <br>The id column is auto-incremented, and each record in the table has a unique number. | | --- | --- |
Insert Data into Specified Columns
We can also insert data into specified columns.
The following SQL statement will insert a new row, but only into the "name", "url", and "country" columns (the id field will be auto-updated):
Example
INSERT INTO Websites (name, url, country)
VALUES ('stackoverflow', 'http://stackoverflow.com/', 'IND');
After executing the above SQL, the "Websites" table will look like this: