SlideShare uma empresa Scribd logo
1 de 37
Chapter - 8

Manipulating Data
DML
- Insert
- Update
- Delete
- Merge
Data Manipulation Language


A DML statement is executed when you:
– Add new rows to a table
– Modify existing rows in a table
– Remove existing rows from a table



A collection of DML statements that form a logical unit of work is called a Transaction.



Consider a banking database. When a bank customer transfers money from a savings
account to a checking account, the transaction might consist of three separate
operations:
- decrease the savings account,
- increase the checking account,
- and record the transaction in the transaction journal.



The Oracle server must guarantee that all three SQL statements are performed to
maintain the accounts in proper balance. When something prevents one of the statements
in the transaction from executing, the other statements of the transaction must be undone.
Adding a New Row – INSERT

statement
INSERT Statement


Add new rows to a table by using the INSERT statement.




Only one row is inserted at a time with this syntax.
Example :-



Enclose character and date values within single quotation marks.
Inserting Rows with Null Values


Implicit method: Omit the column from the column list.



Explicit method: Specify the NULL keyword in the VALUES clause. specify
the empty string (’’) in the VALUES list for character strings and dates.
Common errors that can occur during user input:



Mandatory value missing for a NOT NULL column



Duplicate value violates uniqueness constraint



Foreign key constraint violated



CHECK constraint violated



Data type mismatch



Value too wide to fit in column
Inserting Special Values


The SYSDATE function records the current date and time.
Inserting Specific Date Values


Add a new employee.



If a date must be entered in a format other than the default format (DDMON-RR), for example, with another century, or a specific time, you must
use the TO_DATE function.
Creating a Script


Use & substitution in a SQL statement to prompt for values.



& is a placeholder for the variable value.



Run the script file and you are prompted for input for the & substitution
variables.



The values you input are then substituted into the statement. This allows you to
run the same script file over and over, but supply a different set of values each
time you run it.
Copying Rows from Another Table


Write your INSERT statement with a subquery.



Do not use the VALUES clause.



Match the number of columns in the INSERT clause to those in the subquery.



The number of columns and their data types in the column list of the INSERT clause
must match the number of values and their data types in the subquery.
Changing Data in a Table – UPDATE

statement
UPDATE Statement


Modify existing rows with the UPDATE statement.



Update more than one row at a time, if required.



Specific row or rows are modified if you specify the WHERE clause.



All rows in the table are modified if you omit the WHERE clause.
Updating Two Columns with a Subquery


Update employee 114’s job and salary to match that of employee 205.
Updating Rows Based on Another Table


Use subqueries in UPDATE statements to update rows in a table based on values
from another table.



The example on the slide updates the COPY_EMP table based on the values from the
EMPLOYEES table.



It changes the department number of all employees with employee 200’s job ID to
employee 100’s current department number.
Updating Rows:

Integrity Constraint Error



In the example on the slide, department number 55 does not exist in the parent table,
DEPARTMENTS, and so you receive the parent key violation ORA-02291.
Removing a Row from a Table – DELETE statement
DELETE

VS

TRUNCATE



After all the rows have been eliminated with the DELETE statement, only the
data structure of the table remains. A more efficient method of emptying a table
is with the TRUNCATE statement.



You can use the TRUNCATE statement to quickly remove all rows from a table
or cluster.



Removing rows with the TRUNCATE statement is faster than removing them
with the DELETE statement for the following reasons:
–
–
–
–

The TRUNCATE statement is a data definition language (DDL) statement and
generates no rollback information.
Truncating a table does not fire the delete triggers of the table.
If the table is the parent of a referential integrity constraint, you cannot truncate
the table.
Disable the constraint before issuing the TRUNCATE statement.
The DELETE Statement


You can remove existing rows from a table by using the DELETE statement.



Specific rows are deleted if you specify the WHERE clause.



All rows in the table are deleted if you omit the WHERE clause.
Deleting Rows Based on Another Table


Use subqueries in DELETE statements to remove rows from a table based on values
from another table.



The subquery searches the DEPARTMENTS table to find the department number based
on the department name containing the string “Public.”



The subquery then feeds the department number to the main query, which deletes rows of
data from the EMPLOYEES table based on this department number.
Deleting Rows:

Integrity Constraint Error

If the parent record that you attempt to delete has child records, then you receive the child
record found violation ORA-02292.
However, if the referential integrity constraint contains the ON DELETE CASCADE option,
then the selected row and its children are deleted from their respective tables.
WITH CHECK OPTION on DML Statements


A subquery is used to identify the table and columns of the DML statement.



The WITH CHECK OPTION keyword prohibits you from changing rows that are not
in the subquery.
Using Explicit

Default Values

•

Specify DEFAULT to set the column to the value previously specified
as the
default value for the column.

•

If no default value for the corresponding column has been specified, Oracle
sets the column to null.
The MERGE Statement


Provides the ability to conditionally update or insert data into a database table



Performs an UPDATE if the row exists, and an INSERT if it is a new row:
– Avoids separate updates
– Increases performance and ease of use
– Is useful in data warehousing applications



The decision whether to update or insert into the target table is based on a condition in the
ON clause.



The MERGE statement is deterministic. You cannot update the same row of the target
table multiple times in the same MERGE statement.



An alternative approach is to use PL/SQL loops and multiple DML statements.



The MERGE statement, however, is easy to use and more simply expressed as a single
SQL statement.
MERGE Statement Syntax
Merging Rows Example :
Database Transactions
Database Transactions


The Oracle server ensures data consistency based on transactions.



Transactions give you more flexibility and control when changing data, and they
ensure data consistency in the event of user process failure or system failure.



Transactions consist of DML statements that make up one consistent change to
the data.



For example, a transfer of funds between two accounts should include the debit
to one account and the credit to another account in the same amount.



Both actions should either fail or succeed together; the credit should not be
committed without the debit.
Advantages of

COMMIT and ROLLBACK Statements



Ensure data consistency



Preview data changes before making
changes permanent



Group logically related operations
Implicit Transaction Processing


An automatic commit occurs under the following circumstances:
– DDL statement is issued
– DCL statement is issued
– Normal exit from iSQL*Plus, without explicitly issuing COMMIT or
ROLLBACK statements



An automatic rollback occurs under an abnormal termination of iSQL*Plus or a
system failure.
Committing Changes


Every data change made during the transaction is temporary until the transaction is
committed.

State of the data before COMMIT or ROLLBACK statements are issued:


Data manipulation operations primarily affect the database buffer; therefore, the previous
state of the data can be recovered.



The current user can review the results of the data manipulation operations by querying
the tables.



Other users cannot view the results of the data manipulation operations made by the
current user. The Oracle server institutes read consistency to ensure that each user sees
data as it existed at the last commit.



The affected rows are locked; other users cannot change the data in the affected rows.
State of the Data after

COMMIT



Data changes are made permanent in the database.



The previous state of the data is permanently lost.



All users can view the results.



Locks on the affected rows are released; those rows are
available for other users to manipulate.



All save points are erased.
State of the Data After

ROLLBACK



Discard all pending changes by using the ROLLBACK
statement:



Data changes are undone.



Previous state of the data is restored.



Locks on the affected rows are released.
Statement-Level Rollbacks


Part of a transaction can be discarded by an implicit rollback if a statement
execution error is detected.



If a single DML statement fails during execution of a transaction, its effect is
undone by a statement level rollback, but the changes made by the previous
DML statements in the transaction are not discarded.



They can be committed or rolled back explicitly by the user.



Oracle issues an implicit commit before and after any data definition language
(DDL) statement. So, even if your DDL statement does not execute
successfully, you cannot roll back the previous statement because the server
issued a commit.



Terminate your transactions explicitly by executing a COMMIT or ROLLBACK
statement.
Locking
In an Oracle database, locks:


Prevent destructive interaction between concurrent
transactions



Require no user action



Automatically use the lowest level of restrictiveness



Are held for the duration of the transaction



Are of two types: explicit locking and implicit locking
What Are Locks?


Locks are mechanisms that prevent destructive interaction between
transactions accessing the same resource, either a user object (such as tables
or rows) or a system object not visible to users (such as shared data structures
and data dictionary rows).

How the Oracle Database Locks Data


Oracle locking is performed automatically and requires no user action.



Implicit locking occurs for SQL statements as necessary, depending on the
action requested. Implicit locking occurs for all SQL statements except
SELECT.



The users can also lock data manually, which is called explicit locking.
Implicit Locking


Two lock modes:
– Exclusive: Locks out other users
– Share: Allows other users to access



High level of data concurrency:
– DML: Table share, row exclusive
– Queries: No locks required
– DDL: Protects object definitions



Locks held until commit or rollback
Summary

Mais conteúdo relacionado

Mais procurados

Sql server ___________session_15(data integrity)
Sql server  ___________session_15(data integrity)Sql server  ___________session_15(data integrity)
Sql server ___________session_15(data integrity)
Ehtisham Ali
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
Ashwin Dinoriya
 
2. DML_INSERT_DELETE_UPDATE
2. DML_INSERT_DELETE_UPDATE2. DML_INSERT_DELETE_UPDATE
2. DML_INSERT_DELETE_UPDATE
Amrit Kaur
 
Intro to tsql unit 9
Intro to tsql   unit 9Intro to tsql   unit 9
Intro to tsql unit 9
Syed Asrarali
 

Mais procurados (17)

Database Management - Lecture 2 - SQL select, insert, update and delete
Database Management - Lecture 2 - SQL select, insert, update and deleteDatabase Management - Lecture 2 - SQL select, insert, update and delete
Database Management - Lecture 2 - SQL select, insert, update and delete
 
SQL DDL
SQL DDLSQL DDL
SQL DDL
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
SQL-Alter Table, SELECT DISTINCT & WHERE
SQL-Alter Table, SELECT DISTINCT & WHERESQL-Alter Table, SELECT DISTINCT & WHERE
SQL-Alter Table, SELECT DISTINCT & WHERE
 
Sql server ___________session_15(data integrity)
Sql server  ___________session_15(data integrity)Sql server  ___________session_15(data integrity)
Sql server ___________session_15(data integrity)
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
 
SQL Server Views
SQL Server ViewsSQL Server Views
SQL Server Views
 
Sql select
Sql select Sql select
Sql select
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Sql server ___________session 3(sql 2008)
Sql server  ___________session 3(sql 2008)Sql server  ___________session 3(sql 2008)
Sql server ___________session 3(sql 2008)
 
SQL
SQLSQL
SQL
 
Sql.pptx
Sql.pptxSql.pptx
Sql.pptx
 
Les08
Les08Les08
Les08
 
Updat Dir
Updat DirUpdat Dir
Updat Dir
 
2. DML_INSERT_DELETE_UPDATE
2. DML_INSERT_DELETE_UPDATE2. DML_INSERT_DELETE_UPDATE
2. DML_INSERT_DELETE_UPDATE
 
Intro to tsql unit 9
Intro to tsql   unit 9Intro to tsql   unit 9
Intro to tsql unit 9
 

Destaque

OOUG: Oracle transaction locking
OOUG: Oracle transaction lockingOOUG: Oracle transaction locking
OOUG: Oracle transaction locking
Kyle Hailey
 
Oracle GoldenGate Architecture Performance
Oracle GoldenGate Architecture PerformanceOracle GoldenGate Architecture Performance
Oracle GoldenGate Architecture Performance
Enkitec
 
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Aaron Shilo
 
OOUG - Oracle Performance Tuning with AAS
OOUG - Oracle Performance Tuning with AASOOUG - Oracle Performance Tuning with AAS
OOUG - Oracle Performance Tuning with AAS
Kyle Hailey
 
Oracle SQL Performance Tuning and Optimization v26 chapter 1
Oracle SQL Performance Tuning and Optimization v26 chapter 1Oracle SQL Performance Tuning and Optimization v26 chapter 1
Oracle SQL Performance Tuning and Optimization v26 chapter 1
Kevin Meade
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuning
Simon Huang
 
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And WhatPerformance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
udaymoogala
 

Destaque (20)

OOUG: Oracle transaction locking
OOUG: Oracle transaction lockingOOUG: Oracle transaction locking
OOUG: Oracle transaction locking
 
Oracle Database Performance Tuning Concept
Oracle Database Performance Tuning ConceptOracle Database Performance Tuning Concept
Oracle Database Performance Tuning Concept
 
Oracle GoldenGate Architecture Performance
Oracle GoldenGate Architecture PerformanceOracle GoldenGate Architecture Performance
Oracle GoldenGate Architecture Performance
 
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR usesEarl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
 
Oracle Database Performance Tuning: The Not SQL Option
Oracle Database Performance Tuning: The Not SQL OptionOracle Database Performance Tuning: The Not SQL Option
Oracle Database Performance Tuning: The Not SQL Option
 
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
 
Extreme Replication - Performance Tuning Oracle GoldenGate
Extreme Replication - Performance Tuning Oracle GoldenGateExtreme Replication - Performance Tuning Oracle GoldenGate
Extreme Replication - Performance Tuning Oracle GoldenGate
 
Advanced goldengate training ⅰ
Advanced goldengate training ⅰAdvanced goldengate training ⅰ
Advanced goldengate training ⅰ
 
Oracle Goldengate training by Vipin Mishra
Oracle Goldengate training by Vipin Mishra Oracle Goldengate training by Vipin Mishra
Oracle Goldengate training by Vipin Mishra
 
Oracle database 12c 2 day + performance tuning guide
Oracle database 12c 2 day + performance tuning guideOracle database 12c 2 day + performance tuning guide
Oracle database 12c 2 day + performance tuning guide
 
OOUG - Oracle Performance Tuning with AAS
OOUG - Oracle Performance Tuning with AASOOUG - Oracle Performance Tuning with AAS
OOUG - Oracle Performance Tuning with AAS
 
Oracle SQL Performance Tuning and Optimization v26 chapter 1
Oracle SQL Performance Tuning and Optimization v26 chapter 1Oracle SQL Performance Tuning and Optimization v26 chapter 1
Oracle SQL Performance Tuning and Optimization v26 chapter 1
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning Fundamentals
 
Oracle LOB Internals and Performance Tuning
Oracle LOB Internals and Performance TuningOracle LOB Internals and Performance Tuning
Oracle LOB Internals and Performance Tuning
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuning
 
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And WhatPerformance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
 
Low Level CPU Performance Profiling Examples
Low Level CPU Performance Profiling ExamplesLow Level CPU Performance Profiling Examples
Low Level CPU Performance Profiling Examples
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuning
 
SQL Monitoring in Oracle Database 12c
SQL Monitoring in Oracle Database 12cSQL Monitoring in Oracle Database 12c
SQL Monitoring in Oracle Database 12c
 
Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)
 

Semelhante a Sql DML

Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
Iblesoft
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
PavithSingh
 
Ben Finkel- Using the order by clause.pptx
Ben Finkel- Using the order by clause.pptxBen Finkel- Using the order by clause.pptx
Ben Finkel- Using the order by clause.pptx
StephenEfange3
 
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
TheVerse1
 

Semelhante a Sql DML (20)

Merging data (1)
Merging data (1)Merging data (1)
Merging data (1)
 
Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)
 
SQL Query
SQL QuerySQL Query
SQL Query
 
Interview Questions.pdf
Interview Questions.pdfInterview Questions.pdf
Interview Questions.pdf
 
Adbms
AdbmsAdbms
Adbms
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
 
PL/SQL 3 DML
PL/SQL 3 DMLPL/SQL 3 DML
PL/SQL 3 DML
 
SQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersSQL Database Performance Tuning for Developers
SQL Database Performance Tuning for Developers
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Les09.ppt
Les09.pptLes09.ppt
Les09.ppt
 
Day-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptxDay-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptx
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
Ben Finkel- Using the order by clause.pptx
Ben Finkel- Using the order by clause.pptxBen Finkel- Using the order by clause.pptx
Ben Finkel- Using the order by clause.pptx
 
Assignment 3
Assignment 3Assignment 3
Assignment 3
 
Sql ch 9 - data integrity
Sql ch 9 - data integritySql ch 9 - data integrity
Sql ch 9 - data integrity
 
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
 
ADVANCED MODELLING.pptx
ADVANCED MODELLING.pptxADVANCED MODELLING.pptx
ADVANCED MODELLING.pptx
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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...
 
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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 

Sql DML

  • 1. Chapter - 8 Manipulating Data DML - Insert - Update - Delete - Merge
  • 2. Data Manipulation Language  A DML statement is executed when you: – Add new rows to a table – Modify existing rows in a table – Remove existing rows from a table  A collection of DML statements that form a logical unit of work is called a Transaction.  Consider a banking database. When a bank customer transfers money from a savings account to a checking account, the transaction might consist of three separate operations: - decrease the savings account, - increase the checking account, - and record the transaction in the transaction journal.  The Oracle server must guarantee that all three SQL statements are performed to maintain the accounts in proper balance. When something prevents one of the statements in the transaction from executing, the other statements of the transaction must be undone.
  • 3. Adding a New Row – INSERT statement
  • 4. INSERT Statement  Add new rows to a table by using the INSERT statement.   Only one row is inserted at a time with this syntax. Example :-  Enclose character and date values within single quotation marks.
  • 5. Inserting Rows with Null Values  Implicit method: Omit the column from the column list.  Explicit method: Specify the NULL keyword in the VALUES clause. specify the empty string (’’) in the VALUES list for character strings and dates.
  • 6. Common errors that can occur during user input:  Mandatory value missing for a NOT NULL column  Duplicate value violates uniqueness constraint  Foreign key constraint violated  CHECK constraint violated  Data type mismatch  Value too wide to fit in column
  • 7. Inserting Special Values  The SYSDATE function records the current date and time.
  • 8. Inserting Specific Date Values  Add a new employee.  If a date must be entered in a format other than the default format (DDMON-RR), for example, with another century, or a specific time, you must use the TO_DATE function.
  • 9. Creating a Script  Use & substitution in a SQL statement to prompt for values.  & is a placeholder for the variable value.  Run the script file and you are prompted for input for the & substitution variables.  The values you input are then substituted into the statement. This allows you to run the same script file over and over, but supply a different set of values each time you run it.
  • 10. Copying Rows from Another Table  Write your INSERT statement with a subquery.  Do not use the VALUES clause.  Match the number of columns in the INSERT clause to those in the subquery.  The number of columns and their data types in the column list of the INSERT clause must match the number of values and their data types in the subquery.
  • 11. Changing Data in a Table – UPDATE statement
  • 12. UPDATE Statement  Modify existing rows with the UPDATE statement.  Update more than one row at a time, if required.  Specific row or rows are modified if you specify the WHERE clause.  All rows in the table are modified if you omit the WHERE clause.
  • 13. Updating Two Columns with a Subquery  Update employee 114’s job and salary to match that of employee 205.
  • 14. Updating Rows Based on Another Table  Use subqueries in UPDATE statements to update rows in a table based on values from another table.  The example on the slide updates the COPY_EMP table based on the values from the EMPLOYEES table.  It changes the department number of all employees with employee 200’s job ID to employee 100’s current department number.
  • 15. Updating Rows: Integrity Constraint Error  In the example on the slide, department number 55 does not exist in the parent table, DEPARTMENTS, and so you receive the parent key violation ORA-02291.
  • 16. Removing a Row from a Table – DELETE statement
  • 17. DELETE VS TRUNCATE  After all the rows have been eliminated with the DELETE statement, only the data structure of the table remains. A more efficient method of emptying a table is with the TRUNCATE statement.  You can use the TRUNCATE statement to quickly remove all rows from a table or cluster.  Removing rows with the TRUNCATE statement is faster than removing them with the DELETE statement for the following reasons: – – – – The TRUNCATE statement is a data definition language (DDL) statement and generates no rollback information. Truncating a table does not fire the delete triggers of the table. If the table is the parent of a referential integrity constraint, you cannot truncate the table. Disable the constraint before issuing the TRUNCATE statement.
  • 18. The DELETE Statement  You can remove existing rows from a table by using the DELETE statement.  Specific rows are deleted if you specify the WHERE clause.  All rows in the table are deleted if you omit the WHERE clause.
  • 19. Deleting Rows Based on Another Table  Use subqueries in DELETE statements to remove rows from a table based on values from another table.  The subquery searches the DEPARTMENTS table to find the department number based on the department name containing the string “Public.”  The subquery then feeds the department number to the main query, which deletes rows of data from the EMPLOYEES table based on this department number.
  • 20. Deleting Rows: Integrity Constraint Error If the parent record that you attempt to delete has child records, then you receive the child record found violation ORA-02292. However, if the referential integrity constraint contains the ON DELETE CASCADE option, then the selected row and its children are deleted from their respective tables.
  • 21. WITH CHECK OPTION on DML Statements  A subquery is used to identify the table and columns of the DML statement.  The WITH CHECK OPTION keyword prohibits you from changing rows that are not in the subquery.
  • 22. Using Explicit Default Values • Specify DEFAULT to set the column to the value previously specified as the default value for the column. • If no default value for the corresponding column has been specified, Oracle sets the column to null.
  • 23. The MERGE Statement  Provides the ability to conditionally update or insert data into a database table  Performs an UPDATE if the row exists, and an INSERT if it is a new row: – Avoids separate updates – Increases performance and ease of use – Is useful in data warehousing applications  The decision whether to update or insert into the target table is based on a condition in the ON clause.  The MERGE statement is deterministic. You cannot update the same row of the target table multiple times in the same MERGE statement.  An alternative approach is to use PL/SQL loops and multiple DML statements.  The MERGE statement, however, is easy to use and more simply expressed as a single SQL statement.
  • 27. Database Transactions  The Oracle server ensures data consistency based on transactions.  Transactions give you more flexibility and control when changing data, and they ensure data consistency in the event of user process failure or system failure.  Transactions consist of DML statements that make up one consistent change to the data.  For example, a transfer of funds between two accounts should include the debit to one account and the credit to another account in the same amount.  Both actions should either fail or succeed together; the credit should not be committed without the debit.
  • 28. Advantages of COMMIT and ROLLBACK Statements  Ensure data consistency  Preview data changes before making changes permanent  Group logically related operations
  • 29. Implicit Transaction Processing  An automatic commit occurs under the following circumstances: – DDL statement is issued – DCL statement is issued – Normal exit from iSQL*Plus, without explicitly issuing COMMIT or ROLLBACK statements  An automatic rollback occurs under an abnormal termination of iSQL*Plus or a system failure.
  • 30. Committing Changes  Every data change made during the transaction is temporary until the transaction is committed. State of the data before COMMIT or ROLLBACK statements are issued:  Data manipulation operations primarily affect the database buffer; therefore, the previous state of the data can be recovered.  The current user can review the results of the data manipulation operations by querying the tables.  Other users cannot view the results of the data manipulation operations made by the current user. The Oracle server institutes read consistency to ensure that each user sees data as it existed at the last commit.  The affected rows are locked; other users cannot change the data in the affected rows.
  • 31. State of the Data after COMMIT  Data changes are made permanent in the database.  The previous state of the data is permanently lost.  All users can view the results.  Locks on the affected rows are released; those rows are available for other users to manipulate.  All save points are erased.
  • 32. State of the Data After ROLLBACK  Discard all pending changes by using the ROLLBACK statement:  Data changes are undone.  Previous state of the data is restored.  Locks on the affected rows are released.
  • 33. Statement-Level Rollbacks  Part of a transaction can be discarded by an implicit rollback if a statement execution error is detected.  If a single DML statement fails during execution of a transaction, its effect is undone by a statement level rollback, but the changes made by the previous DML statements in the transaction are not discarded.  They can be committed or rolled back explicitly by the user.  Oracle issues an implicit commit before and after any data definition language (DDL) statement. So, even if your DDL statement does not execute successfully, you cannot roll back the previous statement because the server issued a commit.  Terminate your transactions explicitly by executing a COMMIT or ROLLBACK statement.
  • 34. Locking In an Oracle database, locks:  Prevent destructive interaction between concurrent transactions  Require no user action  Automatically use the lowest level of restrictiveness  Are held for the duration of the transaction  Are of two types: explicit locking and implicit locking
  • 35. What Are Locks?  Locks are mechanisms that prevent destructive interaction between transactions accessing the same resource, either a user object (such as tables or rows) or a system object not visible to users (such as shared data structures and data dictionary rows). How the Oracle Database Locks Data  Oracle locking is performed automatically and requires no user action.  Implicit locking occurs for SQL statements as necessary, depending on the action requested. Implicit locking occurs for all SQL statements except SELECT.  The users can also lock data manually, which is called explicit locking.
  • 36. Implicit Locking  Two lock modes: – Exclusive: Locks out other users – Share: Allows other users to access  High level of data concurrency: – DML: Table share, row exclusive – Queries: No locks required – DDL: Protects object definitions  Locks held until commit or rollback