All for Joomla All for Webmasters

SQL INSERT STATEMENT

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

There are two ways to insert data in a table:

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

1) Inserting data directly into a table

You can insert a row in the table by using SQL INSERT INTO command. But there are 2 ways to do this.

You can specify or ignore the column names while using INSERT INTO statement.

To insert partial column values, you must have to specify the column names. But if you want to insert all the column values, you can specify or ignore the column names.

If you specify the column names, syntax of the insert into statement will be as follows:

  1. INSERT INTO TABLE_NAME
  2. [(col1, col2, col3,…. col N)]
  3. VALUES (value1, value2, value 3, …. Value N);

Here col1, col2, col3, …. colN are the columns of the table in which you want to insert data.

Note: At the time of inserting a row into table, if you add values for all columns then there is no need to specify the column name in SQL INSERT query. Moreover, you must be sure that you are entering the values in the same order as the columns exist.

But, If you ignore the column names, syntax of the insert into statement will be as follows:

  1. INSERT INTO TABLE_NAME
  2. VALUES (value1, value2, value 3, …. Value N);

2) Inserting data through SELECT Statement

SQL INSERT INTO SELECT Syntax

  1. INSERT INTO table_name
  2. [(column1, column2, …. column)]
  3. SELECT column1, column2, …. Column N
  4. FROM table_name [WHERE condition];

Note: when you add a new row, you should make sure that data type of the value and the column should be matched.

If any integrity constraints are defined for the table, you must follow them.

PinIt
submit to reddit

Leave a Reply

Top