Skip to main content

Using the INSERT INTO Statement


In SQL, the INSERT INTO statement is one of the most commonly used commands that allows you to add new rows of data into a table. With this command, you can insert one row or multiple rows at a time. This tutorial will guide you through the process of using the INSERT INTO statement in SQL.

Understanding the INSERT INTO Statement

The INSERT INTO statement is used to insert new records (rows) in a table.

The basic syntax for INSERT INTO statement is:

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...);
  • table_name: refers to the name of the table where you want to insert data.
  • (column1, column2, column3,...): these are the columns in the table that you want to insert data into.
  • VALUES (value1, value2, value3,...): these are the values that you want to insert.

Remember, the order of columns in the INSERT INTO clause must match the order of values in the VALUES clause.

Inserting Data into a Single Column

Let's start with a simple example where we insert data into a single column. Assume we have a table called Customers with two columns CustomerID and CustomerName. If we wanted to insert a new customer with ID '1' and name 'John Doe', we would use the following SQL statement:

INSERT INTO Customers (CustomerID, CustomerName)
VALUES (1, 'John Doe');

Inserting Data into Multiple Columns

You can also insert data into multiple columns at once. Let's insert a new customer with ID '2', name 'Jane Doe', and age '30' into the Customers table:

INSERT INTO Customers (CustomerID, CustomerName, Age)
VALUES (2, 'Jane Doe', 30);

Inserting Multiple Rows

In addition to inserting a single row, the INSERT INTO statement also allows you to insert multiple rows into a table at once. This is achieved by adding more sets of parentheses with values:

INSERT INTO Customers (CustomerID, CustomerName, Age)
VALUES (3, 'Bob Smith', 45),
(4, 'Alice Johnson', 34),
(5, 'Charlie Brown', 28);

Inserting Data without Specifying Columns

You can also insert data without specifying the column names, but for this to work, you have to provide values for all columns and the values must be in the same order as the columns in the table.

INSERT INTO Customers
VALUES (6, 'Emily Davis', 32);

However, this method is not recommended because you need to know the exact order of all columns in the table, and if the table structure changes (e.g., a column is added or removed), it could break your SQL statement.

Conclusion

The INSERT INTO statement is a powerful command that allows you to add new rows of data into your SQL tables. It's important to remember to match the order of columns with the order of values and to ensure that data types match the column’s data type. With these basics, you should now be able to insert data into your SQL tables. This is a fundamental skill in SQL and a stepping stone to mastering SQL data manipulation.