1. Home
SQL

SQL Tutorial: Learn Structured Query Language Basics

Learn all SQL tutorial concepts in detail and master your career today.

  • 59
  • 9 Hours
right-top-arrow

Tutorial Playlist

46 Lessons
6

SQL INSERT INTO With Examples

Updated on 20/06/202462 Views

Introduction

The SQL INSERT INTO statement is a fundamental component of database management. It allows you to add new data rows seamlessly to your tables.

Ever since its initiation, it has held a significant place in Relational Database Management Systems (RDBMS). With nearly all RDBMS offering this SQL query, its significance cannot be overstated in database operations.

Let's examine the SQL INSERT INTO statement or command in more detail. I'll provide specific examples to walk you through the command.

Overview

SQL INSERT INTO allows you to add new rows of data to your database tables effortlessly.

In this guide, I will explain the syntax of the SQL INSERT INTO statement, discuss various scenarios where it can be applied, and illustrate its usage with clear examples.

By reading this article to the end, you will have a good idea of how SQL INSERT INTO adds data to your database tables without any hitches.

What is the SQL INSERT INTO Statement?

The SQL INSERT INTO statement is a powerful SQL command in database management, allowing you to add one or more records to a table effortlessly.

It's important to ensure that the values you're inserting match the data type and constraints of the respective columns in the table. If any mismatch occurs, the INSERT INTO statement will generate an error.

The syntax of the SQL INSERT INTO statement is given as:

INSERT INTO table_name (column1, column2, column3, ...)

VALUES (value1, value2, value3, ...);

● Here, "table_name" represents the table where you want to insert the new row(s),

● "column1", "column2", etc., are the columns where the values are to be inserted.

● Similarly, "value1", "value2", etc., are the actual values you want to insert into the corresponding columns.

Let’s say you have a table storing information about customers, and you want to add a new customer's details to it. This is where the INSERT INTO statement comes into play. Let’s say the "Customers" table has columns like "CustomerID", "FirstName", "LastName", and "Email".

CustomerID

FirstName

LastName

Email

102

Jane

Smith

jane.smith@example.com

103

David

Johnson

david.johnson@example.com

You can use the INSERT INTO statement to insert a new record into this table, specifying the values for each column.

INSERT INTO Customers (CustomerID, FirstName, LastName, Email)

VALUES (101, 'John', 'Doe', 'john.doe@example.com');

You now have:

CustomerID

FirstName

LastName

Email

101

John

Doe

john.doe@example.com

102

Jane

Smith

jane.smith@example.com

103

David

Johnson

david.johnson@example.com

In this example, we're inserting a new customer with CustomerID 101, first name "John", last name "Doe", and email address "john.doe@example.com" into the "Customers" table.

Ways to Use SQL INSERT INTO Statement

Here are three ways you can use the SQL INSERT INTO statement

1. Inserting Data Directly Into a Table

The SQL INSERT INTO statement allows you to insert new data rows directly into your database tables. There are two main ways to insert values into a table using INSERT INTO.

Firstly, you can simply provide the values you want to insert without specifying the column names where the data will be inserted:

INSERT INTO table_name

VALUES (value1, value2, value3...);

Alternatively, you can specify both the column names and values you want to insert:

INSERT INTO table_name (column1, column2, column3...)

VALUES (value1, value2, value3...);

Let's consider a table named "Employees" with columns for EmployeeID, Name, Age, and Department.

EmployeeID

Name

Age

Department

102

Jane Doe

35

Sales

103

Alice Johnson

28

HR

104

Bob Brown

40

Operations

105

Emma White

30

Marketing

We can use INSERT INTO to add new employees to the table:

INSERT INTO Employees (EmployeeID, Name, Age, Department)

VALUES (101, 'John Smith', 30, 'Marketing');

This SQL statement adds a new employee with the specified EmployeeID, Name, Age, and Department to the Employees table.

EmployeeID

Name

Age

Department

101

John Smith

30

Marketing

102

Jane Doe

35

Sales

103

Alice Johnson

28

HR

104

Bob Brown

40

Operations

105

Emma White

30

Marketing

Multiple Records

Similarly, you can insert multiple records or perform SQL INSERT multiple rows by repeating the INSERT INTO statement with different values, like adding more employees to the Employees table:

INSERT INTO Employees (EmployeeID, Name, Age, Department)

VALUES (106, 'Joseph', 31, 'Sales'),

(107, 'Mary', 21, 'HR');

This inserts two new records for employees Jane Doe and Alice Johnson into the Employees table. You now have:

EmployeeID

Name

Age

Department

101

John Smith

30

Marketing

102

Jane Doe

35

Sales

103

Alice Johnson

28

HR

104

Bob Brown

40

Operations

105

Emma White

30

Marketing

106

Joseph

31

Sales

107

Mary

21

HR

2. Inserting Data Through SELECT Statement

Another powerful way to utilize the SQL INSERT statement is by inserting data from one table into another using the SELECT statement. INSERT with SELECT in SQL allows you to copy data from one table and insert it into another table seamlessly. So SQL INSERT from another table is possible.

Let's explain the syntax and provide an example to help you understand this approach better.

SQL INSERT INTO SELECT Syntax:

INSERT INTO target_table_name [(column1, column2, .... column)]

SELECT column1, column2, .... Column N

FROM source_table_name [WHERE condition];

The syntax is broken down into the following components:

● INSERT INTO table_name: Specifies the target table where you want to insert the data.

● (column1, column2, .... columnN): Optional. Specifies the columns in the target table where you want to insert the data. If omitted, data will be inserted into all columns in the target table.

● SELECT column1, column2, .... columnN: Specifies the columns you want to select data from in the source table.

● FROM table_name: Specifies the source table from which you want to select data.

● [WHERE condition]: Optional. Specifies any conditions that the selected rows must meet in the source table.

For example, let's say you have a table named "Customers" with columns for CustomerID, Name, Age, and City, and you want to create a new table named "VIP_Customers" by selecting specific customers from the "Customers" table based on certain criteria.

Original table "Customers":

CustomerID

Name

Age

City

1

John Smith

35

New York

2

Alice Johnson

28

Los Angeles

3

Bob Brown

40

Chicago

4

Emma White

30

Houston

5

James Taylor

45

Miami

You may accomplish this with the INSERT INTO SELECT statement:

INSERT INTO VIP_Customers (CustomerID, Name, Age, City)

SELECT CustomerID, Name, Age, City

FROM Customers

WHERE Age > 30;

Target table "VIP_Customers" after inserting data using SELECT statement:

CustomerID

Name

Age

City

1

John Smith

35

New York

3

Bob Brown

40

Chicago

5

James Taylor

45

Miami

In this example, the SELECT statement retrieves data from the "Customers" table where the Age column is greater than 30, and inserts it into the "VIP_Customers" table. This allows you to create a new table containing only the customers who meet the specified criteria.

Tips for Efficient Use of SQL INSERT INTO Statement

Efficient use of the SQL INSERT INTO statement can greatly streamline the process of adding data to your database. Here are some tips to make the most out of it:

1. Batch Inserts

Instead of executing individual INSERT statements for each record, consider using batch inserts to add multiple rows at once. This can significantly reduce the overhead associated with multiple database transactions.

For instance, using the Employee Table we used before, rather than:

INSERT INTO Employees (Name, Age, Department) VALUES (108, 'John', 30, 'Marketing');

INSERT INTO Employees (Name, Age, Department) VALUES (109, 'Jane', 35, 'Sales');

You can merge all into one statement:

INSERT INTO Employees (Name, Age, Department)

VALUES (108, 'John', 30, 'Marketing'),

(109, 'Jane', 35, 'Sales');

2. Use Default Values

If your table has columns with default values defined, you can omit them from your INSERT statement. This can simplify your queries and reduce the amount of data you need to specify explicitly. For example, To insert into an Orders Table use the following command.:

INSERT INTO Orders (OrderID, CustomerID, OrderDate)

VALUES (1, 101, DEFAULT);

In this example, if OrderDate has a default value defined, you don't need to specify it explicitly.

3. Don’t use Unnecessary Columns

Only include the columns in your INSERT statement that you need to populate. Omitting unnecessary columns reduces the amount of data transferred and processed, improving performance. For instance, Let’s say you want to INSERT into a student’s table:

INSERT INTO Students (Name, Age) VALUES ('Alice', 25);

If the Students table has other columns like Grade, and you're not inserting values into it, there's no need to include it in the INSERT statement.

Common Pitfalls to Avoid While Using the SQL INSERT INTO Statement

When working with the SQL INSERT INTO statement, there are a few common pitfalls that you'll want to avoid to ensure your data is inserted correctly and efficiently. Let's delve into some of these potential stumbling blocks:

1. Missing Columns in Insert Statement

One of the most frequent errors is forgetting to specify all the columns when inserting data into a table. If you omit a column, the database will either assign a default value (if specified) or insert NULL.

For instance, if you have a table with columns for first_name, last_name, and email, make sure your INSERT INTO statement includes values for all these columns.

-- Incorrect

INSERT INTO users (thefirst_name, thelast_name) VALUES ('Jake', 'Doe');

-- Correct

INSERT INTO users (thefirst_name, thelast_name, email) VALUES ('Jake', 'Doe', 'john@example.com');

2. Data Type Mismatch

Make sure that the data types of the values you're inserting match the data types of the columns in your table. If there's a mismatch, it can lead to errors or unexpected behavior. For example, inserting a string into a numeric column or vice versa can result in a conversion error.

-- Incorrect

INSERT INTO employees (employee_id, age) VALUES ('ABC', 30);

-- Correct

INSERT INTO employees (employee_id, age) VALUES (101, 30);

3. Primary Key Violations

If you're inserting data into a table with a primary key, be cautious not to insert duplicate primary key values. Attempting to do so will result in a primary key violation error. This commonly occurs when you're importing data from an external source or performing batch inserts.

-- Incorrect

INSERT INTO customers (customer_id, name) VALUES (101, 'John Doe');

-- Correct (assuming 101 is not already in use)

INSERT INTO customers (customer_id, name) VALUES (102, 'John Doe');

Conclusion

In summary, knowing how to use the SQL INSERT INTO command is crucial for managing your database well. It allows you to add new data to your tables easily and without hassle.

Throughout this guide, we've discussed how to use INSERT INTO, shown examples, and discussed how it can be used in different situations. Just remember to be careful and avoid common mistakes like forgetting to include all the necessary details or trying to add the same information twice.

Following these tips can help you become more skilled at handling your data with SQL. So, keep practicing and enjoy making your databases work smoothly!

FAQs

  1. What is the insert command in SQL?

The INSERT command in SQL is used to add new records or rows of data into a table in a database. It helps you Insert into SQL tables

  1. How to write SQL insert script?

To write an SQL insert script, you specify the table name and the values you want to insert into the table, following the syntax:

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

  1. How do you insert items into table SQL?

You can insert items into a table in SQL using the INSERT INTO statement followed by the table name and the values you want to insert.

  1. What is the syntax for inserting in MySQL?

The syntax of INSERT in MySQL is similar to other SQL databases:

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

  1. How to insert null in SQL?

To insert a NULL value in SQL, you can simply specify NULL in place of the value for the respective column in the INSERT INTO statement.

INSERT INTO table_name (column1, column2, ...)

VALUES (value1, NULL, ...);

  1. What's the distinction between insert and insert into?

There is no difference between INSERT and INSERT INTO in SQL. They both serve the same purpose of adding new records to a table.

  1. How do I insert it in SQL Plus?

In SQL Plus, you use the same INSERT INTO statement as in regular SQL to add data to a table.

  1. What are the examples of INSERT?

Examples of INSERT statements include adding new customers to a customer table, inserting product information into a product table, or adding employee records to an employee table.

  1. Can we use INSERT and select together?

Yes, you can use INSERT INTO with a SELECT statement to insert data selected from one table into another table.

  1. What is the limit for inserting in SQL?

There's no fixed limit to the number of records you can insert in SQL. It depends on factors like database configuration and available system resources.

Pavan Vadapalli

Pavan Vadapalli

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working … Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...