MySQL INSERT

In MySQL Insert Statement is used to add records to the Table.

Syntax

Below is the Basic Syntax of MySQL INSERT Statement.

MySQL INSERT STATEMENT Examples

To understand MySQL INSERT statement with examples, let us execute the following script to create a demo Database MySQLTutorial with Customer table in it.

RESULT:
customertable

Example 1: INSERT INTO

Below statement adds the customer Johnson record into the Customer table. Here all the column names are specified and the values corresponding to the columns is specified in the VALUES clause.

Let us verify whether the customer Johnson record is inserted into the Customer table by executing the following SELECT statement

RESULT:
mysql-insert-into

From the above result we can see that the customer Johnson record is inserted into the Customer table.

Example 2: INSERT: Specifying column names is optional if all column values are passed

The below MySQL INSERT statement demonstrates that, specifying the Column Names in INSERT clause is optional if we are passing all values for all the columns. Here we have to make sure that the values are specified in the same order as the columns position in the Table.

Let us verify whether the customer Smith record is inserted into the Customer table by executing the following SELECT statement

RESULT:
mysql-insert-column-names-is-optional-if-all-values-inserted

From the above result we can see that the customer Smith record is also inserted into the Customer table.

Example 3: Inserting a record with values for only the selected columns of the Table

In the below INSERT statement we are not passing the value for the PhoneNumber column.

RESULT:

mysql-insert-without-nullable-columns

From the above result we can see that the newly inserted record for the customer George has PhoneNumber column value as NULL. The reason is we have not passed the PhoneNumber column value and as this is a NULLable column. So if we don’t pass value to the NULLable column in the MySQL INSERT statement, the INSERT statement will succeed but the NULLable column will have value as NULL

Leave a Reply

Your email address will not be published. Required fields are marked *