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

Preface 1 Data Handling in Files: VIII 1

This document outlines chapters in a book or manual about data handling in databases and SQL. It covers topics like reading and writing files in Java, installing and setting up databases like MySQL, creating tables, using DDL and DML commands, creating SQL scripts, and select queries. Each chapter describes objectives, scope, and examples for key concepts and includes exercises for readers.

Uploaded by

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

Preface 1 Data Handling in Files: VIII 1

This document outlines chapters in a book or manual about data handling in databases and SQL. It covers topics like reading and writing files in Java, installing and setting up databases like MySQL, creating tables, using DDL and DML commands, creating SQL scripts, and select queries. Each chapter describes objectives, scope, and examples for key concepts and includes exercises for readers.

Uploaded by

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

Contents

Preface viii

1 Data handling in files 1


1.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 Case Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.4 How to solve it . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.5 Java Language Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.5.1 Reading Ordinary Text Files in Java . . . . . . . . . . . . . . . . . 3
1.5.2 Writing Text Files in Java . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Home Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2 Storing information by relating data in files 6


2.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 Home Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3 Installation and setup of different DBMS 8


3.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3 MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.4 Getting familiar with environment . . . . . . . . . . . . . . . . . . . . . . . 11
3.5 Oracle Online Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.5.1 SQL Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.5.2 SQL Workshop Icons . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.5.3 SQL Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.5.4 Object Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.5.5 Searching for and Selecting Database objects . . . . . . . . . . . . 16
3.5.6 Browsing a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.6 MS SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.7 Sample databases used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.8 Lab/Home Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

4 Creating simple tables in different DBMS 23


4.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.3 Database Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.4 Create Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

i
4.5 Create a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.6 Enter and view data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.7 Lab Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

5 Basic DDL and DML using query editor 28


5.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
5.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
5.3 Query Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
5.4 Using the File/Open Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
5.5 Using the Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
5.6 Data Definition Language (DDL) . . . . . . . . . . . . . . . . . . . . . . . . 30
5.7 Creating Tables Using MySQL . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.8 Creating Tables Using Oracle/PLSQL . . . . . . . . . . . . . . . . . . . . . 32
5.9 Creating table in MS SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.10 Data Manipulation Language (DML) . . . . . . . . . . . . . . . . . . . . . 34
5.11 Lab Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

6 Creating and using SQL Scripts 35


6.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.3 Case Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.4 Understanding keys and constraints . . . . . . . . . . . . . . . . . . . . . . 37
6.5 Lab and home tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

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

8 More on Select Queries 44


8.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
8.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
8.3 Sorting Results (ORDER BY Clause) . . . . . . . . . . . . . . . . . . . . . 44
8.4 Using the SQL Aggregate Functions . . . . . . . . . . . . . . . . . . . . . 45
8.5 Restricting groupings (HAVING clause) . . . . . . . . . . . . . . . . . . . . 46
8.6 Subquery Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
8.7 ANY and ALL keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
8.8 Lab Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

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

10 Nested Queries (Exercise) 55


10.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
10.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
10.3 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

11 Expressions and Single Row functions 57


11.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
11.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
11.3 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
11.4 Mathematical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
11.5 String Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
11.6 Lab Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

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

14 Multiple Join and Union 75


14.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
14.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
14.3 Multiple Join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
14.4 The SQL UNION Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
14.5 SQL join with update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
14.6 MySQL Delete with inner Join . . . . . . . . . . . . . . . . . . . . . . . . . 78
14.7 MySQL DELETE JOIN with LEFT JOIN . . . . . . . . . . . . . . . . . . . 79
14.8 Lab Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

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

19 Security and Privileges 104


19.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
19.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
19.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
19.4 Access control in MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
19.4.1 Grant tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
19.5 Creating users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
19.5.1 Creating new users using CREATE USER statement . . . . . . . 106
19.5.2 Create new user by using INSERT statement . . . . . . . . . . . 107
19.6 Changing password for accounts . . . . . . . . . . . . . . . . . . . . . . . . 107
19.6.1 MySQL changing password using UPDATE statement . . . . . . 107
19.6.2 MySQL changing password using SET PASSWORD statement . 108
19.6.3 MySQL changing password using GRANT USAGE statement . . 108
19.7 MySQL GRANT Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
19.7.1 MySQL GRANT examples . . . . . . . . . . . . . . . . . . . . . . . 110
19.8 MySQL REVOKE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
19.8.1 Effect of REVOKE statement . . . . . . . . . . . . . . . . . . . . . . . 113
19.9 Lab Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

20 Customized Functions 115


20.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
20.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
20.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
20.4 Custom function syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
20.5 Lab Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

21 Stored Procedures 118


21.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
21.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
21.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
21.4 Creating stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
21.5 Calling stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
21.6 MySQL Stored Procedure Variables . . . . . . . . . . . . . . . . . . . . . . 122
21.7 Assigning variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
21.8 Lab Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

22 Stored Procedure Parameters 125


22.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
22.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
22.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
22.4 Defining Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
22.5 MySQL stored procedure parameter examples . . . . . . . . . . . . . . . . 126
22.6 IN parameter example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
22.7 OUT parameter example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
22.8 INOUT parameter example . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
22.9 Lab Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

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

25 Transaction Management 143


25.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
25.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
25.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
25.4 Properties of Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
25.5 Transactions and storage engines . . . . . . . . . . . . . . . . . . . . . . . 144
25.6 COMMIT and ROLLBACK . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
25.7 AUTOCOMMIT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
25.8 Performing transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
25.9 Transaction Savepoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
25.10Lab Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150

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

27 Special Lab Task I 157


27.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
27.2 Case study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

28 Special Lab Task II 160


28.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
28.2 Case study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

29 Special Lab Task III 163


29.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
29.2 Case study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
30 Creating ERD 167
30.1 Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
30.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
30.3 Creating a New Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
30.4 Generating a Model Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . 169
30.5 Generating a Script and Creating a Database . . . . . . . . . . . . . . . . 170
30.6 Lab Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
PREFACE

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.

Member Database Systems Domain

viii
LAB 1

DATA HANDLING IN FILES

1.1 Objectives

Performing basic data handling using general purpose programming language without
DBMS to emphasize the importance of DBMS.

1.2 Scope

• Storing data in files using Java


• Retrieving Data from Files
• Generating information from data files

1.3 Case Study

In today’s lab we:


1. Allow the user to enter and save students information in students.txt file i.e.
Student Id, Name
2. Allow the user to enter and save students transcript information in Transcript.txt
file i.e. Student Id, Course Name, GPA
3. Generate the following information from Student.txt file:
(a) List students of “BSE” discipline only.
(b) How many students names start with “Muhammad”.
4. Generate the following information from Transcript.txt file:

1
LAB 1. Data handling in files

(a) Display transcript details for the subject “Operating System”


(b) Take the course name from user and then display records with GPA greater
than 2.
Note: You can implement the solution in C/C++ or Java.

1.4 How to solve it

1. Take student information and save to Student file


(a) Student Id and Name are separated by “!” characters
(b) Every line contain data of a specific student
2. Your Students.txt file should look like below:
SP14-BSE-001!Fida Muhammad
SP15-BSE-033!Hashim
SP15-BSE-060!Ghulam Rafi
3. Take Transcript details and save to Transcript.txt file.
(a) CourseName, GPA and Student Id are separated by "!" characters
(b) Every line contain data of a specific course for a student
4. You Transcript.txt file should look like below:
Database Systems!3.2!SP14-BSE-001
Operating Systems!2.5!SP15-BSE-033
Data Structure!3.6!SP15-BSE-060
5. You will need to use the split function of the String class to read each column
from a row.

String[] columns = line.split("!");

Where columns[0] is the “Student Id” and columns[1] is the “Student Name” for
Students.txt file.

1.5 Java Language Solution

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

Database Systems Lab Manual – Page 2 | 171


LAB 1. Data handling in files

• FileReader for text files in your system’s default encoding.


• FileInputStream for binary files and text files that contain ’weird’ characters.
FileReader (for text files) should usually be wrapped in a BufferedFileReader. This
saves up data so you can deal with it a line at a time or whatever instead of character
by character.
If you want to write files, basically all the same stuff applies, except you’ll deal with
classes named FileWriter with BufferedFileWriter for text files, or FileOutputStream
for binary files.

1.5.1 Reading Ordinary Text Files in Java

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.*;

1 public class Test {


2 public static void main(String [] args) {
3

4 // The name of the file to open.


5 String fileName = "temp.txt";
6

7 // This will reference one line at a time


8 String line = null;
9

10 try {
11 // FileReader reads text files in the default
,→ encoding.
12 FileReader fileReader =
13 new FileReader(fileName);
14

15 // Always wrap FileReader in BufferedReader.


16 BufferedReader bufferedReader =
17 new BufferedReader(fileReader);
18

19 while((line = bufferedReader.readLine()) !=
,→ null) {
20 System.out.println(line);
21 }
22

23 // Always close files.


24 bufferedReader.close();
25 }
26 catch(FileNotFoundException ex) {

Database Systems Lab Manual – Page 3 | 171


LAB 1. Data handling in files

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 }

1.5.2 Writing Text Files in Java

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

5 // The name of the file to open.


6 String fileName = "temp.txt";
7

8 try {
9 // Assume default encoding.
10 FileWriter fileWriter =
11 new FileWriter(fileName);
12

13 // Always wrap FileWriter in BufferedWriter.


14 BufferedWriter bufferedWriter =
15 new BufferedWriter(fileWriter);
16

17 // Note that write() does not automatically


18 // append a newline character.
19 bufferedWriter.write("Hello there,");
20 bufferedWriter.write(" here is some text.");
21 bufferedWriter.newLine();
22 bufferedWriter.write("We are writing");
23 bufferedWriter.write(" the text to the file.");
24

Database Systems Lab Manual – Page 4 | 171


LAB 1. Data handling in files

25 // Always close files.


26 bufferedWriter.close();
27 }
28 catch(IOException ex) {
29 System.out.println(
30 "Error writing to file ’"
31 + fileName + "’");
32 // Or we could just do this:
33 // ex.printStackTrace();
34 }
35 }
36 }

1.6 Home Exercise

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?

Database Systems Lab Manual – Page 5 | 171


LAB 2

STORING INFORMATION BY
RELATING DATA IN FILES

2.1 Objectives

1. Relating data in files with each other


2. Queries/Information from multiple files
3. To realize what are the challenges solved by DBMS System i.e.
(a) Reading and Writing to same file concurrently
(b) Generating information from files

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

2.3 Home Exercise

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"

Database Systems Lab Manual – Page 7 | 171


LAB 3

INSTALLATION AND SETUP OF


DIFFERENT DBMS

3.1 Objectives

Installing and configuring different DBMS

3.2 Scope

• DBMS Installation guide


– MYSQL Server
– MS SQL Server
– Oracle online workspace/ SQLPlus
• Getting familiar with environment

3.3 MySQL

Step 1: Download MySQL 5.1 for Windows Step 2: Install MySQL


Double click the MSI installer to start installing MySQL..
(1) Welcome to the Setup Wizard for MySQL Server 5.1. Click Next to continue.

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.

Database Systems Lab Manual – Page 9 | 171


LAB 3. Installation and setup of different DBMS

(4) Installation in progress.


(5) More information about MySQL Enterprise Subscription.

(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.

Database Systems Lab Manual – Page 10 | 171


LAB 3. Installation and setup of different DBMS

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/

3.4 Getting familiar with environment

To run MySQL Workbench got to: Programs-> MYSQL Workbench

Home page interface MySQL Workbench version 6.3.4


Click on local instance MYSQL root if available. If the connection is not available click
on + sign to create new connection. You can give any name. However, the password
given at provided at the time of installation must be used.

Database Systems Lab Manual – Page 11 | 171


LAB 3. Installation and setup of different DBMS

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.

Different Views in Workbench

Database Systems Lab Manual – Page 12 | 171


LAB 3. Installation and setup of different DBMS

3.5 Oracle Online Workspace

3.5.1 SQL Workshop

The SQL Workshop provides tools that enable you to view and manage database ob-
jects.

3.5.2 SQL Workshop Icons

You access SQL Workshop by clicking the SQL Workshop icon on the Workspace home
page. The SQL Workshop home page appears.

The SQL Workshop home page has the following options.


1. Object Browser.

Database Systems Lab Manual – Page 13 | 171


LAB 3. Installation and setup of different DBMS

2. SQL Commands.
3. SQL Scripts.
4. Utilities.
5. Restful Services.

3.5.3 SQL Commands

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.

Database Systems Lab Manual – Page 14 | 171


LAB 3. Installation and setup of different DBMS

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.

3.5.4 Object Browser

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.

Database Systems Lab Manual – Page 15 | 171


LAB 3. Installation and setup of different DBMS

3.5.5 Searching for and Selecting Database objects

To search for a database object in the Object Selection pane:


• On the Workspace home page, click SQL Workshop and then Object Browser.
• Object Browser appears.
• Select an object type from the Object list.
• To search for an object name, enter a case insensitive search term in the Search
field.
• To view all objects, leave the search field blank.

3.5.6 Browsing a Table

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

Database Systems Lab Manual – Page 16 | 171


LAB 3. Installation and setup of different DBMS

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.

3.6 MS SQL Server

Step 1: Download MS-SQL server(any version) for Windows. You can download it
from dream spark student’s account as well.

Database Systems Lab Manual – Page 17 | 171


LAB 3. Installation and setup of different DBMS

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,

Database Systems Lab Manual – Page 18 | 171


LAB 3. Installation and setup of different DBMS

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.

Database Systems Lab Manual – Page 19 | 171


LAB 3. Installation and setup of different DBMS

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.

Database Systems Lab Manual – Page 20 | 171


LAB 3. Installation and setup of different DBMS

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.

Windows server 2012 has been installed with Datacenter.

Database Systems Lab Manual – Page 21 | 171


LAB 3. Installation and setup of different DBMS

3.7 Sample databases used

Tentative databases, case studies can change according to requirements.


• world.sql
• Sakila.sql
• winevalley.sql

3.8 Lab/Home Task

• Install MySQl and MySQL workbench in your lab PC as well as your home com-
puter.

Database Systems Lab Manual – Page 22 | 171


LAB 4

CREATING SIMPLE TABLES IN


DIFFERENT DBMS

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.

4.3 Database Name

• A name can start with either a letter (a, b, c, d, e, f, g, h, i, j, k, l,


m, n, o, p, q, r, s, t, u, v, w, x, y,z, A, B, C, D, E, F, G, H, I,

23
LAB 4. Creating simple tables in different DBMS

J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, or Z), a digit (0, 1,


2,3, 4, 5, 6, 7, 8, or 9), an underscore (_) or a non-readable charac-
ter. Examples are _n, act,
• After the first character (letter, digit, underscore, or symbol), the name can have
combinations of underscores, letters, digits, or symbols. Examples are _n24,
act_52_t
• A name cannot include space, that is, empty characters. If you want to use a
name that is made of various words, start the name with an opening square
bracket and end it with a closing square bracket. Example are [Full Name] or
[Date of Birth]
A database is primarily a file. As such, it must have a name that allows the operating
system to identify it. If you use the Database Properties dialog box of the SQL Server
Enterprise Manager, if you specify the database name in the General property page
and click OK, the interpreter automatically creates a new file that includes and the
name you specified for the database and adds the _Data string to it: this is the name
that will allow the operating system to identify your database’s file.

4.4 Create Database

A "Database" in SQL Server is a container that holds a group of related objects. In


addition to storing the actual data, a Database also stores the structure of how that
data is saved (called a Table), and any related helper objects such a Queries (saved
ways to look data up). To begin, we’ll create a Database using the graphical interface
called the "SQL Server Management Studio".
From the Windows Start Menu, select "Microsoft SQL Server", and then "SQL Server
Management Studio". Once the Management Studio starts, right click the Databases
folder and select new Database. Enter a name in the "Database name" text box. For
this example, well use the name "Test".

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.

Database Systems Lab Manual – Page 24 | 171


LAB 4. Creating simple tables in different DBMS

4.5 Create a Table

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".

Database Systems Lab Manual – Page 25 | 171


LAB 4. Creating simple tables in different DBMS

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.

4.6 Enter and view data

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.

Database Systems Lab Manual – Page 26 | 171


LAB 4. Creating simple tables in different DBMS

4.7 Lab Tasks

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

Database Systems Lab Manual – Page 27 | 171


LAB 5

BASIC DDL AND DML USING QUERY


EDITOR

5.1 Objectives

• Introduction to Query Editor


• Basic DDL Statements
• Basic DML Statement

5.2 Scope

• Basic DDL using query editors


• Basic DML using query editors

5.3 Query Editors

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.

5.4 Using the File/Open Menu

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.

5.5 Using the Toolbar

On the Standard toolbar, click one of the following buttons:


• New Query Opens a new editor window of the type associated with the current
connection in Management Studio. The editor window uses the same authentica-
tion information as the current connection. For example, if you select an instance
of the Database Engine in Object Explorer, and then click the New Query but-
ton, Management Studio opens a 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.

Database Systems Lab Manual – Page 29 | 171


LAB 5. Basic DDL and DML using query editor

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;

5.6 Data Definition Language (DDL)

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

Database Systems Lab Manual – Page 30 | 171


LAB 5. Basic DDL and DML using query editor

• RENAME - rename an object

5.7 Creating Tables Using MySQL

The MySQL CREATE TABLE statement allows you to create and define a table. Syntax

CREATE TABLE [IF NOT EXISTS]


table_name ( column_list datatype [null|not null, auto increment,
,→ constraint ) engine=table_type

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.

1 CREATE TABLE contacts


2 ( contact_id INT(11) NOT NULL AUTO_INCREMENT,
3 last_name VARCHAR(30) NOT NULL,
4 first_name VARCHAR(25),
5 birthday DATE,
6 CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
7 );

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

Database Systems Lab Manual – Page 31 | 171


LAB 5. Basic DDL and DML using query editor

30 characters in length) and can not contain NULL values.


• The third column is called first_name which is a VARCHAR datatype (maxi-
mum 25 characters in length) and can contain NULL values.
• The fourth column is called birthday which is a DATE datatype and can contain
NULL values.
• The primary key is called contacts_pk and is set to the contact_id column.

5.8 Creating Tables Using Oracle/PLSQL

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:

1 CREATE TABLE table_name


2 (
3 column1 datatype [ NULL | NOT NULL ],
4 column2 datatype [ NULL | NOT NULL ],
5 ...
6 column_n datatype [ NULL | NOT NULL ]
7 );

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.

1 CREATE TABLE customers


2 ( customer_id number(10) NOT NULL,
3 customer_name varchar2(50) NOT NULL,
4 city varchar2(50)
5 );

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.

Database Systems Lab Manual – Page 32 | 171


LAB 5. Basic DDL and DML using query editor

• The second column is called customer_name which is a varchar2 datatype (50


maximum characters in length) and also can not contain null values.
• The third column is called city which is a varchar2 datatype but can contain null
values.

5.9 Creating table in MS SQL

The CREATE TABLE statement is used to create a table in a database. Syntax

1 CREATE TABLE table_name


2 (
3 column_name1 data_type(size),
4 column_name2 data_type(size),
5 column_name3 data_type(size),
6 ....
7 );

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

1 CREATE TABLE [dbo].[Customers](


2 [Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
3 [FirstName] [varchar](50) NOT NULL,
4 [LastName] [varchar](50) NOT NULL,
5 [Gender] [bit] NOT NULL,
6 [DOB] [datetime] NOT NULL,
7 [PhoneNumber] [varchar](15) NOT NULL);

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.

Database Systems Lab Manual – Page 33 | 171


LAB 5. Basic DDL and DML using query editor

• The fifth column is called city which is a varchar datatype (255 maximum char-
acters in length) but can contain null values.

5.10 Data Manipulation Language (DML)

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

1 INSERT INTO Customers (FirstName,LastName,Gender,DOB,PhoneNumber)


2 VALUES (’Muhammad’,’Ali’,1,’1/1/1991’,’0443426278817876’)
3

4 UPDATE Customers SET FirstName = ’Ahmad’,DOB = ’4/4/1992’


5 WHERE FirstName = ’Muhammad’;
6

8 DELETE FROM Customers WHERE FirstName = ’Muhammad’;


9

10 SELECT Id,FirstName,LastName,Gender,DOB,PhoneNumber
11 FROM Customers;

5.11 Lab Tasks

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.

Database Systems Lab Manual – Page 34 | 171


LAB 6

CREATING AND USING SQL SCRIPTS

6.1 Objectives

• Creating Script File with following tasks:


– Create database
– Generate the structure of the database
– Insert Sample Data into tables
– Generate Useful information from the tables
– Basic Constraints Introduction

6.2 Scope

• Primary and foreign keys


• Data types
• Basic domain constraints

6.3 Case Study

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:

1 create database DreamHome


2 use DreamHome

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

9 create table PrivateOwner (ownerNo varchar(20) NOT NULL PRIMARY KEY,


,→ fName varchar(50) NOT NULL, lName varchar(50) NOT NULL, address
,→ varchar(50) NOT NULL, telNo varchar(20) NOT NULL)
10

11 create table PropertyForRent (propertyNo varchar(20) NOT NULL PRIMARY


,→ KEY, street varchar(100) NOT NULL, city varchar(50) NOT NULL,
,→ postcode varchar(20) NOT NULL, type varchar(10) NOT NULL, rooms int
,→ NOT NULL, rent DECIMAL NOT NULL,
12 ownerNo varchar(20) References PrivateOwner(ownerNo), staffNo
,→ varchar(20) NOT NULL References Staff(staffNo),branchNo varchar(20)
,→ NOT NULL References Branch(branchNo));
13

14 create table Viewing (clientNo varchar(20) NOT NULL References


,→ Client(clientNo), propertyNo varchar(20) NOT NULL References
,→ PropertyForRent(propertyNo), viewDate DateTime NOT NULL, comment
,→ varchar(200) NOT NULL)
15

16 create table Registration(clientNo varchar(20) NOT NULL References


,→ Client(clientNo),branchNo varchar(20) NOT NULL References
,→ Branch(branchNo),staffNo varchar(20) NOT NULL References
,→ Staff(staffNo),dateJoined DateTime NOT NULL)

Run the following query to insert the data into two tables

1 INSERT into Branch (branchNo, street, city, postcode) VALUES (N’B001’,


,→ N’H#79 I-10/2’, N’ISB’, N’52000’)
2 INSERT into Branch (branchNo, street, city, postcode) VALUES (N’B002’,
,→ N’H#78 Supply’, N’ABT’, N’53000’)
3 INSERT into Branch (branchNo, street, city, postcode) VALUES (N’B003’,
,→ N’H#79 I-10/2’, N’ISB’, N’52000’)
4 INSERT into Branch (branchNo, street, city, postcode) VALUES (N’B004’,
,→ N’H#78 Mandian’, N’ABT’, N’53000’)

Database Systems Lab Manual – Page 36 | 171


LAB 6. Creating and using SQL Scripts

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’)

6.4 Understanding keys and constraints

• Primary Key Vs Entity Integrity


• Foreign Key Vs Referential Integrity
• Null Constraint
• Domain Constraints and Data Types

6.5 Lab and home tasks

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.

Database Systems Lab Manual – Page 37 | 171


LAB 7

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

7.3 Understanding Distinct

Task: Run the following queries and record your results in results column.

38
LAB 7. Select Queries

Query Results

1 Select city from Branch


2 Select distinct(city) from
,→ Branch

7.4 Understanding Aliases

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

1 Select city from Branch

Query Results

1 Select city As MyCity from


,→ Branch

Query Results

1 Select staffNo as ID, fName as


,→ FirstName, lName as [Last
,→ Name], position as Position,
,→ sex as Gender, DOB as [Date
,→ of Birth], salaray as Income
,→ from Staff

Query Results

1 Select (fName +’ ’+lName) as


,→ [Name], position as Position
,→ from Staff

Tip: You can concatenate column for a derived columns.


Filtering of Data based on single and compound conditions You can select data
of your choice from all rows of a table by specifying a condition using a Where clause
in the SELECT Command.

Row selection (WHERE clause)

The five basic search conditions:


• Comparison Compare the value of one expression to the value of another expres-

Database Systems Lab Manual – Page 39 | 171


LAB 7. Select Queries

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

1 SELECT staffNo, fName, lName,


,→ position, salary FROM Staff
2 WHERE salary >10000;
3 SELECT * FROM Branch
4 WHERE city =‘London’ OR city
,→ =‘Glasgow’

Database Systems Lab Manual – Page 40 | 171


LAB 7. Select Queries

Query Results

1 SELECT staffNo, fName, lName,


,→ position, salary
2 FROM Staff
3 WHERE salary BETWEEN 20000 AND
,→ 30000;

Query Results

1 SELECT staffNo, fName, lName,


,→ position, salary
2 FROM Staff
3 WHERE salary >= 20000 AND salary
,→ <=30000;

Query Results

1 SELECT staffNo, fName, lName,


,→ position
2 FROM Staff
3 WHERE position IN (‘Manager’,
,→ ‘Supervisor’);

Query Results

1 SELECT staffNo, fName, lName,


,→ position
2 FROM Staff
3 WHERE position =‘Manager’ OR
,→ position =‘Supervisor’;

Note: The IN test provides a more efficient way of expressing the search condition,
particularly if the set contains many values.

7.5 Pattern match search condition

SQL has two special pattern-matching symbols:


• % percent character represents any sequence of zero or more characters (wild-
card).
• _ underscore character represents any single character. All other characters in
the pattern represent themselves. For example:
– address LIKE ’H%’ means the first character must be H, but the rest of
the string can be anything.
– address LIKE ’H___’ means that there must be exactly four characters in

Database Systems Lab Manual – Page 41 | 171


LAB 7. Select Queries

the string, the first of which must be an H.


– address LIKE ’%e’ means any sequence of characters, of length at least 1,
with the last character an e.
– address LIKE ’%Glasgow%’ means a sequence of characters of any length
containing Glasgow.
– address NOT LIKE ’H%’ means the first character cannot be an H.
Example
Find all owners with the string "Glasgow" in their address.

1 SELECT ownerNo, fName, lName, address, telNo


2 FROM PrivateOwner
3 WHERE address LIKE ‘%Glasgow%’;

Example:NULL search condition (IS NULL/IS NOT NULL)


List the details of all viewings on property PG4 where a comment has not been sup-
plied.

1 SELECT clientNo, viewDate


2 FROM Viewing
3 WHERE propertyNo = ’PG4’ AND comment IS NULL;

7.6 Reading of Data from multiple tables

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

1 Select * from Branch,Staff

Query Results

1 Select * from Branch,Staff


2 Where Branch.banchNo =
,→ Staff.branchNo

Database Systems Lab Manual – Page 42 | 171


LAB 7. Select Queries

Query Results

1 Select * from Branch as b,Staff


,→ as s
2 Where b.banchNo = s.branchNo

Query Results

1 Select * from Branch as b,Staff


,→ as s,PropertyForRent as pfr
2 Where b.banchNo = Staff.branchNo
3 And b.banchNo = pfr.branchNo

Query Results

1 Select * from Branch as b,Staff


,→ as s,PropertyForRent as pfr
2 Where b.banchNo = Staff.branchNo
3 And b.banchNo = pfr.branchNo
4 And s.staffNo = pfr.staffNo

Tip: You can concatenate column for a derived columns

7.7 Exercises

1. Print the list of postcode without any repetition


2. Print all fName from Staff without repetition
3. List all staff with renaming all its columns in results
4. List all clients with re-naming all its columns to synonyms.
5. List all staff with a salary greater than 10,000.
6. List all managers and supervisors.

Database Systems Lab Manual – Page 43 | 171


LAB 8

MORE ON SELECT QUERIES

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.

8.3 Sorting Results (ORDER BY Clause)

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.

1 SELECT staffNo, fName, lName, salary


2 FROM Staff
3 ORDER BY salary DESC;

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.

1 SELECT propertyNo, type, rooms, rent


2 FROM PropertyForRent
3 ORDER BY type;
4 SELECT propertyNo, type, rooms, rent
5 FROM PropertyForRent
6 ORDER BY type, rent DESC;

8.4 Using the SQL Aggregate Functions

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:

1 SELECT staffNo, COUNT(salary)


2 FROM Staff;

Example: How many properties cost more than £350 per month to rent?

1 SELECT COUNT(*) AS myCount


2 FROM PropertyForRent
3 WHERE rent <=350;

Example: How many different properties were viewed in May 2004?

1 SELECT COUNT(DISTINCT propertyNo) AS myCount

Database Systems Lab Manual – Page 45 | 171


LAB 8. More on Select Queries

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.

1 SELECT COUNT(staffNo) AS myCount, SUM(salary) AS mySum


2 FROM Staff
3 WHERE position = ’Manager’;

Example: Find the minimum, maximum, and average staff salary.

1 SELECT MIN(salary) AS myMin, MAX(salary) AS myMax, AVG(salary) AS myAvg


2 FROM Staff;

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:

1 SELECT staffNo, COUNT(salary)


2 FROM Staff;

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.

8.5 Restricting groupings (HAVING clause)

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.

Database Systems Lab Manual – Page 46 | 171


LAB 8. More on Select Queries

8.6 Subquery Rules

The following rules apply to subqueries:


1. The ORDER BY clause may not be used in a subquery (although it may be used
in the outermost SELECT statement).
2. The subquery SELECT list must consist of a single column name or expression,
except for subqueries that use the keyword EXISTS
3. By default, column names in a subquery refer to the table name in the FROM
clause of the subquery. It is possible to refer to a table in a FROM clause of an
outer query by qualifying the column name.
4. When a subquery is one of the two operands involved in a comparison, the sub-
query must appear on the right-hand side of the comparison. For example, it
would be incorrect to express the last example as:

1 SELECT staffNo, fName, lName, position, salary


2 FROM Staff
3 WHERE (SELECT AVG(salary) FROM Staff) < salary;

8.7 ANY and ALL keywords

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.

1 SELECT staffNo, fName, lName, position, salary


2 FROM Staff
3 WHERE salary > SOME (SELECT salary
4 FROM Staff
5 WHERE branchNo = ’B003’);

Example: Find all staff whose salary is larger than the salary of every member of
staff at branch B003.

1 SELECT staffNo, fName, lName, position, salary


2 FROM Staff
3 WHERE salary > ALL (SELECT salary
4 FROM Staff
5 WHERE branchNo = ’B003’);

Database Systems Lab Manual – Page 47 | 171


LAB 8. More on Select Queries

8.8 Lab Tasks

Task: Perform all the examples in this lab.

Database Systems Lab Manual – Page 48 | 171


LAB 9

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

• An SQL query nested inside a larger query is called a subquery.


• A subquery may occur in :
– A SELECT clause
– A FROM clause
– A WHERE clause
• In MySQL subquery can be nested inside a SELECT, INSERT, UPDATE, DELETE, SET,
or DO statement or inside another subquery.
• A subquery is usually added within the WHERE Clause of another SQL SELECT
statement.

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.

9.4 Creating Sub-queries

Syntax:

1 SELECT ... FROM (subquery) [AS] name ...

Example: (Without Subquery) What are the name and address of the customer who
placed order number 1008?

1 SELECT CustomerName, CustomerAddress, CustomerCity, CustomerState,


,→ CustomerPostalCode
2 FROM Customer_T, Order_T
3 WHERE Customer_T.CustomerID = Order_T. CustomerID
4 AND OrderID = 1008;

Example: (With Sub-query): What are the name and address of the customer who
placed order number 1008?

1 SELECT CustomerName, CustomerAddress, CustomerCity,CustomerState,


,→ CustomerPostalCode
2 FROM Customer_T
3 WHERE Customer_T.CustomerID =
4 (SELECT Order_T.CustomerID
5 FROM Order_T
6 WHERE OrderID = 1008);
7 Query: What are the names of customers who have placed orders?
8 SELECT CustomerName
9 FROM Customer_T
10 WHERE CustomerID IN
11 (SELECT DISTINCT CustomerID
12 FROM Order_T);

Using the NOT IN qualifier: Query: Which customers have not placed any orders for
computer desks?

1 SELECT CustomerName

Database Systems Lab Manual – Page 50 | 171


LAB 9. Nested Queries

2 FROM Customer_T WHERE CustomerID NOT IN


3 (SELECT CustomerID FROM Order_T, OrderLine_t, Product_T WHERE
4 OrderLine_t.OrderID = Order_t.OrderID
5 AND OrderLine_T.ProductID = Product_t.ProductID
6 AND ProductDescription = ’Computer Desk’);

9.5 Using EXISTS and NOT EXISTS

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?

1 SELECT DISTINCT OrderID FROM OrderLine_T


2 WHERE EXISTS
3 (SELECT * FROM Product_T Where ProductID = Orderline_t.ProductID
4 AND ProductFinish = ’Natural Ash’
5 );

9.6 EXISTS versus IN and NOT EXISTS versus NOT


IN.

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:

1 SELECT priceEach * quantityOrdered


2 FROM orderdetails
3 WHERE priceEach * quantityOrdered > 10000
4 GROUP BY orderNumber;

Database Systems Lab Manual – Page 51 | 171


LAB 9. Nested Queries

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.

9.7 MySQL subquery in FROM clause

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;

Database Systems Lab Manual – Page 52 | 171


LAB 9. Nested Queries

Notice that the subquery returns the following result set that is used as a derived
table for the outer query.

9.8 MySQL correlated subquery

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/

Database Systems Lab Manual – Page 53 | 171


LAB 9. Nested Queries

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.

Database Systems Lab Manual – Page 54 | 171


LAB 10

NESTED QUERIES (EXERCISE)

10.1 Objectives

To consolidate the techniques learned in the previous Lab.

10.2 Scope

Further practice with nested queries.

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)

ployees who earn more than Mr. Bell.


7. Write a query to find the names (first_name, last_name), the salary of the em-
ployees who earn the same salary as the minimum salary for all departments.
8. Write a query to find the names (first_name, last_name), the salary of the em-
ployees whose salary greater than the average salary of all departments.
9. Write a query to find the names (first_name, last_name) and salary of the em-
ployees who earn a salary that is higher than the salary of all the Shipping Clerk
(JOB_ID = ’SH_CLERK’). Sort the results of the salary of the lowest to highest.
10. Write a query to find the names (first_name, last_name) of the employees who
are not supervisors.
11. Write a query to display the employee ID, first name, last names, and depart-
ment names of all employees.
12. Write a query to display the employee ID, first name, last names, salary of all
employees whose salary is above average for their departments.
13. Write a query to fetch even numbered records from employees table.
14. Write a query to find the 5th maximum salary in the employees table.
15. Write a query to find the 4th minimum salary in the employees table.
16. Write a query to select last 10 records from a table.
17. Write a query to list department number, name for all the departments in which
there are no employees in the department.
18. Write a query to get 3 maximum salaries.
19. Write a query to get 3 minimum salaries.
20. Write a query to get nth max salaries of employees.Further practice with nested
queries

Database Systems Lab Manual – Page 56 | 171


LAB 11

EXPRESSIONS AND SINGLE ROW


FUNCTIONS

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

This Lab covers following topics:


• Expressions
• String Functions
• Date Functions
• Mathematical Functions
• General Functions

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:

11.4 Mathematical Functions

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.

Database Systems Lab Manual – Page 58 | 171


LAB 11. Expressions and Single Row functions

SUM(), AVG(), MAX(), MIN()

11.5 String 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:

Query: Find the first character of the SalespersonName column in salesperson_t


table in the pineview database.
SQL:
SELECT SalespersonName, substr(SalespersonName,1,1)
FROM pineview.salesperson_t;
Output:

Database Systems Lab Manual – Page 59 | 171


LAB 11. Expressions and Single Row functions

11.6 Lab Task

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.

Database Systems Lab Manual – Page 60 | 171


LAB 12

AGGREGATE FUNCTIONS

12.1 Objectives

Using the SQL Aggregate Fucntions

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

12.4 The AVG() Function

The AVG() function returns the average value of a numeric column.


SQL AVG() Syntax

1 SELECT AVG(column_name) FROM table_name

Example:

To create an alias for the average output. Type the command

1 Select AVG(Population) as avgoutput from city;

If we use the following SQL statement:

1 SELECT population FROM city


2 WHERE Population>(SELECT AVG(population) FROM city);

The result will look like this:

Database Systems Lab Manual – Page 62 | 171


LAB 12. Aggregate Functions

12.5 SQL COUNT() Function

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:

1 SELECT COUNT(column_name) FROM table_name

Example:

SQL COUNT(*)
COUNT(*) returns the number of records in a table: Syntax:

1 SELECT COUNT(*) FROM table_name

COUNT(DISTINCT column_name)

Database Systems Lab Manual – Page 63 | 171


LAB 12. Aggregate Functions

COUNT(DISTINCT column_name) returns the number of distinct values of the specified


column:
Syntax:

1 SELECT COUNT(DISTINCT column_name) FROM table_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:

1 SELECT COUNT(Name) AS CityName FROM city


2 WHERE CountryCode=’PAK’;

Database Systems Lab Manual – Page 64 | 171


LAB 12. Aggregate Functions

12.6 FIRST() Function


The FIRST() function returns the first value of the selected column.
Syntax:

1 SELECT FIRST(column_name) FROM table_name

12.7 LAST() Function


The LAST() function returns the last value of the selected column.
Syntax:

1 SELECT LAST(column_name) FROM table_name

12.8 MAX() Function


The MAX() function returns the largest value of the selected column.
Syntax:

1 SELECT MAX(column_name) FROM table_name

Example:

12.9 MIN() Function


The MIN() function returns the smallest value of the selected column.

Database Systems Lab Manual – Page 65 | 171


LAB 12. Aggregate Functions

Syntax:

1 SELECT MIN(column_name) FROM table_name

12.10 SUM() Function


The SUM() function returns the total sum of a numeric column.
Syntax:

1 SELECT SUM(column_name) FROM table_name

Example:

12.11 GROUP BY Statement


Aggregate functions often need an added GROUP BY statement. The GROUP BY
Statement. The GROUP BY statement is used in conjunction with the aggregate func-
tions to group the result-set by one or more columns.
Syntax:

1 SELECT CountryCode, sum(Population)


2 FROM city
3 GROUP BY CountryCode;

Example:

Database Systems Lab Manual – Page 66 | 171


LAB 12. Aggregate Functions

12.12 HAVING Clause


The HAVING clause was added to SQL because the WHERE keyword could not be used
with aggregate functions.

Database Systems Lab Manual – Page 67 | 171


LAB 12. Aggregate Functions

12.13 Lab Task

1. Print countrycode and sum of percentage from countrylangauge, apply groupby


on countrycode.
2. Find sum of any integer column from country table.
3. Count number of records in country table.
4. Count Distinct languages from countrylanguage.

Database Systems Lab Manual – Page 68 | 171


LAB 13

MULTI-TABLE QUERIES

13.1 Objectives

Students will learn how access data from multiple tables using different types of joins

13.2 Scope

• Displaying data from multiple tables.


• Joins
• Inner join
• Left outer join
• Right outer join

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

13.4 Simple join

List the names of all clients who have viewed a property along with any comment
supplied.

1 SELECT c.clientNo, fName, lName, propertyNo, comment


2 FROM Client c, Viewing v
3 WHERE c.clientNo = v.clientNo;

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:

1 FROM Client c JOIN Viewing v ON c.clientNo = v.clientNo


2 FROM Client JOIN Viewing USING clientNo
3 FROM Client NATURAL JOIN Viewing

The first alternative produces a table with two identical clientNo columns. The re-
maining two produce a table with a single clientNo column

13.5 Sorting a join

For each branch office, list the numbers and names of staff who manage properties
and the properties that they manage.

1 SELECT s.branchNo, s.staffNo, fName, lName, propertyNo


2 FROM Staff s, PropertyForRent p
3 WHERE s.staffNo = p.staffNo
4 ORDER BY s.branchNo, s.staffNo, propertyNo;

13.6 Three-table join

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.

1 SELECT b.branchNo, b.city, s.staffNo, fName, lName, propertyNo


2 FROM Branch b, Staff s, PropertyForRent p
3 WHERE b.branchNo = s.branchNo AND s.staffNo = p.staffNo
4 ORDER BY b.branchNo, s.staffNo, propertyNo;

Note, again, that the SQL standard provides alternative formulations for the FROM and

Database Systems Lab Manual – Page 70 | 171


LAB 13. Multi-Table Queries

WHERE clauses, for example:

1 FROM (Branch b JOIN Staff s USING branchNo) AS bs


2 JOIN PropertyForRent p USING staffNo

13.7 Multiple grouping columns

Find the number of properties handled by each staff member.

1 SELECT s.branchNo, s.staffNo, COUNT(*) AS myCount


2 FROM Staff s, PropertyForRent p
3 WHERE s.staffNo = p.staffNo
4 GROUP BY s.branchNo, s.staffNo
5 ORDER BY s.branchNo, s.staffNo;

13.8 Computing a join

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:

1 SELECT [DISTINCT | ALL] {* | columnList}


2 FROM TableName1 CROSS JOIN TableName2

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.

Database Systems Lab Manual – Page 71 | 171


LAB 13. Multi-Table Queries

13.9 Outer joins

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.

1 SELECT b.*, p.*


2 FROM Branch1 b LEFT JOIN PropertyForRent1 p ON b.bCity = p.pCity;

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.

1 SELECT b.*, p.*


2 FROM Branch1 b RIGHT JOIN PropertyForRent1 p ON b.bCity = p.pCity;

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.

1 SELECT b.*, p.*


2 FROM Branch1 b FULL JOIN PropertyForRent1 p ON b.bCity = p.pCity;

This includes, not only those rows that have the same city, but also those rows that
are unmatched in both tables.

13.10 Join Examples

Example: What are the customer IDs and Names of all customers along with the
order id for all the orders that are placed?

1 SELECT Customer_T.CustomerID , Order_T.CustomerID, CustomerName,


,→ OrderID
2 FROM Customer_T, Order_T
3 WHERE Customer_T.CustomerID = Order_T.CustomerID ORDER BY OrderID;

Database Systems Lab Manual – Page 72 | 171


LAB 13. Multi-Table Queries

.
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?

1 SELECT Customer_t.customerid , order_t.customerid, CustomerName,


,→ OrderID
2 FROM customer_t
3 INNER JOIN Order_T ON
4 Customer_t.customerid = Order_T.customerid
5 ORDER BY OrderID;

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.

1 SELECT customer_t.CustomerID, CustomerName, OrderID FROM Customer_T


2 RIGHT OUTER JOIN Order_t ON
3 Customer_t.CustomerID = Order_t.CustomerID;

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 Customer_t.CustomerID, CustomerName , CustomerAddress,


,→ CustomerCity, CustomerState, CustomerPostalCode, Order_t.OrderID,
,→ OrderedQuantity, ProductDescription, ProductStandardPrice,
,→ (OrderedQuantity * ProductStandardPrice) AS price
2 FROM Order_t, Customer_t, Orderline_t, Product_t
3 WHERE
4 Customer_t.Customerid = Order_t.CustomerID AND
5 Orderline_T.orderID = order_t.orderid AND
6 orderline_t.ProductID = product_t.productid AND
7 Order_t.OrderID = 1006;

Example: Self join


This example illustrates the scenario times when a join requires matching rows in a
table with other rows in that same table – that is joining a table with itself.
What are the employee ID and name of each employee, and the name of his/her super-
visor (label the name of supervisor’s name with manager)?

1 SELECT
2 E.EmployeeID,

Database Systems Lab Manual – Page 73 | 171


LAB 13. Multi-Table Queries

3 E.EmployeeName,
4 M.EmployeeName AS Manager FROM
5 Employee_T E, Employee_T M
6 WHERE
7 E.EmployeeSupervisor = M.EmployeeID;

13.11 Lab Tasks

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.

Database Systems Lab Manual – Page 74 | 171


LAB 14

MULTIPLE JOIN AND UNION

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

14.3 Multiple Join

Syntax for multiple join is:

1 SELECT t1.col, t3.col FROM table1 join table2 ON table1.primarykey =


,→ table2.foreignkey
2 join table3 ON table2.primarykey =
,→ table3.foreignkey;

Example: Type the following query

75
LAB 14. Multiple Join and Union

1 Select customers.customerName, orderdetails.quantityordered from


,→ customers
2 inner join orders on customers.customerNumber=orders.customerNumber
3 inner join orderdetails on orders.ordernumber=orderdetails.ordernumber;

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.

14.4 The SQL UNION Operator

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

1 SELECT column_name(s) FROM table_name1


2 UNION
3 SELECT column_name(s) FROM table_name2

Note: The UNION operator selects only distinct values by default. To allow duplicate
values, use UNION ALL.
SQL UNION ALL Syntax

1 SELECT column_name(s) FROM table_name1


2 UNION ALL
3 SELECT column_name(s) FROM table_name2

Example:

1 SELECT customers.customerName FROM customers


2 UNION
3 SELECT orders.orderDate FROM orders;
4 SQL UNION ALL With WHERE

The following SQL statement uses UNION ALL to select all (duplicate values also).

1 SELECT customers.customerName, customers.addressLine1 FROM Customers


2 WHERE customerNumber=103

Database Systems Lab Manual – Page 76 | 171


LAB 14. Multiple Join and Union

3 UNION ALL
4 SELECT orders.orderNumber, orders.orderDate FROM orders
5 WHERE orders.customerNumber=103;

14.5 SQL join with update

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 UPDATE TABLE_A a JOIN TABLE_B b


2 ON a.join_col = b.join_col AND a.column_a = b.column_b
3 SET a.column_c = a.column_c + 1
4 UPDATE [table1_name] AS t1
5 INNER JOIN [table2_name] AS t2
6 ON t1.[column1_name] = t2.[column1_name]
7 SET t1.[column2_name] = t2.[column2_name];

Example: Type the follwong query

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

Database Systems Lab Manual – Page 77 | 171


LAB 14. Multiple Join and Union

13 AND c.val > 10;

14.6 MySQL Delete with inner Join

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: Try the query on two tables.

1 Delete productlines, products


2 From productlines
3 Inner join products on productlines.productline=products.productlines
4 Where productline=’classic Cars’;

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.

1 SELECT * FROM offices


2 WHERE officeCode = 5

Database Systems Lab Manual – Page 78 | 171


LAB 14. Multiple Join and Union

1 SELECT * FROM employees


2 WHERE officeCode = 5

Now, you can delete records associated with officeCode 5 from both offices and employ-
ees tables:

1 DELETE offices, employees


2 FROM offices
3 INNER JOIN employees
4 ON employees.officeCode = employees.officeCode
5 WHERE offices.officeCode = 5

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.

14.7 MySQL DELETE JOIN with LEFT JOIN

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:

Database Systems Lab Manual – Page 79 | 171


LAB 14. Multiple Join and Union

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;

Database Systems Lab Manual – Page 80 | 171


LAB 14. Multiple Join and Union

You will not see any row returned. It means you have successfully deleted customers
who have not ordered any products.

14.8 Lab Task

• Update employee first name with office number 6.


• Update customer with any a particular order number (you can select any order
number).
• Applying union print data of orders and order details table.
• Applying union print a particular office number of an employee. You can select
any office number you want.

Database Systems Lab Manual – Page 81 | 171


LAB 15

ADVANCED DML

15.1 Objectives

Introducing more advacne usage of data minipulation language.

15.2 Scope

• Insert
• Update
• Delete
• Adding comments on tables
Reference database: Perform Queries on World.sql/Employees.SQL sample database

15.3 The SQL DELETE Statement

The DELETE statement is used to delete rows in a table.


Syntax:

DELETE FROM table_name


WHERE some_column=some_value;

Example:
Example:

82
LAB 15. Advanced DML

DELETE FROM employees where employeeNumber=1076;

Delete All Data


It is possible to delete all rows in a table without deleting the table. This means that
the table structure, attributes, and indexes will be intact.
Syntax

DELETE FROM table_name;

or

DELETE * FROM table_name;

Example:

Delete from city;


Sample Query
Delete * from employees;

Note: Be very careful when deleting records. You cannot undo this statement!

15.4 The SQL UPDATE Statement

The UPDATE statement is used to update existing records in a table.


Syntax

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’

Database Systems Lab Manual – Page 83 | 171


LAB 15. Advanced DML

WHERE Empno = 5000;


Update Multiple Columns
UPDATE emp
SET MGR = 7936, ename = ‘Smith’
WHERE empno > 100;

15.5 Insert Query

Syntax:

INSERT INTO table


(column1, column2, ... column_n )
VALUES
(expression1, expression2, ... expression_n );

Alternative Syntax:

INSERT INTO table


(column1, column2, ... column_n )
SELECT expression1, expression2, ... expression_n
FROM source_table
[WHERE conditions];

Example:

Insert into department values(50, ’Computer’, ’Pakistan’, 0992);


Sample Query
INSERT INTO department
(deptno, dname)
SELECT deptno, dname
FROM department
WHERE deptno > 30;

Database Systems Lab Manual – Page 84 | 171


LAB 15. Advanced DML

15.6 Adding Comments on Table

COMMENT statement is used to add comments to tables.


Example:

COMMENT ON TABLE emp IS ’Employee Information’;

15.7 Lab Task

• Apply update on any country name.


• Delete Islamabad city by applying delete query on city table with it’s ID.
• Try to update values for null column COMM column
• Try to update it for a specific employee whose salary is less than 1000
• Try to insert values in customers table.

Database Systems Lab Manual – Page 85 | 171


LAB 16

ADVANCED DDL

16.1 Objectives

Introduction to advanced DDL queries.

16.2 Scope

• Create database
• Create tables
• Constraints
• Not null constraint
• Primary key
• Foreign key
• Alter table
• Drop statements
• Truncate table

16.3 Case Study

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

16.4 Creating Database

First, we will create a database for our case study by the following statement:

1 CREATE DATABASE patient;


2 SHOW DATABASES;

16.5 The SQL CREATE TABLE 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

1 CREATE TABLE table_name


2 (
3 column_name1 data_type(size),
4 column_name2 data_type(size),
5 column_name3 data_type(size),
6 ....
7 );

Database Systems Lab Manual – Page 87 | 171


LAB 16. Advanced DDL

To create the patientattributes table type the following statement

1 Create table patientattributes(PatientNumber int(10) not null,


2 firstName varchar(30), /* limit for varchar is 255*/
3 lastname varchar(30),
4 Address varchar(40),
5 primary key (PatientNumber));

Patient Attributes table

16.6 SQL Primary Key

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.

Database Systems Lab Manual – Page 88 | 171


LAB 16. Advanced DDL

To insert values into table;

1 INSERT INTO ‘patient‘.‘patientattributes‘ (‘PatientNumber‘,


,→ ‘firstName‘, ‘lastname‘, ‘Address‘) VALUES (’2’, ’hamza’, ’maqsod’,
,→ ’peshawar’);
2 INSERT INTO ‘patient‘.‘patientattributes‘ (‘PatientNumber‘,
,→ ‘firstName‘, ‘lastname‘, ‘Address‘) VALUES (’3’, ’any’, ’any’,
,→ ’any’);

Or you can enter data in table and execute on clicking apply.

Insert data in patientcharges table.

1 INSERT INTO patientcharges VALUES (’tablets’, 20664, 2, 345);

Database Systems Lab Manual – Page 89 | 171


LAB 16. Advanced DDL

16.7 SQL Constraints

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

1 CREATE TABLE table_name


2 (
3 column_name1 data_type(size) constraint_name,
4 column_name2 data_type(size) constraint_name,
5 column_name3 data_type(size) constraint_name,
6 ....
7 );

In SQL, we have the following constraints:


• NOT NULL - Indicates that a column cannot store NULL value
• UNIQUE - Ensures that each row for a column must have a unique value
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a
column (or combination of two or more columns) have an unique identity which
helps to find a particular record in a table more easily and quickly
• FOREIGN KEY - Ensure the referential integrity of the data in one table to
match values in another table
• CHECK - Ensures that the value in a column meets a specific condition
• DEFAULT - Specifies a default value when specified none for this column
SQL NOT NULL Constraint The NOT NULL constraint enforces a column to NOT
accept NULL values. The NOT NULL constraint enforces a field to always contain a
value. This means that you cannot insert a new record, or update a record without
adding a value to this field.
SQL UNIQUE Constraint
The UNIQUE constraint uniquely identifies each record in a database table.

Database Systems Lab Manual – Page 90 | 171


LAB 16. Advanced DDL

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.

16.8 The ALTER TABLE Statement

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:

1 ALTER TABLE table_name


2 ADD column_name datatype

Example: Type the following query.

1 alter table patientcharges add extrapayment varchar (255);

To delete a column in a table, use the following syntax (notice that some database
systems don’t allow deleting a column):

1 ALTER TABLE table_name


2 DROP COLUMN column_name;

Database Systems Lab Manual – Page 91 | 171


LAB 16. Advanced DDL

The DROP TABLE Statement The DROP TABLE statement is used to delete a table.

1 DROP TABLE table_name

The DROP DATABASE Statement


The DROP DATABASE statement is used to delete a database.

1 DROP DATABASE database_name

The TRUNCATE TABLE Statement


If we only want to delete the data inside the table, and not the table itself, we can use
the TRUNCATE TABLE statement:

1 TRUNCATE TABLE table_name

16.9 Lab Task

Create a table called suppliers which has 3 columns.


1. The first column is called supplier_id which is created as a number data type
(maximum 10 digits in length) and cannot contain null values.
2. The second column is called supplier_name which is a varchar2 datatype (50
maximum characters in length) and also can not contain null values.
3. The third column is called address which is a varchar2 data type but can contain
null values.
4. Define the supplier_id as the primary key
5. Create a second table named as Item with columns:
6. The first column itemname any length you want
7. The second column supplierId as foreignkey in item table
8. The third column should be itemprice In INT.

Database Systems Lab Manual – Page 92 | 171


LAB 17

DATABASE CONNECTIVITY

17.1 Objectives

To familiarize students with using database connective from java applications.

17.2 Scope

• Creating connection in Java NetBeans


• Using GUI features such as JTable.

17.3 Database connection in Java NetBeans

Snapshots for establishing database connection in Java netbeans.


Step 1: Click on services tab> Right click new connection. In new connection click on
drop down list and select mysql driver for your connection

93
LAB 17. Database Connectivity

Step2: Leave default settings as it is just enter default password that’s 12345.

Step 3: Click next

Database Systems Lab Manual – Page 94 | 171


LAB 17. Database Connectivity

Database Systems Lab Manual – Page 95 | 171


LAB 17. Database Connectivity

17.4 Adding views

You Can add any view you want according to your needs

17.5 Jtable control

Inserting Jtable control can help you to populate this table from database.

Database Systems Lab Manual – Page 96 | 171


LAB 17. Database Connectivity

You can also create Jtable manually from class code.

Database Systems Lab Manual – Page 97 | 171


LAB 17. Database Connectivity

Database Systems Lab Manual – Page 98 | 171


LAB 17. Database Connectivity

Use this connection establishment method according to your needs behind controls.

17.6 Lab Task

1. Establish connection to the tables developed in Lab Task 13.11.

Database Systems Lab Manual – Page 99 | 171


LAB 18

VIEWS

18.1 Objectives

Learning to Create and use views

18.2 Scope

• Views with joins


• Updateable views
• Modifiable views

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

18.4 Creating Updateable 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:

1 officeCode, phone and city.


2 CREATE VIEW officeInfo
3 AS
4 SELECT officeCode, phone, city
5 From offices;
6 Next, we can query data from the officeInfo view using the SELECT
,→ statement.
7 SELECT * FROM officeInfo;

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:

1 SELECT * FROM officeInfo


2 WHERE officeCode = 4;

18.5 Modifying views

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.

1 ALTER VIEW productdetailsinfo


2 AS SELECT productCode, upper(productName) FROM products;
3 Alter view productdetailsinfo
4 As
5 Select productcode, add column emailp varchar(255) from products;

Database Systems Lab Manual – Page 101 | 171


LAB 18. Views

First try to create example of organization:


We create a simple view against the employees table that displays the company’s or-
ganization structure:

1 CREATE VIEW organization


2 AS
3 SELECT CONCAT (E.lastname,E.firstname) AS Employee,
4 CONCAT (M.lastname,M.firstname) AS Manager
5 FROM employees AS E
6 INNER JOIN employees AS M
7 ON M.employeeNumber = E.ReportsTo
8 ORDER BY Manager;

To display the view’s definition, you use the SHOW CREATE

1 VIEW statement as follows:


2 SHOW CREATE VIEW organization;

The following query modifies the organization view by adding an addition email field.

1 ALTER VIEW organization


2 AS
3 SELECT CONCAT(E.lastname,E.firstname) AS Employee,
4 E.email AS employeeEmail,
5 CONCAT(M.lastname,M.firstname) AS Manager
6 FROM employees AS E
7 INNER JOIN employees AS M
8 ON M.employeeNumber = E.ReportsTo
9 ORDER BY Manager

To verify the change, you can query data from the organization view:

1 SELECT * FROM Organization


2 Create view productdetailsinfo
3 As
4 Select * from products;
5 Update productdetailsinfo
6 Set productname= ’hello’
7 Where productcode= ’S10_1678’;
8 select * from productdetailsinfo;

Database Systems Lab Manual – Page 102 | 171


LAB 18. Views

18.6 Removing views

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:

1 DROP VIEW [IF EXISTS] [database_name].[view_name];

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:

1 DROP VIEW IF EXISTS organization;

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.

18.7 Lab Task

• 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.

Database Systems Lab Manual – Page 103 | 171


LAB 19

SECURITY AND PRIVILEGES

19.1 Objectives

• Basic Database Administration


• Access control and privileges

19.2 Scope

• Access control in MySQL


• Creating users
• Granting and revoking privileges

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.

19.4 Access control in MySQL

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

• Request verification: once a connection is established successfully, for each state-


ment issued by the client, MySQL checks whether the client has sufficient priv-
ileges to execute that particular statement. MySQL has the ability to check a
privilege at the database, table, and field level.

19.4.1 Grant tables

There is a database named mysql created automatically by MySQL installer. The


mysql database contains five main grant tables. Administrators manipulate these
tables indirectly through the statements such as GRANT and REVOKE.
These grant tables include:
• user: contains user account and global privileges columns. MySQL uses the user
table to either accept or reject a connection from a host. A privilege granted in
the user table is effective to all databases on the MySQL server.
• db : contains database level privileges. MySQL uses the db table to determine
which database a user can access and from which host. A privilege granted at
the database level in the db table applies to the database and all objects belong
to that database e.g., tables, triggers, views, stored procedures, etc.

• table_priv and columns_priv : contains table-level and column-level privi-


leges. A privilege granted in the table_priv table applies to the table and its
columns while a privilege granted in the columns_priv table applies only to a
specific column of a table.
• procs_priv : contains stored functions and stored procedures privileges MySQL
makes use of those tables to control the privileges in MySQL database server.
MySQL makes use of those tables to control the privileges in MySQL database server.
A list of all tables in the mysql database can be view by following query.

1 use mysql;
2 show tables;

These tables can be accessed using standard select statements.

19.5 Creating users

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.

Database Systems Lab Manual – Page 105 | 171


LAB 19. Security and Privileges

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

3 select * from users;

19.5.1 Creating new users using CREATE USER statement

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:

1 CREATE USER user IDENTIFIED BY password

• The user account in the format ’username’@’hostname’ is followed by the CREATE


USER.
The password is specified after the IDENTIFIED BY clause. The password must
be in plain text. MySQL will encrypt the password for you when it saves the user
into the user table.
For example, to create a new user dbadmin that connects from localhost with the
password CrEate-User, you use the CREATE USER statement as follows:

1 CREATE USER dbadmin@localhost


2 IDENTIFIED BY ’CrEate-User’;

To allow a user to connect from any host, you use the

1 CREATE USER superadmin@’%’


2 IDENTIFIED BY ’Secured’;

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:

1 CREATE USER mysqladmin@’%.ciit.net.pk’


2 IDENTIFIED by ’SecurePass704’;

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

Database Systems Lab Manual – Page 106 | 171


LAB 19. Security and Privileges

contains special characters such as - or % .


Note: If you accidentally quote the account name like ’username@hostname’, MySQL
creates a user with the username@hostname username and allows the user to connect
from any host, which may not be what you expected.
The MySQL CREATE USER statement only creates a new user and does not grant any
privilege to that user. If you want to grant privileges to the user you use the MySQL
GRANT statement.

19.5.2 Create new user by using INSERT statement

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:

1 INSERT INTO user (host,user,password)


2 VALUES(’localhost’,’dbadmin’,PASSWORD(’CrEate-User’));
3 In this tutorial, you have learned various ways to create a user in
,→ MySQL using the CREATE USER statement and INSERT statement.

19.6 Changing password for accounts

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.

19.6.1 MySQL changing password using UPDATE 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’;

Database Systems Lab Manual – Page 107 | 171


LAB 19. Security and Privileges

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.

1 SELECT PASSWORD(’Secret1970’) AS encrypt_password;

This will display somthing like this:


*16A54B5EE15C823362FAE7F64409A8F8C8501DD6

19.6.2 MySQL changing password using SET PASSWORD state-


ment

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.

1 SET PASSWORD FOR ’bse’@’ciit.net.pk’ = PASSWORD(’Secret1970’);

19.6.3 MySQL changing password using GRANT USAGE state-


ment

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:

1 GRANT USAGE ON *.* TO mysqltutorial@mysqltutorial.org IDENTIFIED BY


,→ Secret1970;

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

Database Systems Lab Manual – Page 108 | 171


LAB 19. Security and Privileges

validation.

19.7 MySQL GRANT Statement

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:

1 GRANT privileges (column_list)


2 ON [object_type] privilege_level
3 TO account [IDENTIFIED BY ’password’]
4 [REQUIRE encryption]
5 WITH with_options;

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:

Database Systems Lab Manual – Page 109 | 171


LAB 19. Security and Privileges

• Limit account on access to the database server resource.


• Force account to use the secure connection when connecting to the database
server.
If you want to grant a particular privilege to an account, you must have at least that
privilege and GRANT OPTION privilege.
You often use the MySQL GRANT statement together with the CREATE USER state-
ment. You use the CREATE USER statement to create a new account first and then
use the MySQL GRANT statement to grant privileges to the created account.

19.7.1 MySQL GRANT examples

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:

1 CREATE USER ’super’@’localhost’ IDENTIFIED BY ’SecurePass1’;


2

3 GRANT ALL ON *.* TO ’super’@’localhost’ WITH GRANT OPTION;

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:

1 CREATE USER ’super2’@’%’ IDENTIFIED BY ’SecurePass2’;


2 GRANT ALL classicmodels.* TO ’super2’@’%’ WITH GRANT OPTION;

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:

1 CREATE USER ’rfc’@’%’ IDENTIFIED BY ’SecurePass3’;


2 GRANT SELECT, UPDATE, DELETE ON classicmodels.* TO ’rfc’@’%’;

Available privileges to use with MySQL GRANT


The following table illustrates some of privileges available in MySQL.

Database Systems Lab Manual – Page 110 | 171


LAB 19. Security and Privileges

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.

CREATE VIEW Allow user to create or modify view


DELETE Allow user to use DELETE
DROP Allow user to drop database, table and view
EVENT Allow user to schedule events in Event Scheduler
EXECUTE Allow user to execute stored routines
GRANT OPTION Allow user to have privileges to grant or revoke privi-
leges from other accounts
INDEX Allow user to create or remove indexes.
INSERT Allow user to use INSERT statement
LOCK TABLES Allow user to use LOCK TABLES on tables for which
you have the SELECT privilege
PROCESS Allow user to see all processes with SHOW PRO-
CESSLIST statement.
SELECT Allow user to use SELECT statement
SHOW DATABASES Allow user to show all databases
SHOW VIEW Allow user to use SHOW CREATE VIEW statement
SHUTDOWN Allow user to use mysqladmin shutdown command
TRIGGER Allow user to use TRIGGER operations.
UPDATE Allow user to use UPDATE statement
USAGE Equivalent to “no privileges”

19.8 MySQL REVOKE

In order to revoke privileges from an account, you use the MySQL REVOKE state-
ment. The syntax of MySQL REVOKE statement is as follows:

1 REVOKE privilege_type [(column_list)] [, priv_type


,→ [(column_list)]]...
2 ON [object_type] privilege_level
3 FROM user [, user]...

Database Systems Lab Manual – Page 111 | 171


LAB 19. Security and Privileges

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

1 REVOKE ALL PRIVILEGES, GRANT OPTION FROM user [, user]...

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:

1 REVOKE PROXY ON user FROM user [, user]...

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:

1 SHOW GRANTS FOR user;


2 MySQL REVOKE examples

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:

1 GRANT SELECT, UPDATE, DELETE ON ’classicmodels’.* TO ’rfc’@’localhost’

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:

1 GRANT SELECT, UPDATE, DELETE ON classicmodels.* TO ’rfc’@’localhost’;

Second, you can revoke the UPDATE and DELETE privileges from the rfc account:

Database Systems Lab Manual – Page 112 | 171


LAB 19. Security and Privileges

1 REVOKE UPDATE, DELETE ON classicmodels.* FROM ’rfc’@’localhost’;

Third, you can check the privileges of the rfc account again using the SHOW GRANTS
command.

1 SHOW GRANTS FOR ’rfc’@’localhost’;

1 GRANT SELECT ON ’classicmodels’.* TO ’rfc’@’localhost’

If you want to revoke all privileges of the rfc account, you run the following command:

1 REVOKE ALL PRIVILEGES, GRANT OPTION FROM ’rfc’@’localhost’;

If you check the privileges of the rfc account again, you will see the rfc account has no
privilege.

1 SHOW GRANTS FOR ’rfc’@’localhost’;

1 GRANT USAGE ON *.* TO ’rfc’@’localhost’

Note that USAGE privilege means no privileges in MySQL.

19.8.1 Effect of REVOKE statement

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.

19.9 Lab Task

• Create a user for your first name


• Grant create and select privileges on the pineview database.
• Create a new view for any tables
• Practice grand and revoke statements by granting and revoking any five privi-

Database Systems Lab Manual – Page 113 | 171


LAB 19. Security and Privileges

leges on the view to your new user and see what happens.

Database Systems Lab Manual – Page 114 | 171


LAB 20

CUSTOMIZED FUNCTIONS

20.1 Objectives

In this lab, students will learn how to define, and use functions in MySQL.

20.2 Scope

• Creating customized functions


• Passing arguments to customized functions
• Returning values fomr customized functions.

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.

20.4 Custom function syntax

The following illustrates the simplest syntax for creating a new stored function:

1 CREATE FUNCTION function_name(param1,param2,...)


2 RETURNS datatype

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 CREATE FUNCTION ‘my_function‘ (myinput INT)


2 RETURNS INTEGER
3 BEGIN
4 declare temp int;
5 SELECT COUNT(*) into temp from Product_T where productid>myinput;
6 RETURN temp;
7 END

To call this function we use code

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

3 CREATE FUNCTION CustomerLevel(p_creditLimit double) RETURNS VARCHAR(10)


4 DETERMINISTIC
5 BEGIN

Database Systems Lab Manual – Page 116 | 171


LAB 20. Customized Functions

6 DECLARE lvl varchar(10);


7

8 IF p_creditLimit > 50000 THEN


9 SET lvl = ’PLATINUM’;
10 ELSEIF (p_creditLimit <= 50000 AND p_creditLimit >= 10000) THEN
11 SET lvl = ’GOLD’;
12 ELSEIF p_creditLimit < 10000 THEN
13 SET lvl = ’SILVER’;
14 END IF;
15

16 RETURN (lvl);
17 END
18 mysql stored function

Now, we can call the CustomerLevel() in an SQL SELECT statement as follows:

1 SELECT
2 customerName, CustomerLevel(creditLimit)
3 FROM
4 customers
5 ORDER BY customerName;

20.5 Lab Tasks

1. Write a SQL function to convert temperature from Fahrenheit to Celsius scale.


2. Write a SQL function to find GP and letter grade from percentage marks as per
CIIT grading system.

Database Systems Lab Manual – Page 117 | 171


LAB 21

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

• Creating stored procudeures.


• Using stored procedures.

21.3 Introduction

A stored procedure is a segment of declarative SQL statements stored inside the


database catalog. Typically stored procedures help increase the performance of the
applications. Once created, stored procedures are compiled and stored in the database.
MySQL implements the stored procedures slightly differently as compared with other
DBMS. MySQL stored procedures are compiled on demand. After compiling a stored
procedure, MySQL puts it into a cache. MySQL maintains its own stored procedure
cache for every single connection. If an application uses a stored procedure multi-
ple times in a single connection, the compiled version is used; otherwise the stored
procedure works like a query.

118
LAB 21. Stored Procedures

21.4 Creating 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.

Database Systems Lab Manual – Page 119 | 171


LAB 21. Stored Procedures

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.

Database Systems Lab Manual – Page 120 | 171


LAB 21. Stored Procedures

In your stored procedures menu, you can see your procedure created.

21.5 Calling stored procedures

In order to call a stored procedure, you use the following SQL command:

1 CALL products();

Database Systems Lab Manual – Page 121 | 171


LAB 21. Stored Procedures

21.6 MySQL Stored Procedure Variables

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:

1 DECLARE variable_name datatype(size) DEFAULT default_value;

• 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.

1 DECLARE total_sale INT DEFAULT 0;

MySQL allows you to declare two or more variables that share the same data type
using a single DECLARE statement as following:

1 DECLARE x, y INT DEFAULT 0;

Database Systems Lab Manual – Page 122 | 171


LAB 21. Stored Procedures

We declared two integer variables x and y, and set their default values to zero.

21.7 Assigning variables

Once you declared a variable, you can start using it. To assign a variable another
value, you use the SET statement, for example:

1 DECLARE total_count INT DEFAULT 0;


2 SET total_count = 10;

The value of the total_count variable is 10 after the assignment.


Besides the SET statement, you can use SELECT INTO statement to assign the result
of a query, which returns a scalar value, to a variable. See the following example:

1 DECLARE total_products INT DEFAULT 0;


2 SELECT COUNT(*) INTO total_products
3 FROM products ;

Database Systems Lab Manual – Page 123 | 171


LAB 21. Stored Procedures

21.8 Lab Task

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.

Database Systems Lab Manual – Page 124 | 171


LAB 22

STORED PROCEDURE PARAMETERS

22.1 Objectives

The purpose of this lab is to make students learn how to pass parameters to stored
procedures.

22.2 Scope

• Passing parameters to stored procedures.


• IN, OUT or INOUT modes.

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.

22.4 Defining Parameters

The syntax of defining a parameter in the stored procedures is as follows:

1 MODE param_name param_type(param_size)

Each parameter is separated by a comma ( , ) if the stored procedure has more than
one parameter.

22.5 MySQL stored procedure parameter examples

22.6 IN parameter example

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:

Database Systems Lab Manual – Page 126 | 171


LAB 22. Stored Procedure Parameters

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:

22.7 OUT parameter example

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 ;

Database Systems Lab Manual – Page 127 | 171


LAB 22. Stored Procedure Parameters

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;

Change the status of order from shipped to not-shipped.

Database Systems Lab Manual – Page 128 | 171


LAB 22. Stored Procedure Parameters

To get the number of orders that are in process, we call the CountOrderByStatus
stored procedure as follows:

1 CALL CountOrderByStatus(’in process’,@total);


2 SELECT @total AS total_in_process;

22.8 INOUT parameter example

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

Database Systems Lab Manual – Page 129 | 171


LAB 22. Stored Procedure Parameters

incparameter.
See how we call the set_counter stored procedure:

22.9 Lab Task

Select all the content from customers table for a particular customer. Then using the
IN mode type, pass name in arguments.

Database Systems Lab Manual – Page 130 | 171


LAB 23

TRIGGERS

23.1 Objective

• SQL Triggers

23.2 Scope

• Creating and using triggers

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.

23.4 Difference between a trigger and a stored pro-


cedure

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

procedure is that a trigger is called automatically when a data modification event is


made against a table whereas a stored procedure must be called explicitly.
You can to define maximum six triggers for each table.
• BEFORE INSERT – activated before data is inserted into the table.
• AFTER INSERT – activated after data is inserted into the table.
• BEFORE UPDATE – activated before data in the table is updated.
• AFTER UPDATE – activated after data in the table is updated.
• BEFORE DELETE – activated before data is removed from the table.
• AFTER DELETE – activated after data is removed from the table.

23.5 MySQL trigger syntax

1 CREATE TRIGGER trigger_time trigger_name trigger_event


2 ON table_name
3 FOR EACH ROW
4 BEGIN
5 ...
6 END;

23.6 MySQL trigger example

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.

1 CREATE TABLE employees_audit (

Database Systems Lab Manual – Page 132 | 171


LAB 23. Triggers

2 id INT AUTO_INCREMENT PRIMARY KEY,


3 employeeNumber INT NOT NULL,
4 lastname VARCHAR(50) NOT NULL,
5 changedat DATETIME DEFAULT NULL,
6 action VARCHAR(50) DEFAULT NULL
7 );

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:

Database Systems Lab Manual – Page 133 | 171


LAB 23. Triggers

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:

1 SELECT * FROM employees_audit;

The following output is produced by this query:

Another Example:
Now to understand trigger, create a new table named: PriceUpdates_T.

1 use pineview;
2 create table PriceUpdates_T

Database Systems Lab Manual – Page 134 | 171


LAB 23. Triggers

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

3 CREATE TRIGGER StandardPriceUpdate


4 AFTER UPDATE ON Product_T
5 FOR EACH ROW
6 INSERT INTO PriceUpdates_T VALUES (NEW.ProductID,
,→ NEW.ProductDescription, curdate(), NEW.ProductStandardPrice);

To see our newly created trigger use following command

1 show triggers;

Now the following command will automatically execute (trigger) the trigger
StandardPriceUpdate.

1 update product_t set productstandardprice=210 where productid=3;

After the above command is run, check the data in PriceUpdates_T table.

1 SELECT * FROM priceupdates_t;

You will see a new row is inserted in the PriceUpdates_T table.


Explanation:
The trigger code StandardPriceUpdate states that whenever there is an update in
Product_T table, the updated row(s) fields will be automatically inserted into the
PriceUpdates_T as new rows. That’s why we are seeing new row inserted into PriceUpdates_T
table. FOR EACH ROW means that, the new row in PriceUpdates_T will be inserted for
each updated row, e.g., the following query updates two rows in the product_t table.

1 update product_t set ProductStandardPrice=333


2 where productid in (5,6);

Example:

Database Systems Lab Manual – Page 135 | 171


LAB 23. Triggers

Create the table for which the trigger will be set:

1 CREATE TABLE people (age INT, name varchar(150));

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 ;

Now insert two records to check the trigger functionality.

1 INSERT INTO people VALUES (-20, ’Sid’), (30, ’Josh’);

At the end check the result.

1 SELECT * FROM people;

If you are using MySQL command shell, the following output will be shown.
+——---+——----+
| age | name |
+—--—-+—---—-+
| 0 | Sid |
| 30 | Josh |
+—--—-+——----+

23.7 Lab task and home work

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

Database Systems Lab Manual – Page 136 | 171


LAB 23. Triggers

store the user name of the user who corrects the results.

Database Systems Lab Manual – Page 137 | 171


LAB 24

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

• Creating indexes on primary and secondary keys


• Creating indexes on foreign keys

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.

24.4 Creating Index

The CREATE INDEX command is used to create an index on a table.

138
LAB 24. Indexing

Syntax:

1 CREATE INDEX index_name


2 ON table_name (column_name)

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.

1 CREATE UNIQUE INDEX index_name


2 ON table_name (column_name)

Example:
In the following SQL statement an index is created on a new table.

1 CREATE TABLE employee_records (


2 name VARCHAR(50),
3 employeeID INT, INDEX (employeeID)
4 )

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:

1 CREATE INDEX anyIndex


2 ON city (Name);

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.

The following command creates an index

Database Systems Lab Manual – Page 139 | 171


LAB 24. Indexing

1 CREATE INDEX Name_IDX ON CUSTOMER_T (CUSTOMERNAME) ;

To see the structure of a table we use the DESCRIBE command

1 DESCRIBE CUSTOMER_T;

A key is created on the CustomerName table.

24.5 Showing Indexes

You can use SHOW INDEX command to list out all the indexes associated with a table.
Syntax:

1 SHOW INDEX FROM table_name

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:

24.6 Removing Indexes

DROP INDEX is used to remove index on the customer name in the table.
Example:

Database Systems Lab Manual – Page 140 | 171


LAB 24. Indexing

1 DROP INDEX Name_IDX ON CUSTOMER_T;

24.7 Creating index on foreign keys

Indexes can also be create on foreign keys as illustrated in the following example.
Example:
Step1: Create two tables:

1 CREATE TABLE MASTER(


2 MID VARCHAR(5) PRIMARY KEY,
3 TYPE VARCHAR(10)
4 );
5

6 CREATE TABLE DETAIL(


7 DIDT VARCHAR(5) PRIMARY KEY,
8 DES VARCHAR(50),
9 MID VARCHAR(5)
10 );

Step2: Add foreign key:

1 ALTER TABLE DETAIL ADD FOREIGN KEY (MID) REFERENCES MASTER(MID);

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.

24.8 Removing foreign key indexes

When we drop a foreigh key the index still remains intact.

1 ALTER TABLE DETAIL DROP FOREIGN KEY your_fk_name;

Even after dropping the foreign key, the index still resides and has to be dropped
manually, by

1 DROP INDEX MID ON DETAIL;

Note: When we drop a foreign key, the index does not automatically delete, and we

Database Systems Lab Manual – Page 141 | 171


LAB 24. Indexing

have to delete the index manually.

24.9 Lab Task

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.

Database Systems Lab Manual – Page 142 | 171


LAB 25

TRANSACTION MANAGEMENT

25.1 Objectives

To introduce transaction management in databases.

25.2 Scope

• Using COMMIT and ROLLBACK.


• AUTOCOMMIT.
• Transaction savepoints.

25.3 Introduction

A transaction is a sequential group of database manipulation operations, which is


performed as if it were one single work unit.
A transaction will never be complete unless each individual operation within the group
is successful.
If any operation within the transaction fails, the entire transaction will fail.

25.4 Properties of Transactions

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:

1 UPDATE account SET balance = balance - 100 WHERE name = ’Bill’;


2 UPDATE account SET balance = balance + 100 WHERE name = ’Bob’;

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.

25.5 Transactions and storage engines

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.

25.6 COMMIT and ROLLBACK

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.

Database Systems Lab Manual – Page 144 | 171


LAB 25. Transaction Management

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.

25.8 Performing transactions

One way to perform a transaction is to issue a START TRANSACTION (or BEGIN)


statement to suspend autocommit mode, execute the statements that make up the
transaction, and end the transaction with a COMMIT statement to make the changes
permanent. If an error occurs during the transaction, cancel it by issuing a ROLL-
BACK statement instead to undo the changes.
START TRANSACTION suspends the current autocommit mode, so after the trans-
action has been committed or rolled back, the mode reverts to its state prior to the
START TRANSACTION. (If autocommit was enabled beforehand, ending the transac-
tion puts you back in autocommit mode. If it was disabled, ending the current trans-
action causes you to begin the next one.)
Example:
First, create a table to use:

1 CREATE TABLE t (name CHAR(20),


2 UNIQUE (name))
3 ENGINE = InnoDB;

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;

Database Systems Lab Manual – Page 145 | 171


LAB 25. Transaction Management

+---------+
| 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;

Database Systems Lab Manual – Page 146 | 171


LAB 25. Transaction Management

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:

1 INSERT INTO t SET name = ’Gromit’;


2 INSERT INTO t SET name = ’Wallace’;

MySQL will show the following error: ERROR 1062 (23000): Duplicate entry ’Wallace’
for key 1

1 ROLLBACK;
2 SELECT * FROM t;

+---------+

Database Systems Lab Manual – Page 147 | 171


LAB 25. Transaction Management

| 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:

1 SELECT * FROM score WHERE event_id = 5 AND student_id IN (8,9);

+------------+----------+-------+

Database Systems Lab Manual – Page 148 | 171


LAB 25. Transaction Management

| student_id | event_id | score |


+------------+----------+-------+
| 8 | 5 | 18 |
| 9 | 5 | 13 |
+------------+----------+-------+

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:

1 UPDATE score SET score = 13 WHERE event_id = 5 AND student_id = 8;


2 UPDATE score SET score = 18 WHERE event_id = 5 AND student_id = 9;

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:

1 SELECT * FROM score WHERE event_id = 5 AND student_id IN (8,9);

+------------+----------+-------+
| student_id | event_id | score |
+------------+----------+-------+
| 8 | 5 | 13 |
| 9 | 5 | 18 |
+------------+----------+-------+

Database Systems Lab Manual – Page 149 | 171


LAB 25. Transaction Management

25.9 Transaction Savepoints

MySQL enables you to perform a partial rollback of a transaction.To do this, issue a


SAVEPOINT statement within the transaction to set a marker. To roll back to just that
point in the transaction later, use a ROLLBACK statement that names the savepoint.
The following statements illustrate how this works:

1 CREATE TABLE t (i INT) ENGINE = InnoDB;


2 START TRANSACTION;
3 INSERT INTO t VALUES(1);
4 SAVEPOINT my_savepoint;
5 INSERT INTO t VALUES(2);
6 ROLLBACK TO SAVEPOINT my_savepoint;
7 INSERT INTO t VALUES(3);
8 COMMIT;
9 SELECT * FROM t;

+------+
| 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.

25.10 Lab Tasks

• Perform all the above examples.

Database Systems Lab Manual – Page 150 | 171


LAB 26

LOCKS

26.1 Objectives

To introduce the concepts of locks and sessions

26.2 Scope

• Locking tables for read.


• Locking tables for write.
• Unlocking tables.

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.

26.4 Locking and Unlocking tables

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

1 CREATE DATABASE sampledb;


2

3 CREATE TABLE tbl (


4 id int(11) NOT NULL AUTO_INCREMENT,
5 col int(11) NOT NULL,
6 PRIMARY KEY (id)
7 );

Syntax
The simple form of acquiring a lock for a table is as follows:

1 LOCK TABLES table_name [READ | WRITE]

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;

26.5 Table locking for READ

A READ lock for a table has the following features:


• A READ lock for a table can be acquired by multiple sessions at the same time.
In addition, other sessions can read data from the table without acquiring the
lock.
• The session that holds the READ lock can only read data from the table, but
not write. In addition, other sessions cannot write data into the table until the
READ lock is released. The write operations from another session will be put
into the waiting states until the READ lock is released.
• If the session is terminated normally or abnormally, MySQL will release all the
locks implicitly. This is also relevant for the WRITE lock.
Example: Let’s take a look at how the READ lock works in the following scenario.
Step 1: connect to the sampledb database. To find out the current connection id, you
use the CONNECTION_ID() function as follows:

1 SELECT CONNECTION_ID();

Database Systems Lab Manual – Page 152 | 171


LAB 26. Locks

Step 2: Insert a new row into the tbl table.

1 SELECT CONNECTION_ID();
2 INSERT INTO tbl(col) VALUES(10);

Next, retrieve all rows from the same table.

1 SELECT CONNECTION_ID();
2 SELECT * FROM tbl;

After that, to acquire a lock, you use the LOCK TABLE statement.

1 LOCK TABLE tbl READ;

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();

Then, retrieve data from the tbl .

1 SELECT * FROM tbl;

Database Systems Lab Manual – Page 153 | 171


LAB 26. Locks

Next, insert a new row into the tbl table from the second session.

1 INSERT INTO tbl(col) VALUES(20);

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.

1 SELECT * FROM tbl;

26.6 MySQL table locking for WRITE

The table lock for WRITE has the following features:


Only session that holds the lock of a table can read and write data from the table.
Other sessions cannot read and write from the table until the WRITE lock is released.
Example:
First, acquire a WRITE lock from the first session.

Database Systems Lab Manual – Page 154 | 171


LAB 26. Locks

1 LOCK TABLE tbl WRITE;

Then, insert a new row into the tbl table.

1 INSERT INTO tbl(col) VALUES(11);

Next, read data from the tbl table.

1 SELECT * FROM tbl;

After that, from the second session, try to write and read data:

1 INSERT INTO tbl(col) VALUES(21);


2 SELECT * FROM tbl;

MySQL puts those operations into a waiting state. You can check it using the SHOW
PROCESSLIST statement.

1 SHOW PROCESSLIST;

Finally, release the lock from the first session.

1 UNLOCK TABLES;

You will see all pending operations from the second session executed.

Database Systems Lab Manual – Page 155 | 171


LAB 26. Locks

26.7 Lab Tasks

1. Perform the above examples.


2. Make groups of two students and access each others database through the LAN.
Lock and unlock various tables in the pineview database and verify the impact
on select and insert queries initiated from remote session.

Database Systems Lab Manual – Page 156 | 171


LAB 27

SPECIAL LAB TASK I

27.1 Objectives

Enabling student to consolidate the techniques learned in the previous labs

27.2 Case study

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

program but there are many students in every program.


Write code to create tables which are according to the ER design (given) and implement
additional requirements below.
1. Create three tables with name Department, Program, and Student. The detail
of tables attributes and foreign keys with additional constraints is given bellow:
(a) Department (deptId, dName, dLoc)
i. Set deptId as Primary key
ii. dName must not be null
iii. Add check constraint that location name must be one the cities Islam-
abad, Lahore, Peshawar, Karachi.
(b) Program (pId, pName )
• Set pId as primary key
• Add check constraint the each program must one of the following:
• BCS, BSE, BEE, BPE, BBA, MBA”
• Add deptId as additional column, and set this column as foreign key
which refers to department table’s deptId primary key.
(c) Student (stId, stName, stContact)
• Set stId as primary key
• Add deptId as additional column, and set this column as foreign key
which refers to department table’s deptId primary key.
• Add pId as additional column in student table, and set this column as
foreign key which refers to program table’s pId primary key.
• Set stContact column as unique constraint which ensures that every
contact must be unique against each student.
2. DML operations on the above tables:
(a) Populating data:
• Inset at least three rows in department table
• Insert at least two rows in program table against each department.
• Insert at least 5 student’s data against each department in student’s ta-
ble. In addition to that, every program must show at least one student
in every department.
(b) Updating data:
• Update location as Faisalabad of the computer science department.
• Update the program name as BTN in place of BCS.
3. Fetching/displaying data:
• Display student names of BCS and BSE program.

Database Systems Lab Manual – Page 158 | 171


LAB 27. Special Lab Task I

• Count the number of students in each program of electrical department.


• Display department name with location, program name, and student name
of those students whose program’s name’s last two letters are ‘SE’.

Database Systems Lab Manual – Page 159 | 171


LAB 28

SPECIAL LAB TASK II

28.1 Objectives

Enabling student to consolidate the techniques learned in the previous labs

28.2 Case study

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)

Database Systems Lab Manual – Page 161 | 171


LAB 28. Special Lab Task II

• Set authorId as primary key


• Author name must not null
(f) Book_Author (bookAid, authorBid)
• Set bookAid as foeign key which has been added as a column.
• Set authorBid as foeign key which has been added as a column.
• Set both columns bookAid and authorBid as composite primary key in
this table.
2. DML operations on the above tables:
(a) Populating data:
• Inset at least three rows in employee table
• Set at least three employees as supervisor of other employees.
(b) Insert at least three rows with different store name in store table.
• Insert locations in five different locations/cities against each store name
in the location table.
• Insert at least 10 rows about different books data in the book table.
• Insert author details in the author table.
• Insert foreign key values in the Book_Author table shows the links of
authors with books.
(c) Updating data:
• Update location of store as “Lahore” in place of Islamabad.
• Update publisher as”ABC” in place “XYZ” of Software Engineering book.
(d) Fetching/displaying data:
• Display list of employees whose location is Islamabad and lahroe.
• Count the number of books of C++ and Software engineering.
• Display book titles with author names in the store located at Lahore
city.
• Display employee names under the supervision of those employees whose
salary is between $4000 and $5000.

Database Systems Lab Manual – Page 162 | 171


LAB 29

SPECIAL LAB TASK III

29.1 Objectives

Enabling student to consolidate the techniques learned in the previous labs

29.2 Case study

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

3. Creating Views for security and generating reports


4. Creating Triggers
5. Fetching/displaying data
1. Creating tables and constraints with additional requirements: According to the
scenario, three tables have to be created that are, employee, department, project.
Two additional tables with name Dept_Project and Emp_Project as bridge tables
will be created because of many-to-many relationship. One more table with name
DeptLocation will be created to hold multiple locations of departments at differ-
ent countries. The detail of table with attributes, and primary key and foreign
keys with additional constraints is given bellow:
(a) Employee (empId, name, jobType, specialization, hireDate, startConract-
Date, expireContractDate, salary, gender, birthdate, totalAge, address, deptNo)
• Set empId as Primary key
• Set deptNo as foeign key which has been added as an additional column
in this table which refers department table’s deptNumber which is the
primary key.
• jobType and specialization must not be null
• Add check constraint that the salary must be between 1200and 10000
• Gender must be ‘Male’ or ‘Fmale’
• Total age will be calculated from birthdate of the employee because
totalAge is the derived attribute.
(b) Department (deptNumber, deptName, deptLocation, deptMgrId):
• Set deptNumber as Primary key
• deptName must not be null.
• Set deptMgrId as foeign key which has been added as an additional
column in this table which refers employee table’s empId which is the
primary key.
(c) DeptLocation (location, deptNo)
• Set deptNo as foeign key which has been added as an additional column
in this table which is an additional table because location attribute was
multivalued attribute in the department entity type. This foreign key
refers to the deptNumber of department table.
• Set both attributes location and deptNo as composite primary key.
(d) Project (projectNo, projectName, projectType, totalDuration, totalBudget )
i. Set projectId as primary key
ii. Project name must not be null
(e) Dept_Project (deptNo, projNo)
• Set deptNo as foeign key which has been added as an additional column

Database Systems Lab Manual – Page 164 | 171


LAB 29. Special Lab Task III

and refers to deptNumber of department table.


• Set projNo as foeign key which has been added as an additional column
and refers to projectNo of project table.
• Set both columns deptNo and projNo as composite primary key in this
table.
(f) Emp_Project (empId, projectNo)
• Set empId as foeign key which has been added as an additional column
and refers to empId of employee table.
• Set projNo as foeign key which has been added as an additional column
and refers to projectNo of project table.
• Set both columns empId and projNo as composite primary key in this
table.
2. DML operations on the above tables:
(a) Populating data:
• Inset at least three rows against all column values in employee table
• Insert at least three rows with different department name in depart-
ment table.
• Insert locations in five different locations/cities against each depart-
ment name in the location table.
• Insert at least 5 rows about five different projects offered by at least
three departments. These five projects also show at least three differ-
ent employees working on different projects. To do so, foreign key val-
ues will be populated in both bridge tables Dept_Project and Emp_Project.
(b) Updating data:
• Update expiring date of those employees whose hiredate is between
2010 and 2011.
• Update location of admin department from Pakistan to Dubai.
• Delete all employees details whose expiring date is 2016.
3. Creating Views:
(a) For Security:
• Create view “ProjectEmployeeView” where users can see employee names,
job type, hire date, age, address, project name and duration of the
project.
• Create view “DeptProjectMgrView” where users can find the data of
manager, the department names, the project names, project type and
total budget of the project.
(b) For Generating Reports:
• Create view “EmpDept” where users can generate report to see details

Database Systems Lab Manual – Page 165 | 171


LAB 29. Special Lab Task III

of all employees with their name, specialization, contract start, con-


tract expiry date, and department detail like department name with
its location.
4. Creating Triggers:
(a) Creating an AFTER DELETE trigger:
• Create table User_Audit with attributes ‘username’,’empId’,’jobType’,’salary’,’birth
’userName’ to store the data generated by the trigger.
• Create an AFTER DELETE trigger on EMPLOYEE table to insert the
user name who applies delete operation on the Employee table against
each row. This trigger will insert the values like empId, jobType, salary,
birthdate including user name who will delete the data against columns
mentioned above into User_Audit table.
(b) Creating BEFORE UPDATE trigger on Project table:
• Create table User_Audit_project with columns: username, updation-
Date, totalDuration, totalBudget,
• Create a BEFORE UPDATE trigger on Project table to insert user
name who wants to update total duration or total budget or both of
above of any project. This trigger will also insert the values which are
being updated by the user as well as the date of updating.
5. Fetching/displaying data:
• Display list of employees whose location is New York and whose hire date
is between 2009 and 2012 and who are civil engineers.
• Count the number of employees working in each project. Also display the
project names.
• Display employee names, with contract expire date, project names, and
the department names which have offered those projects, and the location
where the departments exist.
• Display department names and the names of managers who are managing
the departments.

Database Systems Lab Manual – Page 166 | 171


LAB 30

CREATING ERD

30.1 Objective

Creating ERD and converting it in to database schema.

30.2 Scope

• Using MySQL workbench to creat ERD Model


• Creating database from ERD Model

30.3 Creating a New Model

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

Database Systems Lab Manual – Page 168 | 171


LAB 30. Creating ERD

process of adding columns to the table:

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.

30.4 Generating a Model Diagram

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:

Database Systems Lab Manual – Page 169 | 171


LAB 30. Creating ERD

Though we aren’t creating any relationships in this example, it is important to note


the vertical array of buttons to the left of the diagram that allow such relationships to
be created within the diagram tool.
Return to the model by selecting the Model tab beneath the workbench toolbar.

30.5 Generating a Script and Creating a Database

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:

Database Systems Lab Manual – Page 170 | 171


LAB 30. Creating ERD

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.

30.6 Lab Task

Create the ERD following the above procedure for Special Lab Task I (page 157).

Database Systems Lab Manual – Page 171 | 171

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy