0% found this document useful (0 votes)
13 views19 pages

2.3 - SQL Insert Update Delete

The document provides an overview of SQL commands, specifically focusing on the INSERT INTO, UPDATE, and DELETE statements. It explains how to add new data to a database table, modify existing records, and remove rows while emphasizing the importance of using proper syntax and conditions. Key points include methods for inserting data, updating records with specific conditions, and the significance of the WHERE clause in preventing unintended changes.

Uploaded by

kdramalove770
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views19 pages

2.3 - SQL Insert Update Delete

The document provides an overview of SQL commands, specifically focusing on the INSERT INTO, UPDATE, and DELETE statements. It explains how to add new data to a database table, modify existing records, and remove rows while emphasizing the importance of using proper syntax and conditions. Key points include methods for inserting data, updating records with specific conditions, and the significance of the WHERE clause in preventing unintended changes.

Uploaded by

kdramalove770
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 19

SQL INSERT INTO Statement

The SQL INSERT INTO statement is one of the most essential commands for adding new data into a
database table. Whether you are working with customer records, product details or user information,
understanding and mastering this command is important for effective database management.

How SQL INSERT INTO Command Works


The SQL INSERT INTO statement allows you to add new rows of data into an existing table in a
database. It’s a fundamental command in SQL, frequently used to populate tables with data. There
are two primary methods for using this command:

1. Inserting Data into All Columns: If you want to insert data into all columns of the table, you
can omit the column names and simply provide values for every column.

2. Inserting Data with Specific Columns: You can explicitly specify the columns you want to
insert data into, followed by the corresponding values.
The choice of method depends on whether you're inserting data for all the columns in a table or only
for a subset of them.

1. Inserting Data into All Columns (Simple Method)


This method is used when you want to insert data into all columns of a table without specifying
column names. We simply provide the values for each column, in the same order that the columns
are defined in the table.

Syntax:

INSERT INTO table_name


VALUES (value1, value2, value);
Parameters:
 table_name: The name of the table where the data will be inserted
 value1, value2: The values you want to insert into the respective columns of the table

Example:
For better understanding, let's look at the SQL INSERT INTO statement with examples.
Let us first create a table named 'Student'.

CREATE DATABASE StudentDB;


USE StudentDB;

CREATE TABLE Student (


ROLL_NO INT PRIMARY KEY,
NAME VARCHAR(50),
ADDRESS VARCHAR(100),
PHONE VARCHAR(15),
AGE INT
);

INSERT INTO Student (ROLL_NO, NAME, ADDRESS, PHONE, AGE) VALUES


(1, 'Ram', 'Delhi', 'XXXXXXXXXX', 18),
(2, 'Ramesh', 'Gurgaon', 'XXXXXXXXXX', 18),
(3, 'Sujit', 'Rohtak', 'XXXXXXXXXX', 20),
(4, 'Suresh', 'Rohtak', 'XXXXXXXXXX', 18);

Output
ROLL_NO NAME ADDRESS PHONE AGE
1 Ram Delhi xxxxxxxxxxxxxx 18
2 RAMESH GURGAON xxxxxxxxxxxxxx 18
3 SUJIT ROHTAK xxxxxxxxxxxxxx 20
4 SURESH ROHTAK xxxxxxxxxxxxxx 18
3 SUJIT ROHTAK xxxxxxxxxxxxxx 20
2 RAMESH GURGAON xxxxxxxxxxxxxx 18

If we don’t want to specify the column names (and you’re inserting data into all columns), we can
directly insert values in the order they appear in the table structure.

Here's an example:

Query:
INSERT INTO Student
VALUES ('5','HARSH','WEST BENGAL',
'XXXXXXXXXX','19');
Output
ROLL_NO NAME ADDRESS PHONE Age
1 Ram Delhi XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
4 SURESH Delhi XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
2 RAMESH GURGAON XXXXXXXXXX 18
5 HARSH WEST BENGAL XXXXXXXXXX 19

2. Inserting Data into Specific Columns (Flexible Method)


In some cases, you might want to insert data into only certain columns, leaving the others empty or
with default values. In such cases, we can specify the column names explicitly.

Syntax

INSERT INTO table_name (column1, column2, column3


VALUES ( value1, value2, value);
Parameters:
 table_name: name of the table.
 column1, column2..: name of first column, second column.
 value1, value2, value..: the values for each specified column of the
new record.
Example :
Let’s say we only want to insert the student's ID, name, and age
into the Students table, and leave the address and phone number
as NULL (the default value).

INSERT INTO Student (ROLL_NO, NAME, Age)


VALUES ('5', "PRATIK", 19');

Output:

ROLL_NO NAME ADDRESS PHONE Age


1 Ram Delhi XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
4 SURESH Delhi XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
2 RAMESH GURGAON XXXXXXXXXX 18
5 PRATIK null null 19

Note: Columns not included in the INSERT statement are filled with default values (typically NULL).

Inserting Multiple Rows at Once


Instead of running multiple INSERT INTO commands, you can insert multiple
rows into a table in a single query. This is more efficient and reduces the
number of database operations.
Syntax

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


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

Example:
If we want to add multiple students to the Students table in one go, the query would
look like this:
INSERT INTO Student (ROLL_NO, NAME, AGE, ADDRESS,
PHONE)
VALUES
(6, 'Amit Kumar', 15, 'Delhi', 'XXXXXXXXXX'),
(7, 'Gauri Rao', 18, 'Bangalore', 'XXXXXXXXXX'),
(8, 'Manav Bhatt', 17, 'New Delhi', 'XXXXXXXXXX'),
(9, 'Riya Kapoor', 10, 'Udaipur', 'XXXXXXXXXX');
Output:

ROLL_NO NAME ADDRESS PHONE AGE


1 Ram Delhi XXXXXXXXXX 18
2 Ramesh Gurgaon XXXXXXXXXX 18
3 Sujit Rohtak XXXXXXXXXX 20
4 Suresh Rohtak XXXXXXXXXX 18
5 Pratik NULL NULL 19
6 Amit Kumar Delhi XXXXXXXXXX 15
7 Gauri Rao Bangalore XXXXXXXXXX 18
8 Manav Bhatt New Delhi XXXXXXXXXX 17
9 Riya Kapoor Udaipur XXXXXXXXXX 10

Explanation:
 This method is faster than running multiple individual INSERT INTO commands.
 If you're inserting more than 1000 rows, consider using bulk insert or multiple insert
statements for efficiency.

Inserting Data from One Table into Another Table


We can also copy data
from one table into another table using the INSERT INTO SELECT statement. This is very useful
when we want to move or replicate data from one table to another without manually typing all the
data.

Syntax 1: Insert All Columns from Another Table

INSERT INTO target_table


SELECT * FROM source_table;
Example: If you want to copy all data from the OldStudents table into the Students table,
use this query:
INSERT INTO Students
SELECT * FROM OldStudents;
Syntax 2: Insert Specific Columns from Another Table

INSERT INTO target_table (col1, col2, ...)


SELECT col1, col2, ...
FROM source_table;

Example: Let’s say we want to copy only


the Name and Age columns from OldStudents into Students:
INSERT INTO Students (Name, Age)
SELECT Name, Age
FROM OldStudents;

Syntax 3: Insert Specific Rows Based on Condition


You can also insert specific rows based on a condition
by using the WHERE clause with the SELECT statement.
INSERT INTO target_table
SELECT * FROM source_table
WHERE condition;
Example: If we want to copy only students older than 20 years
from OldStudents to Students, we would write:
INSERT INTO Students
SELECT * FROM OldStudents
WHERE Age > 20;
Important Points About SQL INSERT INTO Statement
 Multiple Inserts: You can insert multiple rows at once by separating
each set of values with commas. This reduces the number of queries you
need to run.
 NULL Values: If you don't insert data into a column, it will typically be
set to NULL unless the column has a default value.
 Order of Columns: When using the simple INSERT INTO syntax
without specifying column names, the values must be in the exact same
order as the columns are defined in the table.
 Default Values: Columns not mentioned in the INSERT
INTO statement will be filled with their default values (often NULL).
 Efficiency: Inserting multiple rows at once is much more efficient than
doing it one by one.

SQL UPDATE Statement


In SQL, the UPDATE statement is used to modify existing records in a table. Whether
you are updating a single record or multiple records at once, SQL provides the
necessary functionality to make these changes. Whether you are working with a small
dataset or handling large-scale databases, the UPDATE statement plays a crucial role
in maintaining the integrity of your data.

How the SQL UPDATE Statement Works


The UPDATE statement in SQL is used to modify the data of an existing record in a
database table. We can update single or multiple columns in a single query using the
UPDATE statement as per our requirement. Whether you need to correct data,
change values based on certain conditions, or update multiple fields simultaneously,
the UPDATE statement provides a simple yet effective way to perform these
operations.
key points about UPDATE statement
1. Modify Specific Data: The UPDATE statement can be used to change specific
data in one or more columns for rows that meet a certain condition.
2. Target Specific Rows: You can control which rows to update by using
the WHERE clause. If you omit the WHERE clause, all rows in the table will be
updated, so it’s important to use this clause carefully to avoid unintended changes.
3. Single or Multiple Columns: The UPDATE statement allows you to modify one or
more columns at a time. This makes it versatile when you need to update multiple
pieces of information for the same record.
4. Efficiency: Using UPDATE is more efficient than deleting and re-inserting data
because it directly modifies the existing record without affecting other rows in the
table.
5. Data Integrity: The UPDATE statement helps maintain data integrity by allowing
you to fix errors or modify data without needing to remove and re-add records,
ensuring that related data remains consistent.

Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2,...
WHERE condition;

Parameters
 UPDATE: The SQL command used to modify the data in a table.

 SET: This clause defines which columns will be updated and what their new
values will be.

 WHERE: The condition that determines which rows will be updated. Without it,
all rows will be affected.

 table_name: name of the table in which you want to make updates

 column1, column2, ...: The columns you want to update.

 value1, value2, ...: The new values to assign to these columns.


 condition: Specifies which rows to update. This condition is crucial, as omitting
it will update all rows in the table.

Note: In the above query the SET statement is used to set new values to the
particular column and the WHERE clause is used to select the rows for which the
columns are needed to be updated. If we have not used the WHERE clause then the
columns in all the rows will be updated. So the WHERE clause is used to choose the
particular rows.

Examples of SQL UPDATE Statement


Let’s start by creating a
table and inserting some sample data, which we will use for the UPDATE statement
examples. The Customer table stores information about individual customers, including
their unique CustomerID, personal details like CustomerName and LastName, as well as
their contact details such as Phone and Country.

Query:
CREATE TABLE Customer(
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age int(2),
Phone int(10)
);

-- Insert some sample data into the Customers table

INSERT INTO Customer (CustomerID, CustomerName,


LastName, Country, Age, Phone)
VALUES (1, 'Shubham', 'Thakur',
'India','23','xxxxxxxxxx'),
(2, 'Aman ', 'Chopra',
'Australia','21','xxxxxxxxxx'),
(3, 'Naveen', 'Tulasi', 'Sri
lanka','24','xxxxxxxxxx'),
(4, 'Aditya', 'Arpan',
'Austria','21','xxxxxxxxxx'),
(5, 'Nishant. Salchichas S.A.', 'Jain',
'Spain','22','xxxxxxxxxx');

Output

.
Example 1: Update Single Column Using UPDATE Statement
We have a Customer table and we want to Update the CustomerName where the
Age is 22.

Query:
UPDATE Customer
SET CustomerName = 'Nitin'
WHERE Age = 22;
Output:
Explanation: Only the rows where Age is 22 will be updated, and
the CustomerName will be set to 'Nitin'.

Example 2: Updating Multiple Columns using UPDATE Statement

We need to update both the CustomerName and Country for a specific CustomerID.
Query:

UPDATE Customer
SET CustomerName = 'Satyam',
Country = 'USA'
WHERE CustomerID = 1;
Output:
Explanation: For the row where CustomerID is 1, both CustomerName and Country will
be updated simultaneously.

Note: For updating multiple columns we have used comma(,) to separate the names
and values of two columns.

Example 3: Omitting WHERE Clause in UPDATE Statement

If we accidentally omit the WHERE clause, all the rows in the table will be updated,
which is a common mistake. Let’s update the CustomerName for every record in the
table:

Query:
UPDATE Customer
SET CustomerName = 'Shubham';
Output
Explanation: This will set the CustomerName for every row in the Customer table to
'Shubham'. Be careful while omitting the WHERE clause, as this action is irreversible
unless you have a backup.

Optimizing Your SQL UPDATE Queries


 Avoid frequent updates: Constantly updating rows can slow down
performance. Batch updates or consider using a database trigger to handle
automatic updates.
 Index relevant columns: Ensure that columns in the WHERE clause (such
as CustomerID) are indexed. This will improve the speed of the update operation.

Important Points About SQL UPDATE Statement


1. Always use the WHERE clause: The most important point when using
the UPDATE statement is to always include a WHERE clause unless you genuinely intend
to update all rows.

2. Check your data before updating: Run a SELECT query to view the data you want
to update before executing the UPDATE statement. This helps avoid accidental data
modifications.
SELECT * FROM Customer WHERE Age = 22;
3. Use transactions for critical updates: When performing updates in a production
environment, consider using transactions. Transactions allow you to commit or roll
back changes as needed.
BEGIN TRANSACTION;
UPDATE Customer SET CustomerName = 'John'
WHERE CustomerID = 3;
COMMIT; -- Use ROLLBACK to undo if
necessary

SQL DELETE Statement



The SQL DELETE statement is an essential command in SQL used to remove one or
more rows from a database table. Unlike the DROP statement, which removes the
entire table, the DELETE statement removes data (rows) from the table retaining only
the table structure, constraints, and schema. Whether you need to delete a single row
based on a condition or remove an entire dataset, understanding this command will
help you manage your data effectively.

Using SQL DELETE Statement for Data Removal


The SQL DELETE statement is part of the Data Manipulation Language (DML) and is
used to remove data from a table. The key advantage of using DELETE is that it allows
you to specify a condition (using the WHERE clause) to delete only the rows that match
certain criteria. This ensures you don’t accidentally remove all the data from the table
unless that is your intention.

Syntax:
DELETE FROM table_name
WHERE some_condition;
Parameter Explanation
 Some_condition: A condition used to filter the rows you want to delete.
 table_name: The name of the table from which you want to delete the rows
Note: We can delete single as well as multiple records depending on the condition we
provide in the WHERE clause. If we omit the WHERE clause then all of the records
will be deleted and the table will be empty.

Examples of SQL DELETE Statement


Assume we have created a table named GFG_Employee in SQL, which contains the
personal details of the Employee including their id, name, email and department etc.
as shown below −
CREATE TABLE GFG_Employees (
id INT PRIMARY KEY,
name VARCHAR (20) ,
email VARCHAR (25),
department VARCHAR(20)
);
INSERT INTO GFG_Employees (id, name, email,
department) VALUES
(1, 'Jessie', '[email protected]',
'Development'),
(2, 'Praveen', '[email protected]', 'HR'),
(3, 'Bisa', '[email protected]', 'Sales'),
(4, 'Rithvik', '[email protected]', 'IT'),
(5, 'Suraj', '[email protected]', 'Quality
Assurance'),
(6, 'Om', '[email protected]', 'IT'),
(7, 'Naruto', '[email protected]',
'Development');

Select * From GFG_Employees;


Output

Example 1: Deleting Single Record


We can use the DELETE statement with a condition to delete a specific row from a
table. The WHERE clause ensures only the intended record is removed. We can
delete the records named Rithvik by using the below query:

Query:
DELETE FROM GFG_Employees
WHERE NAME = 'Rithvik';

Output:

Example 2: Deleting Multiple Records


To delete multiple records, you can
specify a condition that matches several rows. Let's delete the rows from the
table GFG_Employees where the department is "Development".
This will delete 2 rows (the first row and the seventh row).

Query
DELETE FROM GFG_Employees
WHERE department = 'Development';
Output

Example 3: Delete All Records from a Table


If we need to delete all records
from the table, we can omit the WHERE clause, or alternatively use the DELETE
statement with an asterisk (*) to denote all rows.

Query:
DELETE FROM GFG_Employees;
Or
DELETE * FROM GFG_Employees;
Output:

All of the records in the table will be deleted, there are no records left to display.
The table GFG_Employees will become empty.

Rolling Back DELETE Operations


Since the DELETE statement is a DML operation, it can be rolled back when executed in a
statement. If you accidentally delete records or need to repeat the process, you can use
the ROLLBACK command.

Query:
START TRANSACTION;
DELETE FROM GFG_Employees WHERE department =
'Development';
-- If needed, you can rollback the deletion
ROLLBACK;
Explanation: The ROLLBACK command will undo the changes made by the DELETE statement,
effectively restoring the records that were deleted during the transaction.

Best Practices for Using SQL DELETE


To use the SQL DELETE statement safely and efficiently, here are some
best practices:
1. Use Transactions: Wrap DELETE statements in transactions to
provide an option to roll back changes if necessary. This ensures data
integrity.
2. Always Use a WHERE Clause: Avoid deleting all rows by accident.
Always filter records using a WHERE clause to specify which rows to
delete. Omitting the WHERE clause will delete all records.
3. Backup Data: Before performing large deletions, ensure that you
have a backup of the data to avoid irreversible loss.
4. Test on Development Server: Always test your DELETE queries on a
development or staging environment to ensure they produce the desired
result before executing them on a live database.
5. Optimize Deletions: For large datasets, delete records in batches to
reduce performance impact and avoid long-running queries.
6. Use Caution When Deleting Data: Be extra cautious when deleting
records from sensitive or production databases. Always verify the
condition in the WHERE clause to ensure you're deleting the right data.

You might also like