SQL INSERT Statement

SQL INSERT statement is a SQL query. It is used to insert a single or a multiple records in a table.

Syntax

The basic syntax for inserting data into a table can be given with:

INSERT INTO table_name (column1,column2,...) VALUES (value1,value2,...);

Here the column1, column2,..., etc. represents the name of the table columns, whereas the value1, value2,..., and so on represents the corresponding values for these columns.

Let's insert some records into the persons table.

  1. By SQL insert into statement
    1. By specifying column names
    2. Without specifying column names
  2. By SQL insert into select statement

Step 1: View Table Structure

Before adding record it's a good idea to obtain the information about the table structure. Execute the following command on MySQL command-line. It will display the information about the columns in the persons table i.e. column name, data type, constraints etc.

mysql> DESCRIBE persons;

You can see the column information or structure of any table in MySQL and Oracle database using the command DESCRIBE table_name;, whereas EXEC sp_columns table_name; in SQL Server (replace the table_name with actual table name).

Step 2: Adding Records to a Table

The following statement inserts a new row in persons table.

INSERT INTO persons (name, birth_date, phone)
VALUES ('Peter Wilson', '1990-07-15', '0711-020361');

Did you notice, we didn't insert any value for id field? Because, if you remember from the create table chapter, the id field was marked with AUTO_INCREMENT flag, which tells MySQL to automatically assign a value to this field if it is left unspecified.

Similarly, insert another row into the persons table, as follow:

Example

INSERT INTO persons (name, birth_date, phone)
VALUES ('Carrie Simpson', '1995-05-01', '0251-031259');

Now if you select the records from persons table, the output will now look like this:

+----+--------------------+------------+-------------+
| id | name               | birth_date | phone       |
+----+--------------------+------------+-------------+
|  1 | Peter Wilson       | 1990-07-15 | 0711-020361 |
|  2 | Carrie Simpson     | 1995-05-01 | 0251-031259 |
|  3 | Victoria Ashworth  | 1996-10-17 | 0695-346721 |
+----+--------------------+------------+-------------+