SlideShare a Scribd company logo
1 of 33
SQL
Ahmed Farag
Information Systems Dept.
Faculty of Computers and Information
Menoufia University, Egypt.
MySQL Insert
MySQL
Insert
• The INSERT statement allows you to insert one or more rows
into a table. The following illustrates the syntax of the INSERT
statement:
INSERT INTO table(c1,c2,...)
VALUES (v1,v2,...);
• In this syntax,
• First, you specify the table name and a list of comma-
separated columns inside parentheses after the INSERT
INTO clause.
• Then, you put a comma-separated list of values of the
corresponding columns inside the parentheses following
the VALUES keyword.
• The number of columns and values must be the same. In
addition, the positions of columns must be corresponding
with the positions of their values.
MySQL
Insert
• To add multiple rows into a table using a single INSERT
statement, you use the following syntax:
• In this syntax,
• First, you specify the table name and a list of comma-
separated columns inside parentheses after the INSERT
INTO clause.
• Then, you put a comma-separated list of values of the
corresponding columns inside the parentheses following
the VALUES keyword.
INSERT INTO table(c1,c2,...)
VALUES
(v11,v12,...),
(v21,v22,...),
...
(vnn,vn2,...);
MySQL
Insert
examples
• Example 1:
INSERT INTO productlines VALUES ('Mobiles','Mobiles',null,null);
MySQL
Insert
examples
• Example 2:
INSERT INTO productlines (productLine,textDescription)
VALUES ('TV','TV');
MySQL INSERT INTO SELECT
MySQL
INSERT
INTO
SELECT
• Besides using row values in the VALUES clause, you can use
the result of a SELECT statement as the data source for the
INSERT statement.
• The following illustrates the syntax of the INSERT INTO SELECT
statement:
• As you can see, instead of using the VALUES clause, you can
use a SELECT statement. The SELECT statement can retrieve
data from one or more tables.
INSERT INTO table_name(column_list)
SELECT
select_list
FROM
another_table;
MySQL
INSERT
INTO
SELECT
Example
• Suppose we have the following suppliers table with the
following structure:
• Note that you will learn how to create a new table in the
future tutorial. For now, you just need to execute this
statement to create the suppliers table.
CREATE TABLE suppliers (
supplierNumber INT AUTO_INCREMENT,
supplierName VARCHAR(50) NOT NULL,
phone VARCHAR(50),
addressLine1 VARCHAR(50),
addressLine2 VARCHAR(50),
city VARCHAR(50),
state VARCHAR(50),
postalCode VARCHAR(50),
country VARCHAR(50),
customerNumber INT
PRIMARY KEY (supplierNumber)
);
MySQL
INSERT
INTO
SELECT
Example
• Because of the new contracts, all customers from California,
USA become the company’s suppliers. The following query
finds all customers in California, USA:
SELECT
customerNumber,
customerName,
phone,
addressLine1,
addressLine2,
city,
state,
postalCode,
country
FROM
customers
WHERE
country = 'USA' AND
state = 'CA';
MySQL
INSERT
INTO
SELECT
Example
• Now, you need to insert these customers from the customers
table into the suppliers table. The following INSERT INTO
SELECT statement helps you to do so:
INSERT INTO suppliers (
supplierName, phone, addressLine1, addressLin
e2,
city, state, postalCode, country, customerNumbe
r
)
SELECT
customerName, phone, addressLine1, addressLine
2,
city, state , postalCode, country, customerNumb
er
FROM
customers
WHERE
country = 'USA' AND
state = 'CA';
MySQL INSERT ON DUPLICATE KEY UPDATE
MySQL
INSERT
ON
DUPLICA
TE KEY
UPDATE
• When you insert a new row into a table if the row causes a
duplicate in UNIQUE index or PRIMARY KEY , MySQL will issue an
error.
• However, if you specify the ON DUPLICATE KEY UPDATE option in
the INSERT statement, MySQL will update the existing row with
the new values instead.
• The syntax of INSERT ON DUPLICATE KEY UPDATE statement is as
follows:
• The only addition to the INSERT statement is the ON
DUPLICATE KEY UPDATE clause where you specify a list of
column-value-pair assignments in case of duplicate.
INSERT INTO table (column_list)
VALUES (value_list)
ON DUPLICATE KEY UPDATE
c1 = v1,
c2 = v2,
...;
MySQL
INSERT
ON
DUPLICA
TE KEY
UPDATE
• Basically, the statement first tries to insert a new row into the
table. If a duplicate error occurs, it will update the existing
row with the value specified in the ON DUPLICATE KEY
UPDATE clause.
• MySQL returns the number of affected-rows based on the
action it performs:
• If the new row is inserted, the number of affected-rows is
1.
• If the existing row is updated, the number of affected-
rows is 2.
• If the existing row is updated using its current values, the
number of affected-rows is 0.
MySQL
INSERT
ON
DUPLICA
TE KEY
UPDATE
• To use the values from the INSERT clause in the DUPLICATE
KEY UPDATE clause, you use the VALUES() function as follows:
INSERT INTO table_name(c1)
VALUES(c1)
ON DUPLICATE KEY UPDATE c1 = VALUES(c1) + 1;
• The statement above sets the value of the c1 to its current
value specified by the expression VALUES(c1) plus 1 if there is
a duplicate in UNIQUE index or PRIMARY KEY.
MySQL
INSERT
ON
DUPLICAT
E KEY
UPDATE
Example
• First, create a table named devices to store the network
devices.
• Next, insert rows into the devices table.
CREATE TABLE devices (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
INSERT INTO devices(name)
VALUES('Router F1'),('Switch 1'),('Switch 2');
• Then, query the data from the devices table to verify the insert:
SELECT
id,
name
FROM
devices;
MySQL
INSERT
ON
DUPLICAT
E KEY
UPDATE
Example
• After that, insert one more row into the devices table.
INSERT INTO
devices(name)
VALUES
('Printer')
ON DUPLICATE KEY UPDATE name = 'Printer';
• Because there is no duplicate, MySQL inserts a new row into
the devices table. The statement above has the same effect as
the following statement:
INSERT INTO devices(name)
VALUES ('Printer');
MySQL
INSERT
ON
DUPLICAT
E KEY
UPDATE
Example
• Finally, insert a row with a duplicate value in the id column.
• Because a row with id 4 already exists in the devices table, the
statement updates the name from Printer to Central Printer.
INSERT INTO devices(id,name)
VALUES
(4,'Printer')
ON DUPLICATE KEY UPDATE name = 'Central Printer';
MySQL INSERT IGNORE Statement
MySQL
INSERT
IGNORE
Statement
• When you use the INSERT statement to add multiple rows to a
table and if an error occurs during the processing, MySQL
terminates the statement and returns an error. As the result, no
rows are inserted into the table.
• However, if you use the INSERT IGNORE statement, the rows with
invalid data that cause the error are ignored and the rows with
valid data are inserted into the table.
• The syntax of the INSERT IGNORE statement is as follows:
INSERT IGNORE INTO table(column_list)
VALUES( value_list),
( value_list),
...
MySQL
INSERT
IGNORE
Statement
• We will create a new table called subscribers for the
demonstration.
CREATE TABLE subscribers (
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(50) NOT NULL UNIQUE
);
• The UNIQUE constraint ensures that no duplicate email exists
in the email column.
• The following statement inserts a new row into the
subscribers table:
INSERT INTO subscribers(email)
VALUES('john.doe@gmail.com');
• It worked as expected.
MySQL
INSERT
IGNORE
Statement
• Let’s execute another statement that inserts two rows into
the subscribers table:
• It returns an error.
• As indicated in the error message, the email
john.doe@gmail.com violates the UNIQUE constraint.
• However, if you use the INSERT IGNORE statement instead.
INSERT INTO subscribers(email)
VALUES('john.doe@gmail.com'),
('jane.smith@ibm.com');
Error Code: 1062. Duplicate entry 'john.doe@gmail.com' for key 'e
mail'
INSERT IGNORE INTO subscribers(email)
VALUES('john.doe@gmail.com'),
('jane.smith@ibm.com');
• MySQL returned a message indicating that one row was
inserted and the other row was ignored.
1 row(s) affected, 1 warning(s): 1062 Duplicate entry 'john.doe@gmail.com'
for key 'email' Records: 2 Duplicates: 1 Warnings: 1
MySQL
INSERT
IGNORE
Statement
• To find the detail of the warning, you can use the SHOW
WARNINGS command as shown below:
SHOW WARNINGS;
• If you query data from subscribers table, you will find that
only one row was actually inserted and the row that causes
the error was not.
MySQL UPDATE
MySQL
INSERT
IGNORE
Statement
• You use the UPDATE statement to update existing data in a
table. you can also use the UPDATE statement to change
column values of a single row, a group of rows, or all rows in a
table.
• The following illustrates the syntax of the MySQL UPDATE
statement:
UPDATE [LOW_PRIORITY] [IGNORE] table_name
SET
column_name1 = expr1,
column_name2 = expr2,
...
[WHERE
condition];
MySQL
INSERT
IGNORE
Statement
• In the UPDATE statement:
• First, specify the table name that you want to update
data after the UPDATE keyword.
• Second, the SET clause specifies which column that you
want to modify and the new values. To update multiple
columns, you use a list of comma-separated assignments.
You supply a value in each column’s assignment in the
form of a literal value, an expression, or a subquery.
• Third, specify which rows to be updated using a condition
in the WHERE clause. The WHERE clause is optional. If
you omit the WHERE clause, the UPDATE statement will
update all rows in the table.
• Notice that the WHERE clause is so important that you should
not forget. Sometimes, you may want to change just one row;
However, you may forget the WHERE clause and accidentally
update all rows of the table.
MySQL
INSERT
IGNORE
Statement
• MySQL supports two modifiers in the UPDATE statement.
• The LOW_PRIORITY modifier instructs the UPDATE
statement to delay the update until there is no
connection reading data from the table. The
LOW_PRIORITY takes effect for the storage engines that
use table-level locking only, for example, MyISAM,
MERGE, MEMORY.
• The IGNORE modifier enables the UPDATE statement to
continue updating rows even if errors occurred. The rows
that cause errors such as duplicate-key conflicts are not
updated.
Using
MySQL
UPDATE to
modify
values in a
single
column
example
• In this example, we are going to update the email of Mary
Patterson to the new email
mary.patterso@classicmodelcars.com.
• First, to ensure the update is successful, we query Mary’s
email from the employees table using the following SELECT
statement:
SELECT
firstname, lastname, email
FROM
employees
WHERE
employeeNumber = 1056;
Using
MySQL
UPDATE to
modify
values in a
single
column
example
• Second, we can update Mary’s email to the new email
mary.patterson@classicmodelcars.com using the UPDATE
statement as shown in the following query:
UPDATE employees
SET
email = 'mary.patterson@classicmodelcars.com'
WHERE
employeeNumber = 1056;
• Because we just want to update one row, we use the WHERE
clause to specify the row using the employee number 1056.
The SET clause sets the value of the email column to the new
email.
• Third, we execute the SELECT statement again to verify the
change.
SELECT
firstname, lastname, email FROM employees
WHERE employeeNumber = 1056;
Using
MySQL
UPDATE to
modify
values in
multiple
columns
• To update values in the multiple columns, you need to specify
the assignments in the SET clause. For example, the following
statement updates both last name and email columns of
employee number 1056:
UPDATE employees
SET
lastname = 'Hill',
email = 'mary.hill@classicmodelcars.com'
WHERE
employeeNumber = 1056;
• To update values in the multiple columns, you need to specify
the assignments in the SET clause. For example, the following
statement updates both last name and email columns of
employee number 1056:
Using MySQL UPDATE to update rows
returned by a SELECT statement
MySQL
INSERT
IGNORE
Statement
• You can supply the values for the SET clause from a SELECT
statement that queries data from other tables.
• For example, in the customers table, some customers do not
have any sale representative. The value of the column
saleRepEmployeeNumber is NULL as follows:
SELECT
customername, salesRepEmployeeNumber
FROM
customers
WHERE
salesRepEmployeeNumber IS NULL;
MySQL
INSERT
IGNORE
Statement
UPDATE customers
SET
salesRepEmployeeNumber = (SELECT
employeeNumber
FROM
employees
WHERE
jobtitle = 'Sales Rep'
LIMIT 1)
WHERE
salesRepEmployeeNumber IS NULL;

More Related Content

What's hot

MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index TuningManikanda kumar
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functionsVikas Gupta
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive dataAmrit Kaur
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL FundamentalsBrian Foote
 
Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle SqlAhmed Yaseen
 
Retrieving data using the sql select statement
Retrieving data using the sql select statementRetrieving data using the sql select statement
Retrieving data using the sql select statementSyed Zaid Irshad
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize outputSyed Zaid Irshad
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Achmad Solichin
 

What's hot (18)

MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
 
Lab1 select statement
Lab1 select statementLab1 select statement
Lab1 select statement
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
Not in vs not exists
Not in vs not existsNot in vs not exists
Not in vs not exists
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
 
Oracle: Basic SQL
Oracle: Basic SQLOracle: Basic SQL
Oracle: Basic SQL
 
10053 - null is not nothing
10053 - null is not nothing10053 - null is not nothing
10053 - null is not nothing
 
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
Views, Triggers, Functions, Stored Procedures,  Indexing and JoinsViews, Triggers, Functions, Stored Procedures,  Indexing and Joins
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
 
Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle Sql
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
Retrieving data using the sql select statement
Retrieving data using the sql select statementRetrieving data using the sql select statement
Retrieving data using the sql select statement
 
Oracle SQL Advanced
Oracle SQL AdvancedOracle SQL Advanced
Oracle SQL Advanced
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize output
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
 
Sql select
Sql select Sql select
Sql select
 

Similar to Sql modifying data - MYSQL part I

DML Statements.pptx
DML Statements.pptxDML Statements.pptx
DML Statements.pptxUnitedGamer1
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commandsBelle Wx
 
SQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdfSQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdfAnishurRehman1
 
Null values, insert, delete and update in database
Null values, insert, delete and update in databaseNull values, insert, delete and update in database
Null values, insert, delete and update in databaseHemant Suthar
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraintsVineeta Garg
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptxSherinRappai
 
MySQL.pptx comuterscience from kvsbbsrs.
MySQL.pptx comuterscience from kvsbbsrs.MySQL.pptx comuterscience from kvsbbsrs.
MySQL.pptx comuterscience from kvsbbsrs.sudhasuryasnata06
 
Intro to tsql unit 9
Intro to tsql   unit 9Intro to tsql   unit 9
Intro to tsql unit 9Syed Asrarali
 
2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL UsedTheVerse1
 

Similar to Sql modifying data - MYSQL part I (20)

Les08
Les08Les08
Les08
 
Sql wksht-2
Sql wksht-2Sql wksht-2
Sql wksht-2
 
DML Statements.pptx
DML Statements.pptxDML Statements.pptx
DML Statements.pptx
 
1 introduction to my sql
1 introduction to my sql1 introduction to my sql
1 introduction to my sql
 
ADV PPT 2 LAB.pptx
ADV PPT 2 LAB.pptxADV PPT 2 LAB.pptx
ADV PPT 2 LAB.pptx
 
Sql wksht-6
Sql wksht-6Sql wksht-6
Sql wksht-6
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
Manipulating data
Manipulating dataManipulating data
Manipulating data
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
SQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdfSQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdf
 
Query
QueryQuery
Query
 
Assignment#02
Assignment#02Assignment#02
Assignment#02
 
Null values, insert, delete and update in database
Null values, insert, delete and update in databaseNull values, insert, delete and update in database
Null values, insert, delete and update in database
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraints
 
SQL report
SQL reportSQL report
SQL report
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
MySQL.pptx comuterscience from kvsbbsrs.
MySQL.pptx comuterscience from kvsbbsrs.MySQL.pptx comuterscience from kvsbbsrs.
MySQL.pptx comuterscience from kvsbbsrs.
 
Intro to tsql unit 9
Intro to tsql   unit 9Intro to tsql   unit 9
Intro to tsql unit 9
 
2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used
 

More from Ahmed Farag

Introduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDBIntroduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDBAhmed Farag
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP conceptsAhmed Farag
 
Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)Ahmed Farag
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams Ahmed Farag
 
intro to pointer C++
intro to  pointer C++intro to  pointer C++
intro to pointer C++Ahmed Farag
 

More from Ahmed Farag (10)

Intro to php
Intro to phpIntro to php
Intro to php
 
Normalization
NormalizationNormalization
Normalization
 
Introduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDBIntroduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDB
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
 
Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
OOP C++
OOP C++OOP C++
OOP C++
 
Functions C++
Functions C++Functions C++
Functions C++
 
intro to pointer C++
intro to  pointer C++intro to  pointer C++
intro to pointer C++
 
Intro to C++
Intro to C++Intro to C++
Intro to C++
 

Recently uploaded

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Sql modifying data - MYSQL part I

  • 1. SQL Ahmed Farag Information Systems Dept. Faculty of Computers and Information Menoufia University, Egypt.
  • 3. MySQL Insert • The INSERT statement allows you to insert one or more rows into a table. The following illustrates the syntax of the INSERT statement: INSERT INTO table(c1,c2,...) VALUES (v1,v2,...); • In this syntax, • First, you specify the table name and a list of comma- separated columns inside parentheses after the INSERT INTO clause. • Then, you put a comma-separated list of values of the corresponding columns inside the parentheses following the VALUES keyword. • The number of columns and values must be the same. In addition, the positions of columns must be corresponding with the positions of their values.
  • 4. MySQL Insert • To add multiple rows into a table using a single INSERT statement, you use the following syntax: • In this syntax, • First, you specify the table name and a list of comma- separated columns inside parentheses after the INSERT INTO clause. • Then, you put a comma-separated list of values of the corresponding columns inside the parentheses following the VALUES keyword. INSERT INTO table(c1,c2,...) VALUES (v11,v12,...), (v21,v22,...), ... (vnn,vn2,...);
  • 5. MySQL Insert examples • Example 1: INSERT INTO productlines VALUES ('Mobiles','Mobiles',null,null);
  • 6. MySQL Insert examples • Example 2: INSERT INTO productlines (productLine,textDescription) VALUES ('TV','TV');
  • 8. MySQL INSERT INTO SELECT • Besides using row values in the VALUES clause, you can use the result of a SELECT statement as the data source for the INSERT statement. • The following illustrates the syntax of the INSERT INTO SELECT statement: • As you can see, instead of using the VALUES clause, you can use a SELECT statement. The SELECT statement can retrieve data from one or more tables. INSERT INTO table_name(column_list) SELECT select_list FROM another_table;
  • 9. MySQL INSERT INTO SELECT Example • Suppose we have the following suppliers table with the following structure: • Note that you will learn how to create a new table in the future tutorial. For now, you just need to execute this statement to create the suppliers table. CREATE TABLE suppliers ( supplierNumber INT AUTO_INCREMENT, supplierName VARCHAR(50) NOT NULL, phone VARCHAR(50), addressLine1 VARCHAR(50), addressLine2 VARCHAR(50), city VARCHAR(50), state VARCHAR(50), postalCode VARCHAR(50), country VARCHAR(50), customerNumber INT PRIMARY KEY (supplierNumber) );
  • 10. MySQL INSERT INTO SELECT Example • Because of the new contracts, all customers from California, USA become the company’s suppliers. The following query finds all customers in California, USA: SELECT customerNumber, customerName, phone, addressLine1, addressLine2, city, state, postalCode, country FROM customers WHERE country = 'USA' AND state = 'CA';
  • 11. MySQL INSERT INTO SELECT Example • Now, you need to insert these customers from the customers table into the suppliers table. The following INSERT INTO SELECT statement helps you to do so: INSERT INTO suppliers ( supplierName, phone, addressLine1, addressLin e2, city, state, postalCode, country, customerNumbe r ) SELECT customerName, phone, addressLine1, addressLine 2, city, state , postalCode, country, customerNumb er FROM customers WHERE country = 'USA' AND state = 'CA';
  • 12. MySQL INSERT ON DUPLICATE KEY UPDATE
  • 13. MySQL INSERT ON DUPLICA TE KEY UPDATE • When you insert a new row into a table if the row causes a duplicate in UNIQUE index or PRIMARY KEY , MySQL will issue an error. • However, if you specify the ON DUPLICATE KEY UPDATE option in the INSERT statement, MySQL will update the existing row with the new values instead. • The syntax of INSERT ON DUPLICATE KEY UPDATE statement is as follows: • The only addition to the INSERT statement is the ON DUPLICATE KEY UPDATE clause where you specify a list of column-value-pair assignments in case of duplicate. INSERT INTO table (column_list) VALUES (value_list) ON DUPLICATE KEY UPDATE c1 = v1, c2 = v2, ...;
  • 14. MySQL INSERT ON DUPLICA TE KEY UPDATE • Basically, the statement first tries to insert a new row into the table. If a duplicate error occurs, it will update the existing row with the value specified in the ON DUPLICATE KEY UPDATE clause. • MySQL returns the number of affected-rows based on the action it performs: • If the new row is inserted, the number of affected-rows is 1. • If the existing row is updated, the number of affected- rows is 2. • If the existing row is updated using its current values, the number of affected-rows is 0.
  • 15. MySQL INSERT ON DUPLICA TE KEY UPDATE • To use the values from the INSERT clause in the DUPLICATE KEY UPDATE clause, you use the VALUES() function as follows: INSERT INTO table_name(c1) VALUES(c1) ON DUPLICATE KEY UPDATE c1 = VALUES(c1) + 1; • The statement above sets the value of the c1 to its current value specified by the expression VALUES(c1) plus 1 if there is a duplicate in UNIQUE index or PRIMARY KEY.
  • 16. MySQL INSERT ON DUPLICAT E KEY UPDATE Example • First, create a table named devices to store the network devices. • Next, insert rows into the devices table. CREATE TABLE devices ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) ); INSERT INTO devices(name) VALUES('Router F1'),('Switch 1'),('Switch 2'); • Then, query the data from the devices table to verify the insert: SELECT id, name FROM devices;
  • 17. MySQL INSERT ON DUPLICAT E KEY UPDATE Example • After that, insert one more row into the devices table. INSERT INTO devices(name) VALUES ('Printer') ON DUPLICATE KEY UPDATE name = 'Printer'; • Because there is no duplicate, MySQL inserts a new row into the devices table. The statement above has the same effect as the following statement: INSERT INTO devices(name) VALUES ('Printer');
  • 18. MySQL INSERT ON DUPLICAT E KEY UPDATE Example • Finally, insert a row with a duplicate value in the id column. • Because a row with id 4 already exists in the devices table, the statement updates the name from Printer to Central Printer. INSERT INTO devices(id,name) VALUES (4,'Printer') ON DUPLICATE KEY UPDATE name = 'Central Printer';
  • 19. MySQL INSERT IGNORE Statement
  • 20. MySQL INSERT IGNORE Statement • When you use the INSERT statement to add multiple rows to a table and if an error occurs during the processing, MySQL terminates the statement and returns an error. As the result, no rows are inserted into the table. • However, if you use the INSERT IGNORE statement, the rows with invalid data that cause the error are ignored and the rows with valid data are inserted into the table. • The syntax of the INSERT IGNORE statement is as follows: INSERT IGNORE INTO table(column_list) VALUES( value_list), ( value_list), ...
  • 21. MySQL INSERT IGNORE Statement • We will create a new table called subscribers for the demonstration. CREATE TABLE subscribers ( id INT PRIMARY KEY AUTO_INCREMENT, email VARCHAR(50) NOT NULL UNIQUE ); • The UNIQUE constraint ensures that no duplicate email exists in the email column. • The following statement inserts a new row into the subscribers table: INSERT INTO subscribers(email) VALUES('john.doe@gmail.com'); • It worked as expected.
  • 22. MySQL INSERT IGNORE Statement • Let’s execute another statement that inserts two rows into the subscribers table: • It returns an error. • As indicated in the error message, the email john.doe@gmail.com violates the UNIQUE constraint. • However, if you use the INSERT IGNORE statement instead. INSERT INTO subscribers(email) VALUES('john.doe@gmail.com'), ('jane.smith@ibm.com'); Error Code: 1062. Duplicate entry 'john.doe@gmail.com' for key 'e mail' INSERT IGNORE INTO subscribers(email) VALUES('john.doe@gmail.com'), ('jane.smith@ibm.com'); • MySQL returned a message indicating that one row was inserted and the other row was ignored. 1 row(s) affected, 1 warning(s): 1062 Duplicate entry 'john.doe@gmail.com' for key 'email' Records: 2 Duplicates: 1 Warnings: 1
  • 23. MySQL INSERT IGNORE Statement • To find the detail of the warning, you can use the SHOW WARNINGS command as shown below: SHOW WARNINGS; • If you query data from subscribers table, you will find that only one row was actually inserted and the row that causes the error was not.
  • 25. MySQL INSERT IGNORE Statement • You use the UPDATE statement to update existing data in a table. you can also use the UPDATE statement to change column values of a single row, a group of rows, or all rows in a table. • The following illustrates the syntax of the MySQL UPDATE statement: UPDATE [LOW_PRIORITY] [IGNORE] table_name SET column_name1 = expr1, column_name2 = expr2, ... [WHERE condition];
  • 26. MySQL INSERT IGNORE Statement • In the UPDATE statement: • First, specify the table name that you want to update data after the UPDATE keyword. • Second, the SET clause specifies which column that you want to modify and the new values. To update multiple columns, you use a list of comma-separated assignments. You supply a value in each column’s assignment in the form of a literal value, an expression, or a subquery. • Third, specify which rows to be updated using a condition in the WHERE clause. The WHERE clause is optional. If you omit the WHERE clause, the UPDATE statement will update all rows in the table. • Notice that the WHERE clause is so important that you should not forget. Sometimes, you may want to change just one row; However, you may forget the WHERE clause and accidentally update all rows of the table.
  • 27. MySQL INSERT IGNORE Statement • MySQL supports two modifiers in the UPDATE statement. • The LOW_PRIORITY modifier instructs the UPDATE statement to delay the update until there is no connection reading data from the table. The LOW_PRIORITY takes effect for the storage engines that use table-level locking only, for example, MyISAM, MERGE, MEMORY. • The IGNORE modifier enables the UPDATE statement to continue updating rows even if errors occurred. The rows that cause errors such as duplicate-key conflicts are not updated.
  • 28. Using MySQL UPDATE to modify values in a single column example • In this example, we are going to update the email of Mary Patterson to the new email mary.patterso@classicmodelcars.com. • First, to ensure the update is successful, we query Mary’s email from the employees table using the following SELECT statement: SELECT firstname, lastname, email FROM employees WHERE employeeNumber = 1056;
  • 29. Using MySQL UPDATE to modify values in a single column example • Second, we can update Mary’s email to the new email mary.patterson@classicmodelcars.com using the UPDATE statement as shown in the following query: UPDATE employees SET email = 'mary.patterson@classicmodelcars.com' WHERE employeeNumber = 1056; • Because we just want to update one row, we use the WHERE clause to specify the row using the employee number 1056. The SET clause sets the value of the email column to the new email. • Third, we execute the SELECT statement again to verify the change. SELECT firstname, lastname, email FROM employees WHERE employeeNumber = 1056;
  • 30. Using MySQL UPDATE to modify values in multiple columns • To update values in the multiple columns, you need to specify the assignments in the SET clause. For example, the following statement updates both last name and email columns of employee number 1056: UPDATE employees SET lastname = 'Hill', email = 'mary.hill@classicmodelcars.com' WHERE employeeNumber = 1056; • To update values in the multiple columns, you need to specify the assignments in the SET clause. For example, the following statement updates both last name and email columns of employee number 1056:
  • 31. Using MySQL UPDATE to update rows returned by a SELECT statement
  • 32. MySQL INSERT IGNORE Statement • You can supply the values for the SET clause from a SELECT statement that queries data from other tables. • For example, in the customers table, some customers do not have any sale representative. The value of the column saleRepEmployeeNumber is NULL as follows: SELECT customername, salesRepEmployeeNumber FROM customers WHERE salesRepEmployeeNumber IS NULL;
  • 33. MySQL INSERT IGNORE Statement UPDATE customers SET salesRepEmployeeNumber = (SELECT employeeNumber FROM employees WHERE jobtitle = 'Sales Rep' LIMIT 1) WHERE salesRepEmployeeNumber IS NULL;