Skip to main content

Inserting Data into Tables

Introduction

In SQL, tables are the primary structure where we store our data. But a table without data is like a library without books. In this tutorial, we will learn how to insert data into SQL tables.

The INSERT INTO Statement

The INSERT INTO statement is used to insert new records in a table. It is important to note that in SQL, we talk about "records" or "rows" of data, not "entries" or "items".

The syntax is as follows:

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

In this syntax, table_name is the name of the table that you want to insert data into. (column1, column2, column3, ...) is a list of columns in the table that you want to insert data into. And (value1, value2, value3, ...) are the values that you want to insert.

Here is an example:

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

In this example, a new record is inserted into the 'Customers' table.

Insert Data Only in Specified Columns

It is not necessary to fill up all the columns in a row when inserting data. You can choose which columns to fill up. The syntax is:

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

In this syntax, (column1, column2, column3, ...) is a list of columns you want to fill up. You only list the columns you want to insert data into.

Here is an example:

INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');

In this example, data is only inserted into the 'CustomerName', 'City', and 'Country' columns.

Insert Data from Another Table

Sometimes, you may want to insert data into a table from another table. You can do this by using a SELECT statement in conjunction with the INSERT INTO statement. The syntax is as follows:

INSERT INTO table1 (column1, column2, ...)
SELECT column1, column2, ...
FROM table2
WHERE condition;

In this syntax, table1 is the table you are inserting data into and table2 is the table you are selecting data from.

Here is an example:

INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';

This statement will insert into the 'Customers' table all suppliers located in Germany from the 'Suppliers' table.

Conclusion

The INSERT INTO statement is a fundamental part of managing data in SQL tables. It allows you to add new rows of data into your tables, whether that data is hardcoded values or selected from other tables. Practice with your own examples to get a good grasp of this statement.