sql logo

Learning SQL - Inserting Data

The SQL INSERT INTO Statement is used to add new rows of data to a table in the database. There are two straightforward syntaxes to insert data into a database shown below:

  1. INSERT INTO <table_name> (<col1>, <col2>, <col3>,...) VALUES (<val1>, <val2>, <val3>,...);
    • You can specify the column names where you want to add data if you are not adding to all columns. If you are adding data to all of the columns use the syntax number 2.

2. INSERT INTO <table_name> VALUES (<val1>, <val2>, <val3>,...);

Examples:

  • INSERT INTO movies (title, year_released) VALUES ('I am Legend', '2007')
  • INSERT INTO movies VALUES ('I am Legend', '2007')

Lastly, we can populate one table with another tables data using the SELECT keyword. The below is only possible if the second table has corresponding columns to the first table.

INSERT INTO <table_1> (<col1>, <col2>... )

SELECT <col1>, <col2>, ...

FROM <table_2>

WHERE <condition>;

Example:

  • INSERT INTO customer_address (street, city, state, zip_code)
    SELECT street, city, state, zip_code FROM providor_address;
  • INSERT INTO customer_address (street, city, state, zip_code)
    SELECT street, city, state, zip_code FROM providor_address
    WHERE state='NY';