Preface 1 Data Handling in Files: VIII 1
Preface 1 Data Handling in Files: VIII 1
Preface viii
i
4.5 Create a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.6 Enter and view data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.7 Lab Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
7 Select Queries 38
7.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
7.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
7.3 Understanding Distinct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
7.4 Understanding Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
7.5 Pattern match search condition . . . . . . . . . . . . . . . . . . . . . . . . . 41
7.6 Reading of Data from multiple tables . . . . . . . . . . . . . . . . . . . . . 42
7.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
9 Nested Queries 49
9.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
9.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
9.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
9.4 Creating Sub-queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
9.5 Using EXISTS and NOT EXISTS . . . . . . . . . . . . . . . . . . . . . . . . 51
9.6 EXISTS versus IN and NOT EXISTS versus NOT IN. . . . . . . . . . . . 51
9.7 MySQL subquery in FROM clause . . . . . . . . . . . . . . . . . . . . . . . 52
9.8 MySQL correlated subquery . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
12 Aggregate Functions 61
12.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
12.2 scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
12.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
12.4 The AVG() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
12.5 SQL COUNT() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
12.6 FIRST() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
12.7 LAST() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
12.8 MAX() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
12.9 MIN() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
12.10 SUM() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
12.11 GROUP BY Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
12.12 HAVING Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
12.13Lab Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
13 Multi-Table Queries 69
13.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
13.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
13.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
13.4 Simple join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
13.5 Sorting a join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
13.6 Three-table join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
13.7 Multiple grouping columns . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
13.8 Computing a join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
13.9 Outer joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
13.10Join Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
13.11Lab Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
15 Advanced DML 82
15.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
15.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
15.3 The SQL DELETE Statement . . . . . . . . . . . . . . . . . . . . . . . . . . 82
15.4 The SQL UPDATE Statement . . . . . . . . . . . . . . . . . . . . . . . . . . 83
15.5 Insert Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
15.6 Adding Comments on Table . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
15.7 Lab Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
16 Advanced DDL 86
16.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
16.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
16.3 Case Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
16.4 Creating Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
16.5 The SQL CREATE TABLE Statement . . . . . . . . . . . . . . . . . . . . . 87
16.6 SQL Primary Key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
16.7 SQL Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
16.8 The ALTER TABLE Statement . . . . . . . . . . . . . . . . . . . . . . . . . 91
16.9 Lab Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
17 Database Connectivity 93
17.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
17.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
17.3 Database connection in Java NetBeans . . . . . . . . . . . . . . . . . . . . 93
17.4 Adding views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
17.5 Jtable control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
17.6 Lab Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
18 Views 100
18.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
18.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
18.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
18.4 Creating Updateable Views . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
18.5 Modifying views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
18.6 Removing views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
18.7 Lab Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
23 Triggers 131
23.1 Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
23.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
23.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
23.4 Difference between a trigger and a stored procedure . . . . . . . . . . . . 131
23.5 MySQL trigger syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
23.6 MySQL trigger example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
23.7 Lab task and home work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
24 Indexing 138
24.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
24.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
24.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
24.4 Creating Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
24.5 Showing Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
24.6 Removing Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
24.7 Creating index on foreign keys . . . . . . . . . . . . . . . . . . . . . . . . . 141
24.8 Removing foreign key indexes . . . . . . . . . . . . . . . . . . . . . . . . . . 141
24.9 Lab Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
26 Locks 151
26.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
26.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
26.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
26.4 Locking and Unlocking tables . . . . . . . . . . . . . . . . . . . . . . . . . . 151
26.5 Table locking for READ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
26.6 MySQL table locking for WRITE . . . . . . . . . . . . . . . . . . . . . . . . 154
26.7 Lab Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
This is the second edition of the new database systems laboratory manual originaly
written by our colleague Dr. Osman Khalid during Spring 2015. In addition to revising
the existing content, many labs have been entirely rewritten in thus edition.
The previous manual was primarily focused on using MySQL for imparting practical
DBMS concepts. In this manual we have tried to be as platform interdependent as
possible in our approach. The three prominent database management systems i.e.
Oracle, MySQL and SQL Server are introduced in the beginning and the differences
between these major DBMS have been left as exercise for students while more focus is
on underlying SQL concepts.
We hope that this document will be a useful resource for our colleagues and students.
viii
LAB 1
1.1 Objectives
Performing basic data handling using general purpose programming language without
DBMS to emphasize the importance of DBMS.
1.2 Scope
1
LAB 1. Data handling in files
Where columns[0] is the “Student Id” and columns[1] is the “Student Name” for
Students.txt file.
The code examples here give you everything you need to read and write files right
away. 1
File handling in Java is frankly a bit of a pig’s ear, but it’s not too complicated once
you understand a few basic ideas. The key things to remember are as follows.
You can read files using these classes:
1
This section is based on this resource https://www.caveofprogramming.com/java/
java-file-reading-and-writing-files-in-java.html
If you want to read an ordinary text file in your system’s default encoding (usually the
case most of the time for most people), use FileReader and wrap it in a BufferedReader.
In the following program, we read a file called "temp.txt" and output the file line by
line on the console. import java.io.*;
10 try {
11 // FileReader reads text files in the default
,→ encoding.
12 FileReader fileReader =
13 new FileReader(fileName);
14
19 while((line = bufferedReader.readLine()) !=
,→ null) {
20 System.out.println(line);
21 }
22
27 System.out.println(
28 "Unable to open file ’" +
29 fileName + "’");
30 }
31 catch(IOException ex) {
32 System.out.println(
33 "Error reading file ’"
34 + fileName + "’");
35 // Or we could just do this:
36 // ex.printStackTrace();
37 }
38 }
39 }
To write a text file in Java, use FileWriter instead of FileReader, and BufferedOutputWriter
instead of BufferedOutputReader.
Here’s an example program that creates a file called ’temp.txt’ and writes some lines
of text to it.
1 import java.io.*;
2 public class Test {
3 public static void main(String [] args) {
4
8 try {
9 // Assume default encoding.
10 FileWriter fileWriter =
11 new FileWriter(fileName);
12
Try to perform some complex calculation to generate more useful information from
your data.
1. Display the number of students who studied "Database Systems"
2. What is the average GPA from Transcript.txt file for a course name asked from
the user?
STORING INFORMATION BY
RELATING DATA IN FILES
2.1 Objectives
2.2 Scope
In this lab you will have to extend your lab 1 to relate data saved in different files. For
the case study used in lab 1, you are now required to accomplish the following in this
lab:
1. Take course name from the user and then display the name of all its students.
For each row in transcript.txt if the course name matches with the one entered
by the user then pick the student id and search it line by line in students.txt file.
When matching line found, then display the name of the student. Repeat this
for all records of that course. For matching line you can use contains or indexOf
methods from String Class in java.
2. Display all students names (distinctly) who have a GPA in the course between
2.5 and 3.5. To generate this information you will have to relate transcript and
students data by checking every record in transcript.txt if the GPA is within the
given range then read student id and display the name of the student. NOTE
6
LAB 2. Storing information by relating data in files
that if the name was already display it should not be displayed again. (This can
be done by storing names in ArrayList<string>)
3. Exchange your data files with each other and then try to generate information
created in above steps. You will have to note down what challenges where faced
while running
1. Either use Threads in Java OR Run multiple instances of your program and then
try to read and write at the same time from your data files.
2. Allow the user to enter a new record in transcript.txt with a condition that if
the given student id not exist in student.txt file then display the following error
message:
"You are violating the rules by inserting a transcript record against
a registration number that not exist in the system"
3.1 Objectives
3.2 Scope
3.3 MySQL
8
LAB 3. Installation and setup of different DBMS
(2) Select a setup type - Typical, Complete, Custom. Select Typical and click Next. The
default insllation directory will be C:\ProgramsFiles\MySQL\MySQLServer5.0
(3) Ready to install MySQL. After review the settings, click Install. If you want to
change any settings, click [Back] button.
(6) Setup Wizard Completed. Make sure you have selected ’Configure the MySQL
Server now’ checkbox if you want to configure it after clicking Finish button.
NOTE: MySQL Workbench for Windows can be installed using the MySQL Installer
that installs and updates all MySQL products on Windows, the standalone .msi in-
stallation package, or manually from a Zip file which can be downloaded from the
following link:
http://dev.mysql.com/downloads/workbench/
Keep rest of the settings as they are. Click test connection to test your connection
which you have made just now.
Model mode: You can make physical model of your database and ERD diagram using
MYSQL workbench. You can work on our local instance which you have just created
to try some SQL commands.
The SQL Workshop provides tools that enable you to view and manage database ob-
jects.
You access SQL Workshop by clicking the SQL Workshop icon on the Workspace home
page. The SQL Workshop home page appears.
2. SQL Commands.
3. SQL Scripts.
4. Utilities.
5. Restful Services.
SQL Commands are used to create, edit, view, run, and delete database objects. To
access SQL Commands:
1. On the Workspace home page, click SQL Workshop.
2. Click SQL Commands.
The SQL Commands home page is divided into two sections: a command editor and a
display pane. You use the command editor to execute SQL commands and the display
pane to view output, saved command lists, and history lists.
Object Browser enables developers to browse, create, and edit objects in a database.
Oracle Application Express has many views defined to help you work with the under-
lying table structures. To access Object Browser:
• On the Workspace home page, click SQL Workshop.
• Click Object Browser.
Object Browser
The Object Browser page is divided into two panes:
• Object Selection pane displays on the left side of the Object Browser page and
lists database objects of a selected type within the current schema. You can
further narrow the results by filtering on the object name.
• Detail pane displays to the right of the page and displays detailed information
about the selected object. To view object details, select an object in the Object
Selection pane. Click the tabs at the top of the Detail pane to view additional
details about the current object. To edit an object, click the appropriate button.
When you view a table in Object Browser, the table description appears. While viewing
this description, you can add a column, modify a column, rename a column, drop a
column, rename the table, copy the table, drop the table, truncate the table, or create
a lookup table based upon a column in the current table. To view a table description:
• On the Workspace home page, click SQL Workshop and then Object Browser.
• Object Browser appears.
• From the Object list, ensure Tables is selected.
• From the Object Selection pane, select a table.
• The table description appears.
• Click the tabs at the top of the page to view different reports about the table.
In your data tab you will find query, count rows and insert row options.
Step 1: Download MS-SQL server(any version) for Windows. You can download it
from dream spark student’s account as well.
Step 2: Once the setup files are loaded, the setup will start with the following screen.
You can change these to meet your needs. Version 2012 is being used in this example.
Step 3:
Once you click Next, you can start the installation, click “Install now”
Step 4: You will see the following screen, wait until it finishes loading,
Step 5: In the following setup screen, you will see four options. Select Windows Server
2012 DataCenter Evaluation (Server With GUI).
After you click Next from previous screen, Read the License terms, tick the "I accept
the license terms" and click Next
Step 7:
Now It will ask you for the drive (or partition) you want to install Windows on. Here
I’m installing it on the one partition I have here.
NOTE: This will remove the content of the partition. Either you create a partition to
install windows on, or you can test this on a testing machine.
Step 8: Now once we picked our partition, clicking on next from previous screen will
start the setup. This process might take a while.
Step 9: Once the setup is done, it will restart and start your Windows Server 2012 for
the first time. It will ask you then to set up a password for the Administrator user.
Step 10: The setup will finalize your settings, might take a couple of minutes.
Step 11: Once the setup is done, you can log in for the first time to your Windows
Server, as the screen says, press Ctrl+Alt+Delete to log in, and use the password you
set in the setup process
Step 12 Once you Log in, Windows Server 2012 will show the Server Manager.
• Install MySQl and MySQL workbench in your lab PC as well as your home com-
puter.
4.1 Objectives
To understand:
• Opening SQL Server Management Studio
• Creating Students and Transcript Tables
• Running simple queries to achieve what we did in Lab 1 & 2
• Realizing What DBMS do for us:
– No physical consideration
– Data independence
– Order of rows and columns does not matter
4.2 Scope
• Basic concepts
• Creating databases and tables.
23
LAB 4. Creating simple tables in different DBMS
As you the type the database name in, the Logical Name for the file types Data and
Log will automatically fill in as well. The "Data" file is where the actual data is saved
on the hard drive. The "Log" file keeps track of any changes to that data. Click OK.
Now that the Database is created, a structure to hold the actual data is needed. This
structure is called a Table. Think of Tables as containing Columns and Rows, like a
spreadsheet. To create a Table, expand the Databases folder, and then expand the
newly created "Test" database.
Right click "Tables" and select "New Table". You will be prompted to fill in "Column
Name" and "Data Type". Fill in "EmpName" with a data type of "varchar(50)". In the
next row, enter a Column Name of Wage with a data type of "money".
Unlike Excel or a spreadsheet, a column in a Database must know ahead of time what
type of data it will be storing. A data type of VarChar(50) tells SQL Server to expect
character data (text), of a variable size not to exceed 50 characters. While you can
enter numbers into a VarChar field, they could not be added nor have math functions
done against them. For math to be allowed on a column, it must be some type of
numeric field, which is why a data type of "money" was used for the Wage column.
Save the Table by clicking the Save icon from the top menu bar; the icon is shown
below.
It will prompt for table name, enter "Employees" and click OK.
To enter data into the newly created Employees table, expand the Tables folder from
the left menu as shown below.
The newly created Employees table will be listed. Right click it and select "Open
Table". A small grid will open. Enter a few data lines as shown below. Moving to a
new line after entering data automatically saves.
1. Create two tables Transcript and Students with same attributes we used in the
files (Lab-1).
2. Insert the Data which you have in your files from lab-1 in above tables
5.1 Objectives
5.2 Scope
To open SQL Query Editor in Microsoft SQL Server Management Studio use one of
the following method:
Using the File/New Menu On the File menu, click New, and then select one of the
query editor options:
• Query with Current Connection: Opens a new editor window of the type
associated with the current connection in Management Studio. The editor win-
dow uses the same authentication information as the current connection. For
example, if you select an instance of the Database Engine in Object Explorer,
and then use Query with Current Connection, Management Studio opens a
28
LAB 5. Basic DDL and DML using query editor
Database Engine Query Editor connected to the same instance using the same
authentication information.
• Database Engine Query: Opens a new Database Engine Query Editor and a
dialog to get the information required to connect to an instance of the Database
Engine.
On the File menu, click Open, and then navigate to a file and open it. Management
Studio opens the appropriate type of editor for the file extension, copies the contents
of the file into the editor window, and also opens a connection dialog if needed. For ex-
ample, if you open a file with a .sql extension, Management Studio opens a Database
Engine Query Editor window, copies in the contents of the .sql file, and opens a con-
nection dialog. If you open a file with an extension not associated with a specific editor,
Management Studio opens a text editor window and copies in the contents of the file.
Query Editor
Default Behavior of the Query Editor
• By default Execute button in the Toolbar will run the whole query file on selected
database in the toolbar i.e. QuizDb
• For running a specific query, Select it and then click on Execute button. This will
only run the highlighted/selected portion of the query editor.
• If you want to open a query on another database than the one selected in the
toolbar, Then use the following before the query:
using MyQuizDB;
Select * from tblQuestion;
DDL statements are used to create and update the structure of database objects, for
example database, tables, views etc. Basic DLL commands
• CREATE - to create objects in the database
• ALTER - alters the structure of the database
• DROP - delete objects from the database
• TRUNCATE - remove all records from a table, including all spaces allocated for
the records are removed
• COMMENT - add comments to the data dictionary
The MySQL CREATE TABLE statement allows you to create and define a table. Syntax
Parameters or Arguments
• IF NOT EXISTS: Optional. If specified, the CREATE TABLE statement will not
raise an error if the tables already exists.
• table_name: The name of the table that you wish to create.
• column_list :The columns that you wish to create in the table.
• Datatype Datatype of the column list must be specified here
• NULL or NOT NULL : Each column should be defined as NULL or NOT NULL. If
this parameter is omitted, the database assumes NULL as the default.
• DEFAULT: default_value
• Optional: It is the value to assign to the column if left blank or NULL.
• AUTO_INCREMENT: Optional. It sets the column to be an autonumber field.
• constraint_name: Optional. The name of the constraint if you define a primary
key, unique constraint or foreign key.
Example Let’s look at a MySQL CREATE TABLE example.
The above MySQL CREATE TABLE example creates a table called contacts which has 4
columns and one primary key:
• The first column is called contact_id which is created as an INT datatype (max-
imum 11 digits in length) and can not contain NULL values. It is set as an
AUTO_INCREMENT field which means that it is an autonumber field (starting at 1,
and incrementing by 1, unless otherwise specified.)
• The second column is called last_name which is a VARCHAR datatype (maximum
The Oracle CREATE TABLE statement allows you to create and define a table.
Syntax
The syntax for the CREATE TABLE statement in Oracle/PLSQL is:
Parameters or arguments
• table_name:The name of the table that you wish to create.
• column1, column2, ... column_n: The columns that you wish to create in
the table. Each column must have a datatype. The column should either be
defined as "null" or "not null" and if this value is left blank, the database assumes
"null" as the default.
Example
Let’s look at an Oracle CREATE TABLE example.
The above Oracle CREATE TABLE example creates a table called customers which
has 3 columns.
• The first column is called customer_id which is created as a number datatype
(maximum 10 digits in length) and can not contain null values.
Parameters or arguments
• table_name: The name of the table that you wish to create.
• column1, column2, ... column_n: The columns that you wish to create in
the table. Each column must have a datatype.
Example
The above MS SQL Server CREATE TABLE example creates a table called Persons which
has 5 columns.
• The first column is called Person_id which is created as a number datatype
(maximum 10 digits in length) and can not contain null values.
• The second column is called LastName_name which is a varchar datatype (255
maximum characters in length) and also can not contain null values.
• The third column is called FirstName_name which is a varchar datatype (255
maximum characters in length) and also can not contain null values.
• The fourth column is called Address which is a varchar datatype (255 maximum
characters in length) and also can not contain null values.
• The fifth column is called city which is a varchar datatype (255 maximum char-
acters in length) but can contain null values.
DML statements are used for managing data within schema objects.
Common DML Commands
• SELECT : retrieve data from the a database
• INSERT : insert data into a table
• UPDATE: updates existing data within a table
• DELETE : deletes all records from a table, the space for the records remain
• MERGE : UPSERT operation (insert or update)
• CALL : call a PL/SQL or Java subprogram
• EXPLAIN PLAN : explain access path to data
• LOCK TABLE : control concurrency
Examples
10 SELECT Id,FirstName,LastName,Gender,DOB,PhoneNumber
11 FROM Customers;
Exercise 1: Write the SQL queries for creating the Students and Transcript tables.
Exercise 2: Insert the data from files into the tables.
Exercise 3: Create 3 UPDATE statements and two DELETE statements on Students or
Transcript table.
6.1 Objectives
6.2 Scope
In most of our lab we will follow our text book case study "DreamHome". Run the
following DDL Statements to create its database and tables:
35
LAB 6. Creating and using SQL Scripts
3 create table Branch (branchNo varchar(20) NOT NULL Primary Key, street
,→ varchar(100) NOT NULL, city varchar(50) NOT NULL, postcode
,→ varchar(20) NOT NULL);
4
5 create table Staff (staffNo varchar(20) NOT NULL PRIMARY KEY, fName
,→ varchar(50) NOT NULL, lName varchar(50) NOT NULL, position
,→ varchar(50) NOT NULL, sex varchar(1) NOT NULL, DOB DateTime NOT
,→ NULL, salary DECIMAL NOT NULL, branchNo varchar(20) NOT NULL
,→ References Branch(branchNo));
6
7 create table Client (clientNo varchar(20) NOT NULL PRIMARY KEY, fName
,→ varchar(50) NOT NULL, lName varchar(50) NOT NULL, telNo varchar(20)
,→ NOT NULL, prefType varchar(50) NOT NULL, maxRent DECIMAL NOT NULL)
8
Run the following query to insert the data into two tables
6 insert into Staff (staffNo, fName, lName, position, sex, DOB, salary,
,→ branchNo) VALUES (N’SA9’, N’Mary’, N’Howe’, N’Assistant’, N’F’,
,→ CAST(0x0000641000000000 AS DateTime), CAST(9000 AS Decimal(18, 0)),
,→ N’B002’)
7 insert into Staff (staffNo, fName, lName, position, sex, DOB, salary,
,→ branchNo) VALUES (N’SG14’, N’David’, N’Ford’, N’Supervisor’, N’M’,
,→ CAST(0x0000531200000000 AS DateTime), CAST(18000 AS Decimal(18,
,→ 0)), N’B003’)
8 insert into Staff (staffNo, fName, lName, position, sex, DOB, salary,
,→ branchNo) VALUES (N’SG37’, N’Ann’, N’Beech’, N’Assistant’, N’F’,
,→ CAST(0x000056D400000000 AS DateTime), CAST(12000 AS Decimal(18,
,→ 0)), N’B003’)
9 insert into Staff (staffNo, fName, lName, position, sex, DOB, salary,
,→ branchNo) VALUES (N’SG5’, N’Susan’, N’Brand’, N’Manager’, N’F’,
,→ CAST(0x0000C85800000000 AS DateTime), CAST(24000 AS Decimal(18,
,→ 0)), N’B003’)
10 insert into Staff (staffNo, fName, lName, position, sex, DOB, salary,
,→ branchNo) VALUES (N’SL21’, N’John’, N’White’, N’Manager’, N’M’,
,→ CAST(0x0000CFF200000000 AS DateTime), CAST(30000 AS Decimal(18,
,→ 0)), N’B004’)
11 insert into Staff (staffNo, fName, lName, position, sex, DOB, salary,
,→ branchNo) VALUES (N’SL41’, N’Julie’, N’Lee’, N’Assistant’, N’F’,
,→ CAST(0x00005D6000000000 AS DateTime), CAST(9000 AS Decimal(18, 0)),
,→ N’B002’)
1. Write the SQL queries to insert sample data into all tables of the DreamHome.
2. Assign the city of each branch to another branch using UPDATE Statements
3. Generate the complete script file for your semester project.
SELECT QUERIES
7.1 Objectives
• Understanding Distinct
• Understanding Aliases
• Reading of Data from multiple tables
• Filtering of Data based on single and compound conditions
• Understanding Order By
7.2 Scope
Get ready for the lab by completing the following pre-requisite steps: Step-1: Ensure
your sample data in “DreamHome” database Step-2: Your MyDatabaseLabs.sql file
is with you which can do the following:
1. Create and drop a database by only providing the name of the database to it
2. Create and drop tables of DreamHome database
3. Insert queries that will add your sample data to the database DreamHome
Task: Run the following queries and record your results in results column.
38
LAB 7. Select Queries
Query Results
Aliases provide you the way to give a different name to a table, column or a derived
column in the results. Note that name are only applicable for results, they do not affect
the Metadata of the tables.
Task: Run the following queries and record your results in results column.
Query Results
Query Results
Query Results
Query Results
sion.
• Range Test whether the value of an expression falls within a specified range of
values.
• Set membership Test whether the value of an expression equals one of a set of
values.
• Pattern match Test whether a string matches a specified pattern.
• Null Test whether a column has a null (unknown) value.
In SQL, the following simple comparison operators are available:
• = equals
• <> is not equal to (ISO standard)
• != is not equal to (allowed in some dialects)
• < is less than
• <= is less than or equal to
• > is greater than
• >= is greater than or equal to
More complex predicates can be generated using the logical operators AND, OR, and
NOT, with parentheses (if needed or desired) to show the order of evaluation.
The rules for evaluating a conditional expression are:
• an expression is evaluated left to right;
• subexpressions in brackets are evaluated first;
• NOTs are evaluated before ANDs and ORs;
• ANDs are evaluated before ORs.
Task: Run the following queries and record your results in results column. More
queries will be asked in the class and you will provide the solutions.
Query Results
Query Results
Query Results
Query Results
Query Results
Note: The IN test provides a more efficient way of expressing the search condition,
particularly if the set contains many values.
You can read data from multiple tables by separating table name by a comma ",". Note
that if you do not specify a condition then results will be a cross multiplication of tables
and may results into invalid rows. Therefore, to generate meaningful information we
should have some condition among the tables.
Task: Run the following queries and record your results in
Query Results
Query Results
Query Results
Query Results
Query Results
7.7 Exercises
8.1 Objectives
• Sorting Data
• Grouping Data
• Aggregate Operations Basics
8.2 Scope
• ORDER BY clause
• HAVING clause
• Aggregate functions COUNT, SUM, AVG, MIN, MAX etc.
The ORDER BY clause consists of a list of column identifiers that the result is to be
sorted on, separated by commas. A column identifier may be either a column name or
a column number†
Example: Produce a list of salaries for all staff, arranged in descending order of salary.
44
LAB 8. More on Select Queries
It is possible to include more than one element in the ORDER BY clause. The major sort
key determines the overall order of the result table.
Example: Produce an abbreviated list of properties arranged in order of property
type.
To perform some form of summation or aggregation of data, similar to the totals at the
bottom of a report. The ISO standard defines five aggregate functions:
• COUNT – returns the number of values in a specified column.
• SUM – returns the sum of the values in a specified column.
• AVG – returns the average of the values in a specified column.
• MIN – returns the smallest value in a specified column.
• MAX – returns the largest value in a specified column.
COUNT(*) is a special use of COUNT, which counts all the rows of a table, regardless of
whether nulls or duplicate values occur.
It is important to note that an aggregate function can be used only in the SELECT list
and in the HAVING clause
It is important to note that an aggregate function can be used only in the SELECT list
and in the HAVING clause. The following query is illegal:
Example: How many properties cost more than £350 per month to rent?
2 FROM Viewing
3 WHERE viewDate BETWEEN ’1-May-04’ AND ’31-May-04’;
Example: Find the total number of Managers and the sum of their salaries.
Aggregate function can be used only in the SELECT list and in the HAVING clause.
If the SELECT list includes an aggregate function and no GROUP BY clause is being
used to group data together, then no item in the SELECT list can include any reference
to a column unless that column is the argument to an aggregate function
For example, the following query is illegal:
The ISO standard requires the SELECT clause and the GROUP BY clause to be closely
integrated. When GROUP BY is used, each item in the SELECT list must be single-
valued per group. Further, the SELECT clause may contain only:
• column names.
• aggregate functions.
• constants.
• an expression involving combinations of the above.
TheWHERE clause filters individual rows going into the final result table, whereas HAV-
ING filters groups going into the final result table.
The ISO standard requires that column names used in the HAVING clause must also
appear in the GROUP BY list or be contained within an aggregate function.
The keywords ANY and ALL may be used with subqueries that produce a single column
of numbers. For ALL the condition will only be true if it is satisfied by all values
produced by the subquery For ANY the condition will be true if it is satisfied by any
(one or more) values produced by the subquery
Example: Find all staff whose salary is larger than the salary of at least one member
of staff at branch B003.
Example: Find all staff whose salary is larger than the salary of every member of
staff at branch B003.
NESTED QUERIES
9.1 Objectives
The purpose of this lab is to familiarize students with how to call a query within other
query to make a sub-query, and how to write efficient sub-queries.
9.2 Scope
• Joins vs sub-queries
• sub-queries inside SELECT, FROM and WHERE clauses
• Correlated Sub-queries
9.3 Introduction
49
LAB 9. Nested Queries
• You can use the comparison operators, such as >, <, or =. The comparison
operator can also be a multiple-row operator, such as IN, ANY, SOME, or ALL.
• A subquery can be treated as an inner query, which is a SQL query placed as a
part of another query called as outer query.
• The inner query executes first before its parent query so that the results of inner
query can be passed to the outer query.
Syntax:
Example: (Without Subquery) What are the name and address of the customer who
placed order number 1008?
Example: (With Sub-query): What are the name and address of the customer who
placed order number 1008?
Using the NOT IN qualifier: Query: Which customers have not placed any orders for
computer desks?
1 SELECT CustomerName
The keywords EXISTS and NOT EXISTS are designed for use only with subqueries.
They produce a simple true/false result. EXISTS is true if and only if there exists at
least one row in the result table returned by the subquery; it is false if the subquery
returns an empty result table.
Example: What are the order IDs for all orders that have included furniture finished
in Naturals ash?
WE use EXISTS when we just want to check whether the sub query returns a non-
empty set (i.e we don’t care what is in the set, just whether it is empty), and we use IN
when we need to know what values are in the. IN and NOT IN return a set of values
from only one column which can be then compared to one column in the outer query.
EXISTS and NOT EXISTS return only true or false value depending on whether there
are any rows in the answer table of the inner query or sub query.
In the following example, we select a list of customers who have at least one order with
total sales greater than 10,000.
First, we build a query that checks if there is, at least, one order with total sales
greater than 10,000:
The query returns 6 rows so that when we use it as a subquery, it will return TRUE;
therefore the whole query will return all customers:
1 SELECT customerName
2 FROM customers
3 WHERE EXISTS (
4 SELECT priceEach * quantityOrdered
5 FROM orderdetails
6 WHERE priceEach * quantityOrdered > 10000
7 GROUP BY orderNumber
8 )
If you replace the EXISTS with NOT EXIST, the query will not return any records at
all.
When you use a subquery in the FROM clause, the result set returned from a subquery
is used as a table. This table is referred to as a derived table or materialized subquery.
The following subquery finds the maximum, minimum and average number of items
in sale orders:
1 SELECT max(items),
2 min(items),
3 floor(avg(items))
4 FROM
5 (SELECT orderNumber,
6 count(orderNumber) AS items
7 FROM orderdetails
8 GROUP BY orderNumber) AS lineitems;
Notice that the subquery returns the following result set that is used as a derived
table for the outer query.
In the previous examples, you notice that the subquery is independent. It means
you can execute the subquery as a single query. However, a correlated subquery is
a subquery that uses the information from the outer query, or you can say that a
correlated subquery depends on the outer query. A correlated subquery is evaluated
once for each row in the outer query.
In the following correlated subquery, we select products whose buy prices are greater
than the average buy price of all products for a specific product line.
1 SELECT productname,
2 buyprice
3 FROM products AS p1
4 WHERE buyprice > (
5 SELECT AVG(buyprice)
6 FROM products
7 WHERE productline = p1.productline)
The inner query executes for every product line because the product line is changed
for every row. Hence, the average buy price will also change.
Lab Tasks:
1. Download and install the HR example database
• Download the HR example database from https://github.com/datacharmer/
test_db
• Unzip the dowloaded zip file and store it in c:\ hr
• Open windows shell, and type the following commands to lead the database
into your local database server
• cd c:\ hr
• mysql -uroot -p < employees.sql
2. Write the following queries.
• list all tables in the employees database
• Write a query to find the names (first_name, last_name) and the salaries of
the employees who have a higher salary than the employee whose last_name=’Bull’.
• Write a query to find the names (first_name, last_name) of all employees
who works in the IT department.
10.1 Objectives
10.2 Scope
10.3 Exercise
1. Write a query to find the names (first_name, last_name) of the employees who
have a manager and work for a department based in the United States.
Hint : Write single-row and multiple-row subqueries
2. Write a query to find the names (first_name, last_name) of the employees who
are managers.
3. Write a query to find the names (first_name, last_name), the salary of the em-
ployees whose salary is greater than the average salary.
4. Write a query to find the names (first_name, last_name), the salary of the em-
ployees whose salary is equal to the minimum salary for their job grade.
5. Write a query to find the names (first_name, last_name), the salary of the em-
ployees who earn more than the average salary and who works in any of the IT
departments.
6. Write a query to find the names (first_name, last_name), the salary of the em-
55
LAB 10. Nested Queries (Exercise)
Expression and single row functions can be used for runtime data minupulation and
are a power feature in SQL. Single row functions are those built-in functions which
work on a single row and return one output per row. For example, length and case
conversion functions are single row functions. Proper use of such functions inside SQL
statements can greatly save coding on the caller side i.e. PHP, Java etc.
11.1 Objectives
• Using Expressions.
• Applying single-row functions.
11.2 Scope
57
LAB 11. Expressions and Single Row functions
11.3 Expressions
Query: What are the standard price and standard price if increased by 10% for every
product [use pineview database].
SQL:
SELECT ProductStandardPrice, ProductStandardPrice*1.1
AS IncreasedBy10
FROM PRODUCT_T;
Explaination:
Returns two columns, one the ProductStandardPrice and the other column with the
price increased by 10% and its alias name as IncreasedBy10. (Multiplying by 1.1 is
equivalent to calculating 10% and adding it to Product Price)
Output:
Query: Round the IncreasedBy10 in the above example to the nearest interger.
SQL:
SELECT ProductStandardPrice, ROUND(ProductStandardPrice*1.1)
AS IncreasedBy10
FROM PRODUCT_T;
Explaination: The column IncreasedBy10 is now rounded to the nearsest integer by
the ROUND function.
Lab Task: Create a table with your marks in any three subjects during your F.Sc.
Examination. Find the total marks, percentage marks, average marks, maximum
marks, minimum marks, using expressions and the follwing row functions.
String Functions are used to compare strings, search and/or replace substrings, modify
a string, convert a string to a different format, and so on. If it’s handy to use a string
function inside SQL statements, do use it, However, if the string operation is too heavy
for database server to handle, it is better to leave string manipulation for the client
side.
Query: Convert the ProductDescription column in product_t table in the pineview
databse into (1) upper case (2) lower case characters.
SQL:
SELECT ProductDescription,
UPPER(ProductDescription),
LOWER(ProductDescription)
FROM pineview.product_t;
Output:
Create a table tow columns for name and family_name respectively. Insert the names
your three friends in lower case case caracters. Write a query to create columns aliased
fullname by using the INITCAT() and CONCAT() functions.
AGGREGATE FUNCTIONS
12.1 Objectives
12.2 scope
• Aggregate Functions
• Haveing and Group By clauses
12.3 Introduction
SQL aggregate functions return a single value, calculated from values in a column.
MySQL provides the following aggregate functions.
• AVG() - Returns the average value
• COUNT() - Returns the number of rows
• FIRST() - Returns the first value
• LAST() - Returns the last value
• MAX() - Returns the largest value
• MIN() - Returns the smallest value
• SUM() - Returns the sum
61
LAB 12. Aggregate Functions
Example:
The COUNT() function returns the number of rows that matches a specified criteria.
The COUNT function returns the number of values of the specified column (NULL values
will not be counted):
Syntax:
Example:
SQL COUNT(*)
COUNT(*) returns the number of records in a table: Syntax:
COUNT(DISTINCT column_name)
Note: COUNT(DISTINCT) works in ORACLE and Microsoft SQL Server, but not in
Microsoft Access.
Example:
Example: If we want to count the number of cities of Pakistan. We can use the
following SQL statement:
Example:
Syntax:
Example:
Example:
MULTI-TABLE QUERIES
13.1 Objectives
Students will learn how access data from multiple tables using different types of joins
13.2 Scope
13.3 Introduction
To combine columns from several tables into a result table we need to use a join oper-
ation. The SQL join operation combines information from two tables by forming pairs
of related rows from the two tables. The row pairs that make up the joined table are
those where the matching columns in each of the two tables have the same value.
If we need to access data from more than one table, the choice is between using a
subquery and using a join. If the final result table is to contain columns from different
tables, then we must use a join.
69
LAB 13. Multi-Table Queries
List the names of all clients who have viewed a property along with any comment
supplied.
The most common multi-table queries involve two tables that have a one-to-many (1:*)
(or a parent/child) relationship
The SQL standard provides the following alternative ways to specify this join:
The first alternative produces a table with two identical clientNo columns. The re-
maining two produce a table with a single clientNo column
For each branch office, list the numbers and names of staff who manage properties
and the properties that they manage.
For each branch, list the numbers and names of staff who manage properties, including
the city in which the branch is located and the properties that the staff manage.
Note, again, that the SQL standard provides alternative formulations for the FROM and
A join is a subset of a more general combination of two tables known as the Cartesian
product. The ISO standard provides a special form of the SELECT statement for the
Cartesian product:
The procedure for generating the results of a SELECT with a join is as follows:
1. Form the Cartesian product of the tables named in the FROM clause.
2. If there is a WHERE clause, apply the search condition to each row of the product
table, retaining those rows that satisfy the condition. In terms of the relational
algebra, this operation yields a restriction of the Cartesian product.
3. For each remaining row, determine the value of each item in the SELECT list to
produce a single row in the result table.
4. If SELECT DISTINCT has been specified, eliminate any duplicate rows from
the result table. In the relational algebra, Steps 3 and 4 are equivalent to a
projection of the restriction over the columns mentioned in the SELECT list.
5. If there is an ORDER BY clause, sort the result table as required.
The Outer join retains rows that do not satisfy the join condition. There are three
types of Outer join: Left, Right, and Full Outer joins. We illustrate their functionality
in the following examples.
Example: Left Outer join
List all branch offices and any properties that are in the same city.
Includes not only those rows that have the same city, but also those rows of the first
(left) table that are unmatched with rows from the second (right) table
Example: Right Outer join
List all properties and any branch offices that are in the same city.
This includes, not only those rows that have the same city, but also those rows of the
second (right) table that are unmatched with rows from the first (left) table.
Example: Full Outer join
List the branch offices and properties that are in the same city along with any un-
matched branches or properties.
This includes, not only those rows that have the same city, but also those rows that
are unmatched in both tables.
Example: What are the customer IDs and Names of all customers along with the
order id for all the orders that are placed?
.
Example: INNER JOIN .
.ON are used to establish an equi-join in the FROM clause.
What are the Customer ID and names of all customers, along with the Order IDs for
all the orders they have placed?
Example: List customer name , identification number, and order number for all orders
listed in the order table. Include the order number, even if there is no customer name,
and identification number available.
This query will also return the rows in which the foreign key column does not exist i.e.
NULL, for any row
Example: Sample join Involving four tables
Assemble all information necessary to create an invoice for order number 1006.
1 SELECT
2 E.EmployeeID,
3 E.EmployeeName,
4 M.EmployeeName AS Manager FROM
5 Employee_T E, Employee_T M
6 WHERE
7 E.EmployeeSupervisor = M.EmployeeID;
1. Select customers name, number , phone from customers table, select checknum-
ber from payments table. Display it for all customers. [either they have made
payment or they haven’t include all customers].
2. Display orderdetails for products. Use inner join.
3. Using right outer join for productline display products.
4. Select customers name and order he made for id =103. Use AND with inner join.
14.1 Objectives
To introduce the concepts of multiple joins and union queries and how to use them.
14.2 Scope
• Multiple joins
• Union
• Union all
• Union with where
• Join with update statement
• Join with delete statement
75
LAB 14. Multiple Join and Union
We first join table 1 and table 2 which produce a temporary table with combined data
from table1 and table2, which is then joined to table3. This formula can be extended
for more than 3 tables to N tables; you just need to make sure that SQL query should
have N-1 join statement in order to join N tables. Like for joining two tables we require
1 join statement and for joining 3 tables we need 2 join statements.
The UNION operator is used to combine the result-set of two or more SELECT state-
ments. Notice that each SELECT statement within the UNION must have the same
number of columns. The columns must also have similar data types. Also, the columns
in each SELECT statement must be in the same order.
SQL UNION Syntax
Note: The UNION operator selects only distinct values by default. To allow duplicate
values, use UNION ALL.
SQL UNION ALL Syntax
Example:
The following SQL statement uses UNION ALL to select all (duplicate values also).
3 UNION ALL
4 SELECT orders.orderNumber, orders.orderDate FROM orders
5 WHERE orders.customerNumber=103;
You often use JOIN clauses to query records in a table that have (in case of INNER
JOIN) or do not have (in case of LEFT JOIN) corresponding records in another table.
In MySQL, you can use the JOIN clauses in the UPDATE statement to perform cross-
table update. The syntax of the MySQL UPDATE JOIN is as follows:
1 SET SQL_SAFE_UPDATES=0;
2 UPDATE customers AS t1
3 INNER JOIN orders AS t2
4 ON t1.customerNumber= t2.customerNumber
5 SET t1.customerName= ’any name’;
Query above updates all the names to the name you have mentioned in the column.
Example: Now try the same query for a particular id to update a particular name.
1 UPDATE customers AS t1
2 INNER JOIN orders AS t2
3 ON t1.customerNumber= t2.customerNumber
4 SET t1.customerName= ’khan2’ where t1.customerNumber=103;
5 Update more than two tables, use syntax on customers, orders and order
,→ details table.
6 UPDATE tableA a
7 JOIN tableB b
8 ON a.a_id = b.a_id
9 JOIN tableC c
10 ON b.b_id = c.b_id
11 SET b.val = a.val+c.val
12 WHERE a.val > 10
You often use the JOIN clause in the SELECT statement to select records from a
table that have corresponding records in other tables. To make it more convenient,
MySQL also allows you to use the INNER JOIN clause with the DELETE statement
to delete records from a table and also the corresponding records in other tables e.g.,
to delete records from both T1 and T2 tables that meet a particular condition, you use
the following statement:
1 DELETE T1, T2
2 FROM T1
3 INNER JOIN T2 ON T1.key = T2.key
4 WHERE condition
Example: Delete office code for a particular employee who has left the organization.
Suppose you want to delete the office with officeCode 5 and you don’t update or delete
the officeCode column in the employees table, the data in the employees table would
be invalid. To delete the office with officeCode 5 and also employee records that belong
to the office, you can use the DELETE statement with the INNER JOIN clause.
Now, you can delete records associated with officeCode 5 from both offices and employ-
ees tables:
If you use the SELECT statements above to query office and employee data with of-
ficeCode 5 in theoffices and employees tables again, you will not see any row returned.
You often use LEFT JOIN clause in the SELECT statement to find records that exist
in the left table and does not have corresponding records in the right table. You can
also use the LEFT JOIN clause in the DELETE statement to delete record in a table
(left table) that does not have corresponding record in another table (right table). The
following syntax illustrates how to use DELETE statement with LEFT JOIN clause to
delete records from T1 table that does not have corresponding records in the T2 table:
1 DELETE T1
2 FROM T1
3 LEFT JOIN T2 ON T1.key = T2.key
4 WHERE T2.key IS NULL
Note that you only put T1 table after the DELETE keyword, not both T1 and T2 tables
like you did with the INNER JOIN clause.
Each customer has zero or more orders. However, each order belongs to one and only
one customer. You can use DELETE statement with LEFT JOIN clause to clean up our
customers master data. The following statement removes customers who do not have
any order:
1 DELETE customers
2 FROM customers
3 LEFT JOIN orders ON customers.customerNumber = orders.customerNumber
4 WHERE orderNumber IS NULL;
Now, if we query customers who have not ordered any product by using the following
SELECT LEFT JOIN query:
1 SELECT c.customerNumber,
2 c.customerName,
3 orderNumber
4 FROM customers c
5 LEFT JOIN orders o ON c.customerNumber = o.customerNumber
6 WHERE orderNumber IS NULL;
You will not see any row returned. It means you have successfully deleted customers
who have not ordered any products.
ADVANCED DML
15.1 Objectives
15.2 Scope
• Insert
• Update
• Delete
• Adding comments on tables
Reference database: Perform Queries on World.sql/Employees.SQL sample database
Example:
Example:
82
LAB 15. Advanced DML
or
Example:
Note: Be very careful when deleting records. You cannot undo this statement!
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
NOTE: If you omit where clause it will update all names. Error Updating Values
Correction You are using safe update mode and you tried to update a table without a
WHERE that uses a KEY column.
It’s because you tried to update a table without a WHERE that uses a KEY column
(err . . . ). The quick fix is to add SET SQL_SAFE_UPDATES=0; before your update
query.
Here’s the example, write command
SET SQL_SAFE_UPDATES=0;
Update Single Column
UPDATE emp
SET ename = ’SmithMiller’
Syntax:
Alternative Syntax:
Example:
ADVANCED DDL
16.1 Objectives
16.2 Scope
• Create database
• Create tables
• Constraints
• Not null constraint
• Primary key
• Foreign key
• Alter table
• Drop statements
• Truncate table
Consider a small case study for a hospital, Patient has following attributes:
• PatientNumber
• Firstname
86
LAB 16. Advanced DDL
• LastName
• Address
There are charges for the prescription or services provided by the hospital to a partic-
ular patient. Attributes for patient charges are:
• Itemdescription
• Itemcode
• PatientNumber
• Amount
First, we will create a database for our case study by the following statement:
The CREATE TABLE statement is used to create a table in a database. Tables are orga-
nized into rows and columns; and each table must have a name.
SQL CREATE TABLE Syntax
The PRIMARY KEY constraint uniquely identifies each record in a database table. Pri-
mary keys must contain Unique values. A primary key column cannot contain NULL
values. Most tables should have a primary key, and each table can have only one
primary key.
SQL constraints are used to specify rules for the data in a table. If there is any viola-
tion between the constraint and the data action, the action is aborted by the constraint.
Constraints can be specified when the table is created (inside the CREATE TABLE state-
ment) or after the table is created (inside the ALTER TABLE statement).
SQL CREATE TABLE + CONSTRAINT Syntax
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for unique-
ness for a column or set of columns. A PRIMARY KEY constraint automatically has a
UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.
The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table. SQL ALTER TABLE Syntax To add a column in a table, use the following syntax:
To delete a column in a table, use the following syntax (notice that some database
systems don’t allow deleting a column):
The DROP TABLE Statement The DROP TABLE statement is used to delete a table.
DATABASE CONNECTIVITY
17.1 Objectives
17.2 Scope
93
LAB 17. Database Connectivity
Step2: Leave default settings as it is just enter default password that’s 12345.
You Can add any view you want according to your needs
Inserting Jtable control can help you to populate this table from database.
Use this connection establishment method according to your needs behind controls.
VIEWS
18.1 Objectives
18.2 Scope
18.3 Introduction
In MySQL, views are not only read-only but also updateable. However in order to
create an updateable view, the SELECT statement that defines the view has to follow
several following rules:
• The SELECT statement must only refer to one database table.
• The SELECT statement must not use GROUP BY or HAVING clause.
• The SELECT statement must not use DISTINCT in the column list of the SELECT
clause.
• The SELECT statement must not refer to read-only views.
• The SELECT statement must not contain any expression (aggregates, functions,
computed columns. . . )
100
LAB 18. Views
When you create updateable views, make sure that you follow the rules above.
Example of creating updateable view:
First, we create a view named officeInfo against the offices table. The view refers to
three columns of the offices table:
Then, we can change the phone number of the office with officeCode 4 through the
officeInfo view by using the UPDATE statement.
1 UPDATE officeInfo
2 SET phone = ’+33 14 723 5555’
3 WHERE officeCode = 4;
Then select all content from office table to check the change.
Finally, to see the change, we can select the data from the officeInfo view by executing
following query:
Once a view is defined, you can modify it by using the ALTER VIEW statement. The
syntax of the ALTER VIEW statement is similar to the CREATE VIEW statement except
the CREATE keyword is replaced by the ALTER keyword.
The following query modifies the organization view by adding an addition email field.
To verify the change, you can query data from the organization view:
Once a view created, you can remove it by using the DROP VIEW statement. The fol-
lowing illustrates the syntax of the DROP VIEW statement:
The IF EXISTS is an optional element of the statement, which allows you to check
whether the view exists or not. It helps you avoid an error of removing a non-existent
view.
For example, if you want to remove the organization view, you can use the DROP
VIEW statement as follows:
Each time you modify or remove a view, MySQL makes a back up of the view defini-
tion file to the /database_name/arc/ folder. In case you modify or remove a view by
accident, you can get a back up from there.
• For all data of customers table, create a view(any name you want). Later update
the view by changing any customer name.
• Create view and apply AVG() function on payments table amount column and
later print it for a particular paymentnumber.
19.1 Objectives
19.2 Scope
19.3 Introduction
Access control and privilege system allows a database administration to create com-
prehensive access rules for handling client operations and effectively preventing unau-
thorized clients from accessing the database system.
The MySQL access control has two stages when a client connects to the server:
• Connection verification: a client, which connects to the MySQL database server,
needs to have a valid username and password. In addition, the host from which
the client connects has to match with the host in the MySQL grant table.
104
LAB 19. Security and Privileges
1 use mysql;
2 show tables;
In MySQL, the administrator control not only who can connect to a database server but
also from where. Therefore, an account in MySQL consists of username and hostname
where the user connects from, that separated by .
For example, if the root user connects from the ciit.net.pk host to the database
server the account name would be root@ciit.net.pk.
This allows to setup multiple accounts with the same name but connects from different
hosts and have different privileges. In addition, you the administrator has control to
setup account to connect from either specific or broad a set of hosts. The username
and host are stored in the grant table named user.
1 use mysql;
2
MySQL provides the CREATE USER statement to allow you to create a new user in a
database server. The syntax of the CREATE USER statement is as follows:
The percentage wildcard % has the same effect as it is used in the LIKE operator
e.g., to allow mysqladmin user to connect from any host to the ciit.net.pk you use
percentage wildcard % as follows:
Notice that the underscore wildcard _ can also be used in the CREATE USER statement.
If the hostname part of the account is omitted, MySQL still accepts it and allows the
user to connect from any host. The quote is very important especially when the account
A less common way to create a user is to use the INSERT statement to insert a new
record into the user table.
By doing this, you need to use the PASSWORD function to encrypt the password before
inserting the user record into the table as the following statement:
MySQL provides several statements that you can use to change or reset the password
of a MySQL account including the UPDATE statement, SET PASSWORD statement
and GRANT USAGE statement.
The first way to change the password is to use the UPDATE statement to update the
User and Host column of the user table in the mysql database.
After executing the UPDATE statement, you need to execute the FLUSH PRIVI-
LEGES statement to reload privileges from the grant table in the mysql database.
Suppose you want to change the password for bse user that connects from the ciit.net.pk
host to Secret1970 , you need to execute the following statements:
1 USE mysql;
2
3 UPDATE user
4 SET password = PASSWORD(’Secret1970’)
5 WHERE user = ’bse’ AND
6 host = ’ciit.net.pk’;
8 FLUSH PRIVILEGES;
It is important to note that we’ve used the PASSWORD() function to encrypt the plain
text password. The following example demonstrates how the PASSWORD() function
encrypts a plain text password.
The second way to change the password is by using the SET PASSWORD statement.
You use the MySQL account in user@host format to update the password. If you need
to change the password for other accounts, you need to have at least UPDATE privi-
lege.
You don’t need to execute the FLUSH PRVILILEGES statement to reload privileges
from grant table.
The following statement changes password of the bse account using the SET PASS-
WORD statement.
The third way to change the password is to use the GRANT USAGE statement with
the IDENTIFIED BY clause.
In this way, you specify the password in plain text instead of the encrypted one.
The following statement changes the password of the mysqltutorial account using the
GRANT USAGE statement:
Note: In case you want to reset the password of the MySQL root account, you need
to force the MySQL database server to stop and restart without using grant table
validation.
MySQL provides you with the MySQL GRANT statement that allows you to grant ac-
cess privileges to database accounts. The following illustrates the GRANT statement
syntax:
privileges indicates the privileges that you assign to the account. For example, the
CREATE privilege allows an account to create databases and create tables. You can
grant multiple privileges using single GRANT statement; the privileges are separated
by commas.
• column_list specifies the columns to which a privilege applies. The columns are
separated by commas and listed within parentheses. The column_list is the op-
tional element.
• privilege_level specifies the level at which the privileges apply. You can use
global privileges, database-specific privileges, table-specific privileges, column-
specific privileges, etc.
• account specifies which account is being granted the privileges.
• password specifies the password to assign to the account. If the account exists,
the GRANT statement replaces the old password by the new one. Like the CRE-
ATE USER statement, you use plain text password followed by the IDENTIFIED
BY clause. The IDENTIFIED BY clause is optional.
• After the REQUIRE clause, you specify whether the account has to connect to
the database server over the secure connection using SSL.
• If you want the account to have the privilege that can grant its own privileges
to other accounts, you need to use the WITH clause with the GRANT OPTION
clause. In addition, you can use the WITH clause to allocate MySQL database
server’s resource e.g., to set how many connections or statements that an account
can use per hour. This is very helpful in shared environments such as MySQL
shared hosting.
• If the account that you specify in the GRANT statement after the TO clause ex-
ists, the GRANT statement modifies its privileges, otherwise, the GRANT state-
ment creates a new account with the specified privileges.
Besides granting privileges, the GRANT statement also assigns other characteristics
to an account such as:
Let’s practice with some examples of using MySQL GRANT statement to have a better
understanding.
If you want to create a super account that can do anything including being able to
grant privileges to other users, you can use the following statements:
The ON *.* clause means all databases and all objects in the databases. The only
limitation of the super user is that it can only connect to the database server from the
localhost, which makes the MySQL server more secure.
To create a user that has all access in the sample database and can connect from any
host you use the following statements:
You can grant multiple privileges using a single GRANT statement. For example, you
can create a user that can execute the SELECT, INSERT and UPDATE statements
against the classicmodels sample database using the following statements:
PRIVILEGE DESCRIPTION
ALL [PRIVILEGES] Grant all privileges at specified access level except
GRANT OPTION
ALTER Allow to use of ALTER TABLE statement
ALTER ROUTINE Allow user to alter or drop stored routine
CREATE Allow user to create database and table
CREATE ROUTINE Allow user to create stored routine
CREATE TABLESPACE Allow user to create, alter or drop tablespaces and log
file groups
CREATE TEMPORARY TABLES Allow user to create temporary table by using
CREATE TEMPORARY TABLE
CREATE USER Allow user to use the CREATE USER, DROP USER, RE-
NAME USER, and REVOKE ALL PRIVILEGES state-
ments.
In order to revoke privileges from an account, you use the MySQL REVOKE state-
ment. The syntax of MySQL REVOKE statement is as follows:
Explanation:
• You specify a list of privileges that you want to revoke from an account right
after the REVOKE keyword. You need to separate privileges by a comma.
• ON clause specifies the privilege level at that privileges is to be revoked.
• After FROM keyword, you specify the account that you want to revoke the priv-
ileges. You can specify multiple accounts in the FROM clause. You separate the
accounts by the comma.
In order to revoke privileges from an account, you must have GRANT OPTION privi-
lege and privileges that you are revoking. To revoke all privileges, you use the follow-
ing
To execute the above command, you must have the global CREATE USER privilege or
the UPDATE privilege for the mysql database.
To revoke proxy user, you use the REVOKE PROXY command as follows:
A proxy user is a valid user in MySQL who can impersonate another user, therefore,
the proxy user has all privileges of the user that it impersonates.
Before revoking privileges of a user, it is good practice to check if the user has the
privileges by using the SHOW GRANTS statement as follows:
Suppose rfc account has privileges SELECT, UPDATE and DELETE in the classic-
models sample database . If you want to revoke UPDATE and DELETE privileges
from the rfc account, you can do so as follows:
First, you check the privileges of rfc account using SHOW GRANTS statement:
If you have not followed the previous tutorial on granting privileges to user, you can
first grant the SELECT, UPDATE and DELETE privileges for rfc account that con-
nects from localhost to the classicmodels database as follows:
Second, you can revoke the UPDATE and DELETE privileges from the rfc account:
Third, you can check the privileges of the rfc account again using the SHOW GRANTS
command.
If you want to revoke all privileges of the rfc account, you run the following command:
If you check the privileges of the rfc account again, you will see the rfc account has no
privilege.
The effect of MySQL REVOKE statement depends on the privilege level as follows:
• Changes that are made to the global privileges only take effect when the client
connects to the MySQL in the subsequent sessions. The changes are not applied
to all currently connected accounts.
• The change of database privileges is applied after the next USE statement.
• Table and column privilege’s changes are applied to all queries that are issued
after the changes are made.
leges on the view to your new user and see what happens.
CUSTOMIZED FUNCTIONS
20.1 Objectives
In this lab, students will learn how to define, and use functions in MySQL.
20.2 Scope
20.3 Introduction
A function returns one value and has only input parameters. You have already seen
the many built-in functions included in SQL, such as MAX, MIN, CEILING, FLOOR,
SQRT, etc. Custom functions (also called stored functions) can be created in MySQL.
The following illustrates the simplest syntax for creating a new stored function:
115
LAB 20. Customized Functions
3 [NOT] DETERMINISTIC
4 statements
1. You specify the name of the stored function after CREATE FUNCTION clause.
2. You list all parameters of the stored function inside the parentheses. By de-
fault, all parameters are IN parameters. You cannot specify IN , OUT or INOUT
modifiers to the parameters.
3. You must specify the data type of the return value in the RETURNS statement.
It can be any valid MySQL data types.
4. For the same input parameters, if the stored function returns the same result, it
is considered deterministic and otherwise the stored function is not determinis-
tic. You have to decide whether a stored function is deterministic or not. If you
declare it incorrectly, the stored function may produce an unexpected result, or
the available optimization is not used which degrades the performance.
5. You write the code in the body of the stored function. It can be a single statement
or a compound statement. Inside the body section, you have to specify at least
one RETURN statement. The RETURN statement returns a value to the caller.
Whenever the RETURN statement is reached, the stored function’s execution is
terminated immediately.
Example: The following function returns takes one value as input and returns a
single value.
1 select my_function(3);
Example:
The following example is a function that returns the level of a customer based on credit
limit. We use the IF statement to decide the credit limit. (classicmodels database).
1 DELIMITER $$
2
16 RETURN (lvl);
17 END
18 mysql stored function
1 SELECT
2 customerName, CustomerLevel(creditLimit)
3 FROM
4 customers
5 ORDER BY customerName;
STORED PROCEDURES
21.1 Objectives
This lab introduces the stored procedures and discuss several examples of how effec-
tively can we use stored procedures in MySQL.
21.2 Scope
21.3 Introduction
118
LAB 21. Stored Procedures
MySQL stored procedure Example We are going to develop a simple stored proce-
dure named GetAllProducts() to help you get familiar with the syntax. The GetAllProducts()
stored procedure selects all products from the products table.
Launch the mysql client tool and type the following commands:
1 DELIMITER //
2 CREATE PROCEDURE GetAllProducts()
3 BEGIN
4 SELECT * FROM products;
5 END //
6 DELIMITER ;
Explanation:
• The first command is DELIMITER //, which is not related to the stored procedure
syntax. The DELIMITER statement changes the standard delimiter which is semi-
colon ( ; ) to another. In this case, the delimiter is changed from the semicolon( ; )
to double-slashes // . Why do we have to change the delimiter? Because we want
to pass the stored procedure to the server as a whole rather than letting mysql
tool to interpret each statement at a time. Following the END keyword, we use
the delimiter // to indicate the end of the stored procedure. The last command
(DELIMITER;) changes the delimiter back to semicolon (;).
• We use the CREATE PROCEDURE statement to create a new stored procedure. We
specify the name of stored procedure after the CREATE PROCEDURE statement.
In this case, the name of the stored procedure is GetAllProducts. We put the
parentheses after the name of the stored procedure.
• The section between BEGIN and END is called the body of the stored procedure.
You put the declarative SQL statements in the body to handle business logic. In
this stored procedure, we use a simple SELECT statement to query data from the
products table.
In MySQL Workbench, you can create a new stored procedure as follows:
Right click on stored procedures and select create new stored procedure.
It will generate a query for you with a random generated name. You can change the
name to any name you want. We want to have content of products table for that we
are selecting all the data from products table.
In your stored procedures menu, you can see your procedure created.
In order to call a stored procedure, you use the following SQL command:
1 CALL products();
A variable is a named data object whose value can change during the stored procedure
execution. We typically use the variables in stored procedures to hold the immediate
results. These variables are local to the stored procedure. Declaring variables
To declare a variable inside a stored procedure, you use the DECLARE statement as
follows:
• First, you specify the variable name after the DECLARE keyword. The variable
name must follow the naming rules of MySQL table column names.
• Second, you specify the data type of the variable and its size. A variable can have
any MySQL data types such as INT , VARCHAR , DATETIME , etc.
• Third, when you declare a variable, its initial value is NULL . You can assign the
variable a default value by using DEFAULT keyword.
We want declare a variable named total sale and with default value 0.
MySQL allows you to declare two or more variables that share the same data type
using a single DECLARE statement as following:
We declared two integer variables x and y, and set their default values to zero.
Once you declared a variable, you can start using it. To assign a variable another
value, you use the SET statement, for example:
1. Create a stored procedure for any table following the manual process.
2. Create a stored procedure for average of quantity ordered in orderdetails table.
You can follow automatic/ manual any process you want.
3. Count total of amount from payments table and store the results in a variable.
22.1 Objectives
The purpose of this lab is to make students learn how to pass parameters to stored
procedures.
22.2 Scope
22.3 Introduction
The parameters make the stored procedure more flexible and useful. In MySQL, a
parameter has one of three modes IN, OUT or INOUT.
• IN – is the default mode. When you define an IN parameter in a stored proce-
dure, the calling program has to pass an argument to the stored procedure. In
addition, the value of an IN parameter is protected. It means that even the value
of the IN parameter is changed inside the stored procedure; its original value is
retained after the stored procedure ends. In other words, the stored procedure
only works on the copy of the IN parameter.
• OUT – the value of an OUT parameter can be changed inside the stored procedure
and its new value is passed back to the calling program. Notice that the stored
procedure cannot access the initial value of the OUT parameter when it starts.
• INOUT – an INOUT parameter is the combination of IN parameter and OUT
125
LAB 22. Stored Procedure Parameters
parameter. It means that the calling program may pass the argument, and the
stored procedure can modify the INOUT parameter and pass the new value back
to the calling program.
Each parameter is separated by a comma ( , ) if the stored procedure has more than
one parameter.
The following example illustrates how to use the IN parameter in the GetOfficeByCountry
stored procedure that selects offices located in a particular country.
The countryName is the IN parameter of the stored procedure. Inside the stored pro-
cedure, we select all offices that locate in the country specified by the countryName
parameter. Suppose, we want to get all offices in the USA, we just need to pass a value
(USA) to the stored procedure as follows:
Change the country name to Pakistan; they do not have any offices in Pakistan.
To get all offices in France, we pass the France literal string to the GetOfficeByCountry
stored procedure as follows:
The following stored procedure returns the number of orders by order status. It has
two parameters: orderStatus : IN parameter that is the order status which we want
to count the orders.
total : OUT parameter that stores the number of orders for a specific order status.
Type the following CountOrderByStatus stored procedure.
1 DELIMITER $$
2 CREATE PROCEDURE CountOrderByStatus(
3 IN orderStatus VARCHAR(25),
4 OUT total INT) //global variables
5 BEGIN
6 SELECT count(orderNumber)
7 INTO total
8 FROM orders
9 WHERE status = orderStatus;
10 END$$
11 DELIMITER ;
To get the number of shipped orders, we call the CountOrderByStatus stored proce-
dure and pass the order status as Shipped , and also pass an argument ( @total ) to
get the return value.
1 CALL CountOrderByStatus(’Shipped’,@total);
2 SELECT @total;
To get the number of orders that are in process, we call the CountOrderByStatus
stored procedure as follows:
The following example demonstrates how to use INOUT parameter in the stored pro-
cedure.
• The set_counter stored procedure accepts one INOUT parameter ( count ) and
one INparameter ( inc ).
• Inside the stored procedure, we increase the counter ( count ) by the value of the
incparameter.
See how we call the set_counter stored procedure:
Select all the content from customers table for a particular customer. Then using the
IN mode type, pass name in arguments.
TRIGGERS
23.1 Objective
• SQL Triggers
23.2 Scope
23.3 Introduction
A SQL trigger is a named set of SQL statements that are triggered automatically
when a data modification (i.e., INSERT, UPDATE, DELETE) occurs or if certain data
definitions are encountered. If a condition stated within a trigger is met, then a pre-
scribed action is taken. Triggers are used when you need to perform, under specified
conditions, a certain action as the result of some database event (e.g., the execution
of a DML statement such as INSERT, UPDATE, or DELETE or the DDL statement ALTER
TABLE). Thus, a trigger has three parts—the event, the condition, and the action—and
these parts are reflected in the coding structure for triggers.
A SQL trigger is a special type of stored procedure. It is special because it is not called
directly like a stored procedure. The main difference between a trigger and a stored
131
LAB 23. Triggers
Let’s start creating a trigger in My-SQL to log the changes of the employees table.
Step 1: Create a new table named employees_audit to keep the changes of the em-
ployee table. The following statement creates the employee_audit table.
Step 2: Create a BEFORE UPDATE trigger that is invoked before a change is made to
the employees table.
1 DELIMITER $$
2 CREATE TRIGGER before_employee_update
3 BEFORE UPDATE ON employees
4 FOR EACH ROW
5 BEGIN
6 INSERT INTO employees_audit
7 SET action = ’update’,
8 employeeNumber = OLD.employeeNumber,
9 lastname = OLD.lastname,
10 changedat = NOW();
11 END$$
12 DELIMITER ;
Step 3: In a trigger defined for INSERT, you can use NEW keyword only. You cannot use
the OLD keyword. However, in the trigger defined for DELETE, there is no new row so
you can use the OLD keyword only. In the UPDATE trigger, OLD refer to the row before
it is updated and NEW refers to the row after it is updated.
Then, to view all triggers in the current database, you use SHOW TRIGGERS state-
ment as follows:
1 SHOW TRIGGERS;
In addition, if you look at the schema using MySQL Workbench under the employ-
ees > triggers, you will see the before_employee_update trigger as shown in the
screenshot below:
Step 4: After that, update the employees table to check whether the trigger is invoked.
1 UPDATE employees
2 SET
3 lastName = ’Phan’
4 WHERE
5 employeeNumber = 1056;
Step 5: To check if the trigger was invoked by the UPDATE statement, you can query
the employees_audit table using the following query:
Another Example:
Now to understand trigger, create a new table named: PriceUpdates_T.
1 use pineview;
2 create table PriceUpdates_T
3 (
4 ProductID int,
5 ProductDescription varchar(50),
6 UpdateDate DATE,
7 NewPrice decimal(6,2)
8 )
Now we write the trigger code as follows, that will create a trigger with name:
StandardPriceUpdate.
1 use pineview;
2
1 show triggers;
Now the following command will automatically execute (trigger) the trigger
StandardPriceUpdate.
After the above command is run, check the data in PriceUpdates_T table.
Example:
Now define the trigger. It will be executed before every INSERT statement for the
people table:
1 delimiter //
2 CREATE TRIGGER agecheck BEFORE INSERT ON people FOR EACH ROW IF NEW.age
,→ < 0 THEN SET NEW.age = 0; END IF;//
3 delimiter ;
If you are using MySQL command shell, the following output will be shown.
+——---+——----+
| age | name |
+—--—-+—---—-+
| 0 | Sid |
| 30 | Josh |
+—--—-+——----+
Lab Task:
• Create a table result with columns student_name, student_reg, course_code,
marks,
• Create another table result_correction with the same columns as the above
table and an additional column correction_time
• Create a trigger to store the existing result into result_correction before up-
dating the table result. The correction_time column should store the time
this correction was made.
Home Work:
Create another addition column in the result_correction and modify the trigger to
store the user name of the user who corrects the results.
INDEXING
24.1 Objectives
• Students will learn the benefits of creating indexes on database tables, how to
create indexes on table fields, and how to drop indexes.
• Students will understand the relation of indexes with a table’s foreign keys. Stu-
dents will learn how to create indexes on foreign key, and how to drop a foreign
key index
24.2 Scope
24.3 Introduction
A database index is a data structure that improves the speed of operations in a ta-
ble. Indexes can be created using one or more columns, providing the basis for both
rapid random lookups and efficient ordering of access to records. Creating indexing
improves the performance of SELECT operations. Indexes also add to the cost of in-
serts, updates, and deletes because each index must be updated.
138
LAB 24. Indexing
Syntax:
This index allows duplicate values. To creates a unique index on a table which does not
allow duplicate values the UNIQUE keyword is used according to the followng syntax.
Example:
In the following SQL statement an index is created on a new table.
Example:
An index can be creating index on existing table. The SQL statement below creates an
index named AnyIndex on the Name column in the city table:
Example:
To see the structure of a table we use the DESCRIBE command.
1 DESCRIBE CUSTOMER_T;
If you are using MySQL Workbench the following output will be produced.
1 DESCRIBE CUSTOMER_T;
You can use SHOW INDEX command to list out all the indexes associated with a table.
Syntax:
Example: The following statements show the indexes created on the employeeskills_t
table in the pineview database.
1 use pineview;
2 show indexes from employeeskills_t;
Output:
DROP INDEX is used to remove index on the customer name in the table.
Example:
Indexes can also be create on foreign keys as illustrated in the following example.
Example:
Step1: Create two tables:
Note: When we create a foreign key in a table, the index is made automatically on the
foreign key attribute.
Task: Verify whether the index has been created.
Even after dropping the foreign key, the index still resides and has to be dropped
manually, by
Note: When we drop a foreign key, the index does not automatically delete, and we
Task 1: Create index on any column of the territory_t table of pineview database.
Task 2:
• Download the employees database from: https://github.com/datacharmer/
test_db/archive/master.zip
• Import the databse into your local mysql MySQL by executing the SQL scripts
in the zip file.
• Create some indexes and compare the performance (in milliseconds) of a select
and an insert query before and after the creating indexes.
TRANSACTION MANAGEMENT
25.1 Objectives
25.2 Scope
25.3 Introduction
Transactions have the following four standard properties, usually referred to by the
acronym ACID:
143
LAB 25. Transaction Management
• Atomicity: ensures that all operations within the work unit are completed suc-
cessfully; otherwise, the transaction is aborted at the point of failure and previ-
ous operations are rolled back to their former state.
• Consistency: ensures that the database properly changes states upon a suc-
cessfully committed transaction.
• Isolation: enables transactions to operate independently on and transparent to
each other.
• Durability: ensures that the result or effect of a committed transaction persists
in case of a system failure.
Example:
Consider a financial transfer where money from one account is placed into another
account. Suppose that Bill writes a check to Bob for $100.00 and Bob cashes the check.
Bill’s account should be decremented by $100.00 and Bob’s account incremented by the
same amount:
If a crash occurs between the two statements, the operation is incomplete. Depending
on which statement executes first, Bill is $100 short without Bob having been credited,
or Bob is given $100 without Bill having been debited.
In MySQL, transactions begin with the statement BEGIN WORK and end with either
a COMMIT or a ROLLBACK statement. The SQL commands between the beginning
and ending statements form the bulk of the transaction.
A transaction ends when it is committed or rolled back, either explicitly with a COMMIT
or ROLLBACK statement or implicitly when a DDL (Data Definition Language (DDL) is
used to manage table and index structure.
To use transactions in MySQL, you must use a transactional storage engine such as
InnoDB or Falcon. Engines such as MyISAM and MEMORY will not work.
These two keywords Commit and Rollback are mainly used for MySQL Transactions.
When a successful transaction is completed, the COMMIT command should be issued
so that the changes to all involved tables will take effect.
If a failure occurs, a ROLLBACK command should be issued to return every table
referenced in the transaction to its previous state.
25.7 AUTOCOMMIT
You can control the behavior of a transaction by setting session variable called AUTO-
COMMIT. If AUTOCOMMIT is set to 1 (the default), then each SQL statement (within
a transaction or not) is considered a complete transaction and committed by default
when it finishes.
When AUTOCOMMIT is set to 0, by issuing the SET AUTOCOMMIT=0 command, the
subsequent series of statements acts like a transaction and no activities are committed
until an explicit COMMIT statement is issued.
By default, MySQL runs in autocommit mode, which means that changes made by
individual statements are committed to the database immediately to make them per-
manent.
The statement creates an InnoDB table, but you can use a different transactional
storage engine if you like. Next, initiate a transaction with START TRANSACTION,
add a couple of rows to the table, commit the transaction, and then see what the table
looks like:
1 START TRANSACTION;
2 INSERT INTO t SET name = ’William’;
3 INSERT INTO t SET name = ’Wallace’;
4 COMMIT;
5 SELECT * FROM t;
+---------+
| name |
+---------+
| Wallace |
| William |
+---------+
You can see that the rows have been recorded in the table. If you had started up a
second instance of mysql and selected the contents of t after the inserts but before
the commit, the rows would not show up.They would not become visible to the second
mysql process until the COMMIT statement had been issued by the first one.
If an error occurs during a transaction, you can cancel it with ROLLBACK. Using the
t table again, you can see this by issuing the following statements:
1 START TRANSACTION;
2 INSERT INTO t SET name = ’Gromit’;
3 INSERT INTO t SET name = ’Wallace’;
MySQL will show the following error: ERROR 1062 (23000): Duplicate entry ’Wallace’
for key 1
To undo the previous set of statements type the following:
1 ROLLBACK;
2 SELECT * FROM t;
+---------+
| name |
+---------+
| Wallace |
| William |
+---------+
The second INSERT attempts to place a row into the table that duplicates an existing
name value.The statement fails because name has a UNIQUE index. After issuing
the ROLLBACK, the table has only the two rows that it contained prior to the failed
transaction.
In particular, the INSERT that was performed just prior to the point of the error has
been undone and its effect is not recorded in the table.
Issuing a START TRANSACTION statement while a transaction is in process commits
the current transaction implicitly before beginning a new one.
Another way to perform transactions is to manipulate the autocommit mode directly
using SET statements:
1 SET autocommit = 0;
2 SET autocommit = 1;
Setting the autocommit variable to zero disables autocommit mode. The effect of any
statements that follow becomes part of the current transaction, which you end by
issuing a COMMIT or ROLLBACK statement to commit or cancel it.With this method,
autocommit mode remains off until you turn it back on, so ending one transaction also
begins the next one.You can also commit a transaction by re-enabling autocommit
mode.
To see how this approach works, begin with the same table as for the previous
Examples:
1 DROP TABLE t;
2 CREATE TABLE t (name CHAR(20), UNIQUE (name)) ENGINE = InnoDB;
Then disable autocommit mode, insert some rows, and commit the transaction:
1 SET autocommit = 0;
2 INSERT INTO t SET name = ’William’;
3 INSERT INTO t SET name = ’Wallace’;
4 COMMIT;
5 SELECT * FROM t;
+---------+
| name |
+---------+
| Wallace |
| William |
+---------+
At this point, the two rows have been committed to the table, but autocommit mode
remains disabled. If you issue further statements, they become part of a new transac-
tion, which may be committed or rolled back independently of the first transaction.To
verify that autocommit is still off and that ROLLBACK will cancel uncommitted state-
ments, issue the following statements:
MySQL will show the following error: ERROR 1062 (23000): Duplicate entry ’Wallace’
for key 1
1 ROLLBACK;
2 SELECT * FROM t;
+---------+
| name |
+---------+
| Wallace |
| William |
+---------+
To re-enable autocommit mode, use this statement:
1 SET autocommit = 1;
As just described, a transaction ends when you issue a COMMIT or ROLLBACK state-
ment, or when you re-enable autocommit while it is disabled.Transactions also end un-
der other circumstances. In addition to the SET autocommit, START TRANSACTION,
BEGIN, COMMIT, and ROLLBACK statements that affect transactions explicitly, cer-
tain other statements do so implicitly because they cannot be part of a transaction. In
general, these tend to be DDL (data definition language) statements that create, alter,
or drop databases or objects in them, or statements that are lock-related. For exam-
ple, if you issue any of the following statements while a transaction is in progress, the
server commits the transaction first before executing the statement:
• ALTER TABLE
• CREATE INDEX
• DROP DATABASE
• DROP INDEX
• DROP TABLE
• LOCK TABLES
• RENAME TABLE
• SET autocommit = 1 (if not already set to 1)
• TRUNCATE TABLE
• UNLOCK TABLES (if tables currently are locked)
A transaction also ends if a client’s connection ends or is broken before a commit oc-
curs. In this case, the server automatically rolls back any transaction the client was
performing. If a client program automatically reconnects after its connection to the
server is lost, the connection will be reset to its default state of having autocommit
enabled.
Example: Transactions are useful in all kinds of situations. Suppose that you’re
working with the score table that is part of the grade-keeping project and you discover
that the grades for two students have gotten mixed up and need to be switched. The
incorrectly entered grades are as follows:
+------------+----------+-------+
To fix this, student 8 should be given a score of 13 and student 9 a score of 18. That
can be done easily with two statements:
However, it’s necessary to ensure that both statements succeed as a unit. This is a
problem to which transactional methods may be applied. To use START TRANSAC-
TION, do this:
1 START TRANSACTION;
2 UPDATE score SET score = 13 WHERE event_id = 5 AND student_id = 8;
3 UPDATE score SET score = 18 WHERE event_id = 5 AND student_id = 9;
4 COMMIT;
To accomplish the same thing by manipulating the autocommit mode explicitly in-
stead, do this:
1 SET autocommit = 0;
2 UPDATE score SET score = 13 WHERE event_id = 5 AND student_id = 8;
3 UPDATE score SET score = 18 WHERE event_id = 5 AND student_id = 9;
4 COMMIT;
5 SET autocommit = 1;
Either way, the result is that the scores are swapped properly:
+------------+----------+-------+
| student_id | event_id | score |
+------------+----------+-------+
| 8 | 5 | 13 |
| 9 | 5 | 18 |
+------------+----------+-------+
+------+
| i |
+------+
| 1 |
| 3 |
+------+
After executing these statements, the first and third rows have been inserted, but the
second one has been canceled by the partial rollback to the my_savepoint savepoint.
LOCKS
26.1 Objectives
26.2 Scope
26.3 Introduction
MySQL allows a client session to acquire a table lock explicitly for preventing other
sessions from accessing the table during a specific period.
A client session can acquire or release table locks only for itself. It cannot acquire or
release table locks for other sessions.
Case Study: create a sample database named sampledb that includes a simple table
named tbl to practice the table locking statements.
151
LAB 26. Locks
Syntax
The simple form of acquiring a lock for a table is as follows:
You put the name of the table after the LOCK TABLES keywords and followed by a
lock type. MySQL provides two lock types: READ and WRITE . We will go into detail
of each lock type in the next section.
To release a lock for a table, you use the following statement:
1 UNLOCK TABLES;
1 SELECT CONNECTION_ID();
1 SELECT CONNECTION_ID();
2 INSERT INTO tbl(col) VALUES(10);
1 SELECT CONNECTION_ID();
2 SELECT * FROM tbl;
After that, to acquire a lock, you use the LOCK TABLE statement.
Finally, in the same session, if you try to insert a new row into the tbl table, you will
get an error message.
1 SELECT CONNECTION_ID();
2 SELECT * FROM tbl;
3 INSERT INTO tbl(col) VALUES(11);
Error Code: 1099. Table ’tbl’ was locked with a READ lock and can’t be
updated.
So the once READ lock is acquired, you cannot write data into the table within the
same session.
Example: Let’s check the READ lock from a different session.
First, connect to the sampledb and check the connection id:
1 SELECT CONNECTION_ID();
Next, insert a new row into the tbl table from the second session.
The insert operation from the second session is in the waiting state because a READ
lock already acquired on the tbl table by the first session and it has not released yet.
You can see the detailed information from the SHOW PROCESSLIST statement.
1 SHOW PROCESSLIST;
After that, go back to the first session and release the lock by using the UNLOCK TA-
BLES statement. After you release the READ lock from the first session, the INSERT
operation in the second session executed.
Finally, check it the data of the tbl table to see if the INSERT operation from the
second session really executed.
After that, from the second session, try to write and read data:
MySQL puts those operations into a waiting state. You can check it using the SHOW
PROCESSLIST statement.
1 SHOW PROCESSLIST;
1 UNLOCK TABLES;
You will see all pending operations from the second session executed.
27.1 Objectives
ER Model:
In this scenario, every department offers one or more programs and each program
must belong to a single department. There are many students in each department
but each student must belong to a single department. Every student registers a single
157
LAB 27. Special Lab Task I
28.1 Objectives
Write code to create tables which are according to the ER design (given) and implement
additional requirements in each sub section:
ER Model:
160
LAB 28. Special Lab Task II
Book publishing company is going to store records of their books, with authors, its
number of stores along with their employees in the computer system. The company
wants to store books data like book name, book id, publishing company, book price.
Each book is recognized by book id. Author includes author name and author id. An
author is identified by author id. An author may write or contribute in one or more
books, but a book must refer to at least one author. The company has more than one
store in the country. A store has its store id, and location in the country. A store is
recognized by store id and its location. The company has many employees. Employee’s
data includes employee id, employee name, employee salary, and employee address.
The company wants to store employee’s address in parts like city name, post code,
and street name. Each store can have more than one employee, but each store must
be managed by exactly one employee. Every employee works under one store of the
company. There are some employees who supervise other employees. An employee
can supervise one or more employees but a single employee can be supervised under a
single employee.
According to the scenario, four tables have to be created that are, Employee, Store,
Book, Author. One additional table with name Book_Author as bridge table will be
created because of many-to-many relationship between book and author. One more
table will be created to hold multiple locations of store.
The detail of table with attributes, and primary key and foreign keys with additional
constraints is given bellow:
1. Creating tables and constraints with additional requirements:
(a) Employee (ssNo, name, streetNo, city, zipCode, salary, superSsNo)
• Set ssNo as Primary key
• Set superSsNo as foeign key which has been added as an additional
column in the same table affecting recursive relationship.
• dName must not be null
• Add check constraint that the salary must be between 1200and 5000
(b) Store (storeId, sName):
• Set storeId as primary key
(c) Location (location, storeLid):
• Set storeLid as foeign key which has been added as an additional col-
umn in the location table which is an additional table because location
attribute was multivalued attribute in the store entity type.
• Set location and storeLid as composite primary key attribute.
(d) Book (bookId, bName, publisher, price)
• Set bookId as primary key
• Set “XYZ” as default value of publisher attribute
(e) Author (authorId, authorName)
29.1 Objectives
Write code to create tables which are according to the ER design (given) and imple-
ment additional requirements in each sub section: ER Model: A multination company
wants to build a computer system. It has its number of departments, engineers with
other employees, engineers work on number of projects. Each department has a name,
number and location. A department may exist at different locations in the world. Each
department is identified by its department number. There are many employees like
engineers with special expertise, medical doctors, and other supporting staff. The com-
pany stores each employee’s employee identification number, name, hiredate, contract
date with its starting and expiring date of contract, salary address, gender, and birth
date. Each employee is recognized by its employee identification number. Every em-
ployee works in a single department, but a department may have many employees.
An employee can manage a single department, and each department has exactly one
manager. A departments offer zero or more projects, but each project must belong to
at least one department. A project has its project name, project type, and duration.
Each project is identified by its project number. An employee may work on number of
projects, but each project must have at least one employee.
The special task has been divided as the following:
1. Creating tables and constraints with additional requirements
2. DML operations on the tables
163
LAB 29. Special Lab Task III
CREATING ERD
30.1 Objective
30.2 Scope
To create a new model, start the MySQL Workbench tool and click on the Create New
EER Model option located in the Data Modeling column of the home screen. A new
panel will be added to the workbench labeled Model:
167
LAB 30. Creating ERD
Begin the modeling process by double clicking on the tab labeled mydb MySQL Schema.
In the resulting properties panel change the name of the schema to mySample:
Close the schema property panel by clicking on the small "x" next in the Schema
tab. Having given our schema a name, we can now add a table to the model. This
is achieved by double clicking on the Add Table button in the Tables panel:
Change the table name to inventory and then select the Columns tab to begin the
By default, the workbench will create a non-null primary key named idinventory. For
the purposes of this exercise we will keep this column, though in practice this can be
changed. Select the second line, double click in the Column Name field and name the
column product. Accept the default value of VARCHAR for the datatype. Repeat these
steps to add a price column of type FLOAT and a quantity column of type INTEGER.
Each of these should be declared as non-null by checking the boxes in the NN column:
Before proceeding, save the model using the File -> Save Model menu item, or using
the appropriate toolbar button.
To generate an EER diagram of our model, select the Model -> Create Diagram from
Catalog Objects menu option. The diagram illustrated in the following figure will then
be generated:
Having created a model, the next step is to generate a SQL script from the model and
feed it through to a database server where it will be executed to create the physical
database and table. To achieve this, select the Database -> Forward Engineer. . . menu
option. In the resulting dialog, a range of selections are available to filter and modify
the script that will ultimately be generated. Unless you have specific requirements,
leave the default selections unchanged. In addition, the objects that are to be gen-
erated may also be selected. Since this is a very simple example, and all we have to
generate is table information, select only the Export MySQL Table Objects option and
click Next to review the generated SQL script:
Assuming the script appears as expected given the initial model from which it has
been generated, click Next to specify the server to which the script is to be sent (or
save the script if it is to be used later, perhaps within the SQL Editor or mysql client):
Select the stored connection to which the script is to be sent together with any other
connection parameters that are required, click on Execute and enter the password if
required to do so. The success or otherwise of the execution will then be reported in
the following screen. Assuming a successful operation, the new database will now be
present on the designated database server.
Create the ERD following the above procedure for Special Lab Task I (page 157).