0% found this document useful (0 votes)
13 views

IM 101_Fundamentals of Database Systems_Unit 12

Uploaded by

ceemorgan91
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

IM 101_Fundamentals of Database Systems_Unit 12

Uploaded by

ceemorgan91
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Copyright © 2020 by the Pamantasan ng Lungsod ng Valenzuela

All rights reserved. No part of this module may be reproduced, repurposed, distributed, or transmitted in
any form or by any means including photocopying, reprinting, or other electronic or mechanical
methods without the prior written permission of PLV and the individual developers of instructional
materials (IMs) except in the case of brief quotations embodied in critical and creative reviews and
certain other noncommercial uses permitted by the Copyright Law. For permission request, address your
written correspondence whether printed or electronic to the Chair of the University Committee on
Instructional Materials Development and Evaluation at the address below:

Pamantasan ng Lungsod ng Valenzuela


Tongco St., Maysan, Valenzuela City
College: Department: Course Course Title:
Engineering and Information Information Code: Fundamentals of Database
Technology Technology IM 101 Systems
Faculty: Chairperson:
Rommel P. Apostol, MIT PATRICK LUIS M. FRANCISCO, MIT

Understanding the Flow of Data in Everyday Transactions,


A module in IM 101: Fundamentals of Database Systems
Foreword
This module aims to help students understand, familiarize, and adopt the use of fundamental data
processes and operation to utilize them in developing more efficient and secure information systems.
This module contains lessons that introduce them to the core concept of database systems and
management and answers the essential questions presented in each part of the module. The learning
outcomes from each part of the module will help the students understand the essential questions given
and at a certain point in the discussions, an evaluation will be done through the use of different
activities.
At the end of this module, the student will be able to understand the basic concepts and use of
database systems and be able to use tools and software in manipulating them.
Table of Contents
Unit Twelve
Essential Questions …………………………………………………………………………….. 1
Intended Learning Outcomes …………………………………………………………………... 1
Assesment Task
Diagnostic ………………………………………………………………………………. 1
Formative ……………………………………………………………………….….….. 23
Summative ……………………………………………………………………….….… 23
Lessons Input …………………………………………………………………………………… 1
References …………………………………………………………………………………..…. 23
1

Unit Twelve – Data Manipulation Commands and using Rules of Precedence


This unit introduces the different data manipulation commands and how they are used in manipulating
data inside our database. It will also include on the different rules governing such commands such as
Rules of Precedence.

 Essential Question
What are the basic Data Manipulation Language commands ?
How do we call database alias ?
How do operators follow precedence in an Structured Query Language query ?

 Intended Learning Outcomes


The basic Data Definition Language commands used in Structured Query Language such as select,
insert, update and delete
Using alias and following operator precedence in Structured Query Language

 Diagnostic Assessment Task


At the start of the lesson the instructor will provide the following activities to gauge the students
understanding of the lesson beforehand :
1. The instructor will give the students two to three problems related to the use of Data
Manipulation commands and Rules of Precedence in Structured Query Language

 Lessons Input

What Do You Need to Write an SQL Query?


To write an SQL query, you will first need to create a relational database.
In SQL, we call a database relational because it is divided into tables that are related to each other.
These tables break down the data into smaller and more manageable units, which allows better
maintenance and overall performance.

Where can you create an SQL database?


To do it, you need to have a Database Management System (DBMS) installed. A DBMS is a software
that helps you create and manage the database. If you don’t have one installed on your system already,
here are a few most popular options:

 MySQL (open-source)
2

 SQL Server Express (open-source)


 Oracle (paid)
Regardless of the DBMS you choose, all of them provide security and protection for all the databases
you create. It also helps maintain consistency if there are several users working on the DBMS at once.

The Guide to Writing an SQL Query


Now, let’s take a closer look at what you need to know to write an SQL query as well as some common
mistakes to avoid.

Step #1: Understand the Process behind the SQL Query


Before you start writing an SQL query, you need to understand how it works, when performing
commands.
When you enter a query, it is immediately parsed into a tree. A parser, which is a computer program that
translates SQL statements into a parse tree, helps identify whether the query fits the syntactical as well
as semantic requirements, i.e., that it is recognizable.
Then, if everything is correct, the parser creates an internal query, which is then passed to the rewrite
engine.
After that, the task optimizer, which analyzes how many execution plans a query has, finds the optimal
execution plan for your given query. This plan represents the algorithm, which will be used to perform
the command.
If the query is written correctly, you will get the results you expect.
Now, let’s take a look at what it takes to write a proper SQL query.

Step #2: Get a Database Ready


So, as we already mentioned, to write an SQL query, you need to create an environment for it by
launching a database.
If you already have your DBMS software installed, you can proceed right to creating a database by using
a ‘CREATE DATABASE’ statement. The basic syntax of this command will look like this:

CREATE DATABASE database_name;

For instance, if you want to create a database for client reviews, the result will look like this:

CREATE DATABASE client_reviews;

To move on to using your database, you need to continue your SQL query with the ‘USE’ statement:

USE client_reviews;

This will make this database a target for all your future commands.
Keep in mind: if the database with this name already exists, you will get an error message. However, to
avoid this, you can use the ‘IF NOT EXISTS’ statement. Here’s how it looks like in MySQL:

mysql> CREATE DATABASE IF NOT EXISTS client_reviews;


3

If your query is correct, you will get an OK message.


MSSQL
IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = 'client_reviews')
CREATE DATABASE client_reviews;

Step #3: Create a Table to Organize Information


If the database is ready, you can now proceed to creating a table. As we already mentioned, tables help
you structure your queries and make the data more manageable.
To create a table, you need to input the ‘CREATE TABLE’ statement. The syntax for this statement will
look similar to this:

CREATE TABLE table_name (


column1_name_constraint,

)

It is clear what we should insert in the table name and column name, but let’s take a closer look at the
types of constraints.
A constraint is a declaration of data type, which indicates what kind of data the column will include.
There are several kinds of constraints that you can include in a column:

 CHAR – fixed-length data strings (max. size of 255 characters)


 DATE – dates in the YYYY-MM-DD format
 DATETIME – dates in the YYYY-MM-DD format and time in the HH:MM:SS format
 DECIMAL – precise decimal data
 INT – numbers within the range of 2147483648 to 2147483647
 TEXT – textual data (max. size of 65,500 characters)
 TIMESTAMP – timestamp data with the precise number of seconds
 VARCHAR – variable-length data strings (max. size of 65,500 characters)
 Modifiers – UNIQUE constraint ensures unique value for each row in a column; PRIMARY-
KEY constraint marks a relevant field in the table; DEFAULT constraint represents the
default value of the columns; AUTO_INCREMENT automatically assigns value to a field if
it has not been specified; CHECK constraint puts a restriction on the values that can be
included in one column; NOT NULL constraint excludes the null value from a field.

Note that in MS SQL Server, thew equivalent of AUTO_INCREMENT is identity(1,1).

If we create a table for each of the people who have given their customer reviews, the final result will
look like this:
4

CREATE TABLE customer_profiles (


id INT NOT NULL AUTO_INCREMENT,
name VARCHAR NOT NULL,
birth_date DATE,
review TEXT
);

For MS SQL Server the command will be :


CREATE TABLE customer_profiles (
id INT NOT NULL identity(1,1),
name VARCHAR(50) NOT NULL,
birth_date DATE,
review varchar(max)
);

When creating a table, you can encounter the same problem as with a database if the table does not exist.
To avoid it, to the ‘CREATE TABLE’ statement, you should also add the ‘IF NOT EXISTS’ statement.

Step #4: Start with the Basic SQL Statements


When the table is ready and operational, you can now continue writing SQL queries by inserting data
inside the table.
Here are all basic statements to input and manage the data inside the table:
1) ‘INSERT INTO’ statement
This statement is used to include new rows into a table. Here’s how the syntax will look like in this case:

INSERT INTO table_name (column1, column2, column 3);

You can also include values – the data that you want to include in each column.
Here’s how the final query would look like for our customer reviews table after inserting data into it:

INSERT INTO customer profiles (name, birth_date, review)


VALUES (‘Jennifer Dickinson’, ‘1987-07-07’, ‘good service’)

The final result will give you a numbered list of the names, birth dates, and reviews in the form of a
table.

SQL INSERT Statement Basic Structure


The INSERT statement’s main purpose is to add rows to a table. Though an insert statement inserts data
from many sources, such as literal values or source vales, the basic format is the same.
There are three components to an SQL INSERT statement:

1. The table receiving new rows.


2. The columns to populate
5

3. The source data for new rows.


The general format for the Insert Statement IS:

INSERT INTO tableName


(column1, column2, …)
VALUES (value1, value2, …)

We’re now going to do some sample inserts, so if you haven’t done so already, run the script to create
the esqlSalesPerson table.

CREATE TABLE esqlSalesPerson

( SalesPersonID int IDENTITY(1,1) NOT NULL,

FullName varchar(50) NOT NULL,

SalesLastYear money NULL,

City nvarchar(50) NULL,

rowguid uniqueidentifier NOT NULL);

SQL INSERT INTO – Inserting Single Row


In this example we insert a single row into the esqlSalesPerson table. Here is its table structure :

Figure 12.1 esqlSalesPerson Table

Let’s assume we want to insert a new sales person into the table. The command to run is:
INSERT INTO dbo.esqlSalesPerson
(FullName, SalesLastYear,
City, rowguid)
VALUES ('George Hitson', NULL,
'Midland', '794310D2-6293-4259-AC11-71D96689A3DD')
6

Notice we didn’t specify the SalesPersonID in the column list. This is an identity column and
automatically populated.
You can switch around the columns; they don’t have to be in order. Also notice not all the columns are
specified:

INSERT INTO dbo.esqlSalesPerson


(City, FullName,
rowguid)
VALUES ('Traverse City', 'Donald Sax',
'F6E26EFD-5838-40F8-ABB3-D487D2932873')

Creates the following row:

Figure 12.2 esqlSalesPerson table sample data

Notice that since SalesLastYear wasn’t specified, it is NULL:


Enclose column values with parenthesis. This represent one rows worth of data. To insert more than one
row, just include another set of column values. Just be sure to separate each set with a comma as below:
INSERT INTO dbo.esqlSalesPerson (City, FullName, rowguid)
VALUES ('Bay City', 'Ralph Gitter',
'DED7DB59-7149-47DD-8D8F-D5FCFFF11124'),
('Alpena', 'Mike Orange',
'94600A1E-DD83-4ACE-9D59-8CD727A2C83E')

Before we continue on with more complicated example, it’s important to step back and consider the
SQL INSERT statement’s behavior and some best practices.
Considerations
Data Type Considerations (padding)
Keep in mind that when inserting data into columns whose data type is CHAR, VARCHAR, or
VARBINARY, the padding or truncation of data depends upon the SET ANSI_PADDING setting.
Inserting the value ‘Kris’ into a field defined as CHAR(10) results in a value padded with six additional
spaces. The value inserted is ‘Kris ‘ The padding rule can be confusing when using INSERT INTO.

Error handling
You can handle errors when executing an INSERT INTO statement using a TRY…CATCH construct.
There are several common reason an INSERT statement may fail. Some of the common ones are:
7

 Unique Key Violation – you’re trying to insert a record into a table which causes a duplicate
key value.
 Primary Key Violation – you’re trying to insert a record into a table which already has a
row with the same primary key.
 Foreign Key Violation – your trying to insert a row into a “child” table, yet the “parent”
doesn’t exist.
 Data Type Conversion – You’re trying to insert a row, where one of the values can’t be
correctly convert into the corresponding columns data type.
In these cases, the INSERT statement execution stops and the INSERT generates an error. No rows are
inserted into the table, even rows
This “all or nothing” behavior can be modified for arithmetic errors. Consider a divide by zero error.
INSERT INTO myNumbers (x, y)
VALUES (10/0, 5),
(10/5, 2),
(10/2, 5)

Will generate an error if SET ARITHABORT is set to ON. In this case, the inserted is stopped, no rows
are inserted, and an error is thrown.
However, if SET ARITHABORT is set to OFF and ANSI_WARNINGS are OFF, then the same
statement will successfully complete. Where there is a mathematical error, the result is replaced with
NULL.
For example,
SET ARITHABORT OFF
SET ANSI_WARNINGS OFF
INSERT INTO myNumbers (x, y)
VALUES (10/0, 5),
(10/5, 2),
(10/2, 5)

adds three rows with the values

Figure 12.3 sample data


8

When adding rows to tables it is important to understand there are some columns requiring special
handling.

INSERT SELECT and Unique Identifiers


When adding data to column declared with the uniqueidentifier type use the NEWID() function to
generate a globally unique value.
As an example

INSERT INTO esqlSalesPerson


(City, FullName, rowguid)
VALUES ('Traverse City', 'Donald Sax', NEWID())

Inserts a new row into the esqlSalesPerson. If you run the command again, another row is added, but the
rowguid value is different.
NEWID() generates a new value each time it is called.
Identity Column Property
A new value is generated for the column whenever a row is inserted into a table with a identity column
property. Because of this, since esqlSalesPerson.SalesPersonID is an identity column, we don’t specify
it in our INSERT statement. Each time a row is added the identity value is incremented by one.
If you try to insert a row using your own value, you’ll throw an error.
The INSERT statement

INSERT INTO esqlSalesPerson


(SalesPersonID, City, FullName, rowguid)
VALUES (9999,'Traverse City', 'Donald Sax', NEWID())

Generates the error


Cannot insert explicit value for identity column in table 'esqlSalesPerson' when
IDENTITY_INSERT is set to OFF.

To get around this you can SET IDENTITY_INSERT ON

SET IDENTITY_INSERT esqlSalesPerson ON;


INSERT INTO esqlSalesPerson
(SalesPersonID, City, FullName, rowguid)
VALUES (9999,'Traverse City', 'Donald Sax', NEWID())

Runs with no errors thrown.


9

Default Values and other


When inserting rows, any columns not specified are provided a value by the DBMS;
otherwise the row cannot be loaded.
The DBMS automatically provides values for columns if:

 the column is an IDENTITY column (see above)


 a default value is specified and no other value is specified.
 the column is null-able. In this case it is set to NULL.
 The column is commutable. Here the calculation is used.

If a value isn’t provided by the statement and the engine is unable to provide a
value, the row cannot be inserted. This typically happens with a value is missing
and the column is NOT NULL.

Inserting Data from Other Tables


You can also use the INSERT INTO SELECT statement to insert one or more rows
from one table into another. The results of a SELECT feed into the INSERT INTO.
The general form is

INSERT INTO targetTable (column1, column2, …)


SELECT (column1, column2, …)
FROM sourceTable

Let’s assume the Adventure Works sales manager would like to create a SalesPerson table and only
include sales people who’s last year’s sales were greater than $1,000,000.
To populate this table, you could run the following INSERT SELECT:

INSERT INTO esqlSalesPerson


(FullName, SalesLastYear, rowguid)
SELECT P.FirstName + ' ' + P.LastName, S.SalesLastYear, NEWID()
FROM Sales.SalesPerson S
INNER JOIN Person.Person P
ON P.BusinessEntityID = S.BusinessEntityID
WHERE S.SalesLastYear > 1000000

In order for this to work properly the columns returned from the SELECT statement have to be in the
same order as specified int the INSERT column list. In this example notice that rowguid is a required
field. To populate this value, we use the NEWID() function.
You can also use a common table expression to define the rows to insert.
You can also write the example as a CTE (Common Table Expression):
10

WITH topSalesPerson (FullName, SalesLastYear, rowguid)


AS (
SELECT P.FirstName + ' ' + P.LastName, S.SalesLastYear, NEWID()
FROM Sales.SalesPerson S
INNER JOIN Person.Person P
ON P.BusinessEntityID = S.BusinessEntityID
WHERE S.SalesLastYear > 1000000 )
INSERT INTO esqlSalesPerson
(FullName, SalesLastYear, rowguid)
SELECT FullName, SalesLastYear, rowguid
FROM topSalesPerson

Though there is more typing, I like the CTE method. I think it makes the INSERT statement easier to
read.
Remember, when using SELECT statement to insert data into another table it is best practice to first just
run the SELECT statement as is to ensure you are selecting the correct rows. Also, always develop and
test your code! I highly recommend using a development copy of your database.

2) ‘SELECT’ clause

This clause is used to select and extract data from one or different tables. The syntax for this clause will
follow this pattern:

SELECT column1_name, column2_name FROM table_name

The combination of the ‘SELECT’ and ‘FROM’ clauses allows you to fetch information from one or
several columns within one or different tables. If you want to select all columns in one table, you can
simply use the combination of ‘SELECT’, ‘FROM’ clauses, and the name of the table.

We will discuss more samples of this on the latter units.

3) ‘WHERE’ clause
By inserting this clause in a table, you can select data based on a certain condition. It is helpful if you
want to select for an update or entirely delete one of the records in a row or a column based on a
condition like a name, birth date, etc. Here’s the basic syntax using this clause:

SELECT column1_name FROM table_name WHERE condition

As you can see, the WHERE clause is used together with the ‘SELECT’ and ‘FROM’ clauses to help
you fetch the right data from the right column or row.
You can also use the ‘WHERE’ clause to filter different records based on a certain condition.
To make sure that you select the right data, this clause allows you to use several basic comparison
operators:
11

 = (equal)
 > (greater than)
 < (less than)
 >= (greater than or equal)
 <= (less than or equal)
 LIKE (to find similar patterns)
 IN (finding matches according to a certain value)
 BETWEEN (defining the range of values)
To make these operators work, include them right after the ‘WHERE’ clause.

Figure 12.4 Comparison Operators

4) ‘AND’ and ‘OR’ operators


To write a basic SQL query and effectively select the data from a certain column in a table, you also
need to use ‘AND’ and ‘OR’ operators used together with the ‘WHERE’ clause.
The AND operator is used to combine two different conditions and gives you the results only if there is
data that matches both these conditions. Here’s how the syntax with the ‘AND’ operator looks like:

SELECT column1_name, column2_name…FROM table_name


WHERE condition1 AND condition2

Respectively, the OR operator combines two different conditions and gives you the results if there is
data that matches one of these conditions. The syntax, in this case, looks like this:

SELECT column1_name, column2_name…FROM table_name


WHERE condition1 OR condition2

To write a more complex SQL query, you can also combine the ‘AND’ and ‘OR’ operators, which will
allow you to retrieve data that matches many different conditions.
5) ‘IN’ and ‘BETWEEN’ Operators
These operators help you select an exclusive variety of values based on certain conditions.
The IN operator allows you to select all the data that falls under a certain criterion. The syntax of the
query, including the ‘IN’ operator, should look like this:
12

SELECT column1_name…FROM table_name


WHERE condition1 IN (value1, value2, value3…)

For instance, you can retrieve information about customers coming from the same country using this
operator. Similarly, you can add ‘NOT’ to the ‘IN’ operator, if you want to exclude some results.
If you want to get results within a certain range of values, you can use the BETWEEN operator. In this
case, the syntax will look as follows:

SELECT column1_name…FROM table_name


WHERE condition1 BETWEEN value1 AND value 2
As you can see, the ‘AND’ operator is also used to compare the values and fetch the results.
6) ‘ORDER BY’ clause
This clause is used when you want to put the fetched results in a certain order. The ORDER BY
clause tells the server how to organize the data, and the syntax looks like this:

SELECT column_list…FROM table_name ORDER BY column_name

preferred order of the fetched data.


7) ‘LIMIT’/ ‘TOP’ clause
If you want to limit the number of results, you can include the ‘LIMIT’ clause in MySQL or Top clause
in SQL Server. The basic syntax using this clause looks like this:

SELECT column_list…FROM table_name ORDER BY value LIMIT number (MySQL)

SELECT TOP number column_list…FROM table_name ORDER BY value (SQL Server)

As you can see, the ‘ORDER BY’ clause is also used in this case, because it helps identify the values to
be limited.
8) ‘UPDATE’ statement
Once you’ve inserted and selected data, you can now proceed to writing an SQL query to update this
data. To do it, you will need to use the UPDATE statement, for which the syntax looks similar to this:

UPDATE table_name
SET column1_name = value 1…
WHERE condition1, condition2…

The ‘SET’ clause allows you to identify a specific column or row that needs to be updated. You can also
use all the above-mentioned operators, like ‘AND’ and ‘OR’ to update the table.

Also, let’s initially populate the table with some data using the following INSERT statement:
WITH topSalesPerson
(FullName, SalesLastYear, City, rowguid)
AS (SELECT S.FirstName + ' ' + S.LastName,
13

S.SalesLastYear,
S.City ,
NEWID()
FROM Sales.vSalesPerson S
WHERE S.SalesLastYear > 1000000 )
INSERT INTO esqlSalesPerson (FullName, SalesLastYear,
City, rowguid)
SELECT FullName,
SalesLastYear,
City,
rowguid
FROM topSalesPerson

Basic Structure
The SQL UPDATE statement is used to change column values. Though an update statement can modify
columns data from many sources, such as literal values or other query results, the basic format is the
same.
There are three components to an UPDATE statement:

1. The table you wish to change.


2. The column you wish to change.
3. The source data you wish to use to make the change.
The general format for the UPDATE Statement is:

UPDATE tableName
SET column1 = value1,
column2 = value2,

We’re now going to do some sample updates, so if you haven’t done so already, run the script to create
the esqlSalesPerson table.

Simple Example – Updating Every Row


In this example, we insert a single row into the esqlSalesPerson table.

Let’s assume we want to the city for every salesperson to Ann Arbor. The command to run is:

UPDATE esqlSalesPerson
SET City = 'Ann Arbor'

You can also update more than one column at a time. To update both the City and rowguid we can run
14

UPDATE esqlSalesPerson
SET City = 'Ann Arbor',
rowguid = NEWID()

Which updates the table to the following:

Figure 12.5 esqlSalesPerson table data

UPDATE esqlSalesPerson
SET FullName = 'Don Sax'
WHERE SalesPersonID = 10027

Changes Donald Sax’s name to Don Sax.


Notice we used the primary key SalesPersonID to filter the row. This makes it really easy to ensure
the SQL UPDATE applies to one row.

Figure 12.5.1 esqlSalesPerson table data

Note: The SalesPersonID generated for your table’s rows may be different than what is show in the
exercises, since this primary key is auto generated.
15

Simple Example – Updating Multiple Rows


The UPDATE statement is capable of updating more than one row. This is controlled by the WHERE
clause. All rows returned via the WHERE clause criteria are updated.

Suppose every SalesPerson whose ID is less than 10031 worked in Saline. To update the rows to reflect
this we could use this UPDATE statement:

UPDATE esqlSalesPerson
SET City = 'Saline'
WHERE SalesPersonID < 10031

Which results in the following row modifications:

Figure 12.5.2 esqlSalesPerson table data after update

Considerations using the SQL UPDATE Statement


The UPDATE statement is complex and there are many elements to consider. Here are some of the
more important ones.

Data Type Considerations (padding)


Keep in mind that when updating data in columns whose data type is CHAR, VARCHAR, or
VARBINARY, the padding or truncation of data depends upon the SET ANSI_PADDING setting.
When SET ANSI_PADDING OFF then CHAR data types are padded with spaces, VARCHAR data
types have trailing spaces removed, and VARBINARY have trailing zeros removed.
For instance, if a field is defined as CHAR(10) and you update the value ‘Kris’ into this column, then it
will be padded with six spaces. The value is changed to ‘Kris ‘

UPDATE Statement Error handling


You can handle errors when executing an UPDATE statement using a TRY…CATCH construct.
There are several common reason an UPDATE statement may fail. Some of the common ones are:

 Unique Key Violation – you’re trying to update a value which causes a duplicate key value.
16

 Data Type Conversion – You’re trying to update a value which can’t be correctly convert
into the corresponding columns data type.
In these cases, the UPDATE statement execution stops and the UPDATE generates an error. No rows
from the UPDATE statement are saved into the table, even those rows that didn’t generate an error.
This “all or nothing” behavior can be modified for arithmetic errors. Consider a divide by zero error.

UPDATE myNumbers
SET X = 10/0

Will generate an error if SET ARITHABORT is set to ON. In this case the inserted is stopped, no rows
are updated and an error thrown.

UPDATE Statement Locking Behavior


An exclusive (X) lock is always placed on a table when an update is run. The lock is held in place until
the update statement completes. Since this is an exclusive lock, not other transaction can modify data
on this table, until the one which originally placed the lock is completed.

9) ‘DELETE’ statement
This statement allows you to remove one or several rows. The syntax for this query is simple and looks
like this:

DELETE FROM table_name WHERE condition

The ‘WHERE’ clause specifies the record that should be deleted according to the condition assigned to
it. Don’t omit it, otherwise, you will delete all the records from the table.

Basic Structure of the DELETE Statement


The DELETE statement is used to change column values.
There are three components to an DELETE statement:

1. The table you wish to remove rows from.


2. The criteria used to choose the rows to remove.
The general format for the DELECT Statement is:

DELETE
FROM tableName
WHERE searchCondition

We’re now going to do some sample DELETEs, so if you haven’t done so already, run the script to
create the esqlSalesPerson table.
17

Simple Example – Deleting Every Row


When you use DELETE without a WHERE clause, it removes every row from the table. If we want to
delete every from esqlSalesPerson we could run:

DELETE
FROM esqlSalesPerson

I would recommend, for the purposes of our example, to wrap the DELETE command in a transaction
so you don’t have to repeatedly insert rows into the example database. Here you’ll see the same
DELETE statement.

BEGIN TRANSACTION
SELECT COUNT(1) FROM esqlSalesPerson

DELETE
FROM esqlSalesPerson

SELECT COUNT(1) FROM esqlSalesPerson


ROLLBACK

The first count statement return 13 rows; whereas, the second returns 0. Since I ROLLBACK the
transaction, the delete operation isn’t permanent.

Simple Example – Deleting A Single Row


A more realistic use case it deleting a single row. In many applications, this a achieved by filtering on a
single row.
If you know the primary key, you’re golden, as the primary key is unique and meant to positively
identify each row.
18

Figure 12.6 esqlSalesPerson table data

Suppose we want to delete Jillian Carson’s row. To do so we would issue the following:
DELETE
FROM esqlSalesPerson
WHERE SalesPersonID = 10095

You may be wondering how you would know the primary key.
You can imagine if you had a web app that listed every sales person, that the grid may contain the sales
person’s Full Name, and Last Year’s Sales, but hidden on the grid would also be their SalesPersonID.
When a user selected a row on the grid, and elected to remove the row, the application would retrieve
the hidden primary key for the row, and then issue the delete command to the database.

Simple Example – Deleting Multiple Rows


Suppose we only want to show high performing sales people in the esqlSalesPerson table. We only
want to keep those sales people with last year’s sales greater or equal to $2,000,000.
Since our table contain those with less than this amount, we need to remove them by running the
following:

DELETE
FROM esqlSalesPerson
WHERE SalesLastYear > 2000000.00

You can run the following command to try the script within a transaction:
BEGIN TRANSACTION
SELECT COUNT(1) FROM esqlSalesPerson

DELETE
FROM esqlSalesPerson
WHERE SalesLastYear < 2000000.00
19

SELECT FullName, SalesLastYear


FROM esqlSalesPerson
ROLLBACK

Here are the result of running the script:

Figure 12.6 result of script

The blue arrow shows there were originally 13 records, and the red the remaining whose sales are
greater than or equal to two million dollars.
You can also create more complex filtering conditions. Later on in the article we’ll show how to use a
subquery. You can also use Boolean conditions, in the WHERE clause as well just as you would with
the SELECT statement.

Considerations using the DELETE Statement


To delete all rows in a table, use TRUNCATE TABLE. It is much fast than DELETE as it does log
changes. But there are key differences (See DELETE isn’t TRUNCATE! below)
Also, don’t forget you can use the @@ROWCOUNT function to find out how many rows were deleted.

Error handling
If a DELETE statement throw an error all rows are restored to their state prior to the statement being
run. If an error is triggered no rows are removed.
There are many reasons why a delete statement may fail. Some of the more typical ones include:

 Orphan Rows – if a FOREIGN KEY constraint is defined between two tables, such as
parentTable and childTable, then DELETE a parentTable row will cause an error if
childTable rows related to the parent exist. They way around this is to first remove the
corresponding childTable rows, then the parentTable row.
20

 Arithmetic Errors – If an expression evaluation results in an arithmetic error, such as divide


by zero, the DELETE is canceled an no rows removed.

Locking Behavior
A delete statement places an exclusive (X) lock on the table. This mean no other query can modify the
table’s data until the DELETE transaction completes.
You can still read data, but need to use the NOLOCK hint or read uncommitted isolation level.

DELETE isn’t TRUNCATE!


Delete isn’t TRUNCATE! Use DELETE to remove one or more rows from a table. Only in special
situation, such as when you need to reset a table to its initial state should you consider TRUNCATE.
Many people get DELETE and TRUNCATE mixed up.

Complex Example – DELETE Using a SubQuery


You can also create more complex delete statement. Just about any clause you can write into a SELECT
statement WHERE clause, can be written into the DELETE statement’s, including subqueries in the
WHERE clause.
Let’s do an example.
Suppose you need to remove all sales persons that live in the US from the esqlSalesPerson table.
Though our table has City, it doesn’t have country. We can get around this by using a subquery.

BEGIN TRANSACTION
SELECT COUNT(1) FROM esqlSalesPerson

DELETE
FROM esqlSalesPerson
WHERE esqlSalesPerson.City IN
(SELECT DISTINCT City
FROM Person.Address A
INNER JOIN Person.StateProvince S
ON A.StateProvinceID = S.StateProvinceID
AND S.CountryRegionCode = 'US' )

SELECT FullName, SalesLastYear


FROM esqlSalesPerson
ROLLBACK

Please Note, I wrapped the example in a transaction so I wouldn’t permanently delete my test data.
The subquery is colored blue. Notice that it is no different from any other correlated subquery you may
have used in the past.
21

The mechanics of this DELETE statement are:

1. Find distinct cities for all people that live in the US.
2. DELETE sales people whose city is in this list.
The first step results from the subquery. The second step deletes rows per the WHERE clause.

10) ‘TRUNCATE TABLE’ statement


However, if you do want to remove all the rows at once, the TRUNCATE TABLE statement will help
you do it quicker than a ‘DELETE’ statement. The syntax for this query looks like this:

TRUNCATE TABLE table_name

While removing the rows from the table, this statement doesn’t actually delete the structure of the table.
You can use this statement if you want to rework the entire table.

Step #5: Proofread Your SQL Query


If you’ve finished writing an SQL query and it still doesn’t work, you might have made a mistake along
the way.
So, watch out for these most common SQL query mistakes and make sure you proofread your query to
avoid them:

 Misspelled commands. This is the most common SQL query mistake. To solve this
problem, you can use an SQL editor to fix the broken SQL statements and clauses. If your
query contains text under the TEXT constraint, you also need to proofread it. You can do it
quickly using different thesis sites containing automated proofreaders.
 The omission of punctuation signs. A proper SQL query also needs to have brackets and
quotation marks to operate properly. So check your query for single quotes and double
quotes and make sure everything displays properly.
 Improper order of the statement. If your query doesn’t work, the statements in it might be
in an improper order. Having syntax templates at hand might help if you don’t have enough
experience writing SQL queries.

To make your SQL queries work, you need to write them while keeping in mind where performance
problems might appear within your query. Then, if you get an error message, you might already have an
understanding, where to look for an issue and how to solve it.

Data Manipulation Commands Review

INSERT command – used to enter data into the table. Its basic syntax looks like this
22

INSERT INTO tablename VALUES (values1….valuesN)


Example :
INSERT INTO tbl_product
VALUES ('Shampoo Day',32.1,'1/28/2012')
We can also insert data in selected columns,
INSERT INTO tbl_product(prod_name,prod_date)
VALUES ('Conditioner Day','2/28/2012')

COMMIT command – any changes committed to the database will be saved.


Example :
COMMIT;

SELECT command – used to list contents of the table.The syntax of the command is:
SELECT columnnames FROM tablename
You could also use a wildcard character (*) to select all columns from the table.Example:
SELECT * FROM tablename

UPDATE command – modify the data in the table. The syntax is :


UPDATE tablename
SET columnname = expression
WHERE condition
Example :
update tbl_product
set prod_name = 'Gugo Bae'
where prod_id = 2

ROLLBACK command – undo any changes to the made since the last COMMIT command.It should be
executed before any COMMIT command is made, otherwise, all changes would be made final.

DELETE command – used to delete data or objects in our database.Syntax is :


23

DELETE FROM tablename


WHERE condition

delete from tbl_product


where prod_id = 2

Subquery – or nested or inner query is a query that is embedded or nested inside another query.

Selecting Rows with Conditional Restrictions


SELECT columns/* FROM tablename
WHERE condition

We use WHERE clause to set restrictions when selecting data.

Using Computed Columns and Aliases


We can perform operations on certain columns to return a result such as product,average,sum or the
likes.We can also use the word AS referred to as alias to rename a certain column result. Example :
SELECT PRODUCT_QUANTITY * PRODUCT_PRICE FROM tbl_Products
SELECT PRODUCT_QUANTITY * PRODUCT_PRICE AS TOTAL_PRICE FROM tbl_Products

Rules of Precedence
Rules that establish the order to which computations are computed.
1. Perform operations within parentheses

2. Perform power operations

3. Perform multiplication and division

4. Perform addition and subtraction

 Formative Assessment Task


24

1. The instructor during the last five minutes of class, will give students one minute (or two to
five minutes) to write the answers to one or two questions, such as, What was the most
important thing you learned? and What question or questions remain unanswered?.
2. The instructor will give the students two to three problems related to the use of Data
Manipulation commands and Rules of Precedence in Structured Query Language

*** End of Lesson Input ***

 Summative Assessment Task


1. The instructor will provide a written examination with the topics discussed in Unit Ten to
Twelve

References

Garcia-Molina, H.,Ullman, J.,Widom, J. (2008). Database Systems: The Complete Book (2nd ed., pp 189-
501). Pearson

You might also like