0% found this document useful (0 votes)
16 views256 pages

E Textbook

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)
16 views256 pages

E Textbook

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/ 256

Project 609854‐EPP‐1‐2019‐1‐FR‐EPPKA2‐CBHE‐JP ‐ ASEAN FACTORI 4.

0:
From Automation and Control Training to the Overall Roll‐out of Industry 4.0 across South East Asian Nations

Database Basics and


operations with MySQL

University of Health Sciences (UHS)


&
University of Ruse “Angel Kanchev” (UR)

2023
Project 609854‐EPP‐1‐2019‐1‐FR‐EPPKA2‐CBHE‐JP ‐ ASEAN FACTORI 4.0:
From Automation and Control Training to the Overall Roll‐out of Industry 4.0 across South East Asian Nations

BACKGROUND
The e‐textbook titled “Database Basics and operations with MySQL” is intended for students registered in
the University of Health Sciences (UHS) in Vientiane, Laos.
The purpose of this e‐textbook is to present to the students the basic concepts of the modern databases
and the most basic characteristics and operations of the Structured Query Language – SQL.

OBJECTIVES
The objectives are as follows:

‐ To present the concepts of data management and the basic the modern databases
‐ To introduce the students to the different data types and the data definition concepts
‐ To present the basic SQL operations and queries
‐ To introduce the students to MySQL Server and its characteristics
‐ To show to the students the basic steps for database design and the related rules

PROFILE OF THE INSTRUCTORS


Detailed agenda and instructor’s profile are shown below.

Name Affiliation
Mr. Lattanavong Thammabavong University of Health Sciences, Vientiane, Laos
Mr. Seksith Vangkonevilay University of Health Sciences, Vientiane, Laos
Ms. Noy Lovanhuk University of Health Sciences, Vientiane, Laos
Assoc. Prof. Dr. Nina Bencheva University of Ruse “Angle Kanchev”, Ruse, Bulgaria
Prof. Dr. Georgi Hristov University of Ruse “Angle Kanchev”, Ruse, Bulgaria
Assoc. Prof. Dr. Plamen Zahariev University of Ruse “Angle Kanchev”, Ruse, Bulgaria

This E‐textbook is a part of the ASEAN FACTORI 4.0 project, supported by ERASMUS+ Program of the European Union.

ASEAN FACTORI 4.0: From Automation and Control Training to the Overall Roll‐out of Industry 4.0 across South East Asian
Nations, reference number: 609854‐EPP‐1‐2019‐1‐FR‐EPPKA2‐CBHE‐JP.

Disclaimer: This publication reflects the views only of the authors, and the Commission cannot be held responsible for any use
which may be made of the information contained therein.
Project 609854‐EPP‐1‐2019‐1‐FR‐EPPKA2‐CBHE‐JP ‐ ASEAN FACTORI 4.0:
From Automation and Control Training to the Overall Roll‐out of Industry 4.0 across South East Asian Nations

TABLE OT CONTENTS

Chapter 1. Introduction to Databases

1.1. Data Management. When Do We Need a Database?


1.2. Database Engines.
1.3. The Structured Query Language.
1.4. MySQL. Relational DB Management.
1.5. Table Relationships. Splitting data in tables.
1.6. Programmability. Customizing Database Behavior.
1.7. Summary

Chapter 2. Data Definition and Data Types

2.1. Data Types in MySQL Server. Numeric, String and Data Types.
2.2. Database Modeling. Data Definition using GUI Clients.
2.3. Basic SQL Queries. Data Definition using SQL.
2.4. Table Customization. Adding Rules, Constraints and Relationships.
2.5. Altering Tables. Changing Table Properties After Creation.
2.6. Deleting Data and Structures. Dropping and Truncating.
2.7. Summary

Chapter 3. Create, Retrieve, Update, Delete (CRUD) using SQL queries

3.1. Query Basics. SQL Introduction.


3.2. Retrieving Data. Using SQL SELECT.
3.3. Writing Data in Tables. Using SQL INSERT.
3.4. Modifying Existing Records. Using SQL UPDATE and DELETE.
3.5. Summary

Chapter 4. Functions and Wildcards in MySQL Server

4.1. Functions in MySQL Server


4.2. String Functions
4.3. Arithmetical Operators and Numeric Functions
4.4. Date Functions
4.5. Wildcards. Selecting results by partial match.
4.6. Summary
Chapter 5. Data Aggregation ‐ How to get data insights?

5.1. Grouping. Consolidating data based on criteria.


5.2. Aggregate Functions. COUNT, SUM, MAX, MIN, AVG…
5.3. Having. Using predicates while grouping.
5.4. Summary

Chapter 6. Table Relations ‐ Database Design and Rules

6.1. Database Design. Fundamental Concepts.


6.2. Table Relations. Relational Database Model in Action.
6.3. Retrieving Related Data. Using Simple JOIN statements.
6.4. Cascade Operations. Cascade Delete/Update.
6.5. Entity / Relationship Diagrams
6.6. Summary

Chapter 7. Joins, Subqueries and Indices ‐ Data Retrieval and Performance

7.1. Joins. Gathering Data From Multiple Tables.


7.2. Subqueries. Query Manipulation on Multiple Levels.
7.3. Indices. Clustered and Non‐Clustered Indices.
7.4. Summary

Chapter 8. Functions and Triggers – User‐defined Functions, Procedures, Triggers and Transactions

8.1. User‐Defined Functions. Encapsulating custom logic.


8.2. Stored Procedures. Sets of queries stored on DB Server.
8.3. What is a Transaction? Executing operations as a whole.
8.4. Triggers. Maintaining the integrity of the data.
8.5. Summary
Chapter 1.
Introduction to Databases

Database Basics and operations with MySQL


Data Management
When Do We Need a Database?

Database Basics and operations with MySQL


Storage vs. Management
SALES RECEIPT 00315 – 07/16/2016
Date: 07/16/2016 David Rivers
Order#:[00315] Oil Pump (OP147-0623)
1 x 69.90
Customer: David Rivers
Product: Oil Pump
S/N: OP147-0623

Unit Price: 69.90


Qty: 1

Total: 69.90

Database Basics and operations with MySQL


Storage vs. Management

Order# Date Customer Product S/N Qty


00315 07/16/2016 David Rivers Oil Pump OP147-063 1

Database Basics and operations with MySQL


Storage vs. Management
• Storing data is not the primary reason to use a database
• Flat storage eventually runs into issues with

• Size
• Ease of updating
• Accuracy
• Security
• Redundancy
• Importance

Database Basics and operations with MySQL


Databases
• A database is an organized collection of related information

• It imposes rules on the contained data


• Access to data is usually provided by a "system" (DBMS) database
management
• Relational storage first proposed by Edgar Codd in 1970

Database Basics and operations with MySQL


RDBMS
• Relational Data Base Management System
• Database management

• It parses requests from the user and takes the appropriate action

• The user doesn't have direct access to the stored data

• Data is presented by relations – collection of tables related by common fields

• MS SQL Server, DB2, Oracle and MySQL

Database Basics and operations with MySQL


Client-Server Model

Database Engines
Database Basics and operations with MySQL
Database Engine Flow
• SQL Server uses the Client-Server Model

Clients Query Engine Access Database

Data Data

Database Basics and operations with MySQL


Client-Server Model
CLIENTS

TCP/IP

DATABASE

Database Basics and operations with MySQL


Top Database Engines

Source: http://db-engines.com/en/ranking

Database Basics and operations with MySQL


The Structured Query Language
Query Components
Database Basics and operations with MySQL
Structured Query Language
• Programming language designed for managing data in a relational
database

• Developed at IBM in the early 1970s

• To communicate with the Engine we use SQL

Database Basics and operations with MySQL


Structured Query Language
• Subdivided into several language elements

• Queries
Update clause Expression
• Clauses
UPDATE employees
• Expressions
SET salary = salary * 0.1
Statement WHERE job_title = "Cashier";
• Predicates
Predicate
• Statements

Database Basics and operations with MySQL


Structured Query Language
• Logically divided in four sections

• Data Definition – describe the structure of our data

• Data Manipulation – store and retrieve data

• Data Control – define who can access the data

• Transaction Control – bundle operations and allow rollback

Database Basics and operations with MySQL


Structured Query Language
SQL
DDL DML DCL TCL
CREATE SELECT GRANT BEGIN TRAN
ALTER INSERT REVOKE COMMIT
DROP UPDATE DENY ROLLBACK
TRUNCATE DELETE SAVE
Database Basics and operations with MySQL
MySQL
Relational DB Management

Database Basics and operations with MySQL


MySQL
• Open-source relational database management system
• Used in many large-scale websites like including Google, Facebook, YouTube
etc.
• Works on many system platforms –
MAC OS, Windows, Linux
• Download MySQL Server

• Windows: dev.mysql.com/downloads/windows/installer/

• Ubuntu/Debian: dev.mysql.com/downloads/repo/apt/

Database Basics and operations with MySQL


MySQL Server Architecture
Instance
• Logical Storage Database(Schema) Database(Schema)

• Instance
• Database/Schema Table Table
• Table Database(Schema)
Table Table

• Physical Storage
• Data files and Log files
• Data pages Data Logs

☰ ☰ ☰ ☰ ☰ ☰ ☰ ☰

Database Basics and operations with MySQL


Database Table Elements
• The table is the main building block of any database Column
customer_id first_name birthdate city_id
1 Brigitte 03/12/1975 101

2 August 27/05/1968 102

3 Benjamin 15/10/1988 103

Row 4 Denis 07/01/1993 104

Cell
• Each row is called a record or entity
• Columns (fields) define the type of data they contain

Database Basics and operations with MySQL


Table Relationships
Splitting data in tables

Database Basics and operations with MySQL


Why Split Related Data?
Empty records
first last registered email email2
David Rivers 05/02/2016 [email protected] [email protected]

Sarah Thorne 07/17/2016 [email protected] NULL

Michael Walters 11/23/2015 [email protected] NULL


Redundant information

order_id date customer product s/n price


00315 07/16/2016 David Rivers Oil Pump OP147-0623 69.90

00315 07/16/2016 David Rivers Accessory Belt AB544-1648 149.99

00316 07/17/2016 Sarah Thorne Wiper Fluid WF000-0001 99.90

00317 07/18/2016 Michael Walters Oil Pump OP147-0623 69.90

Database Basics and operations with MySQL


Related Tables
• We split the data and introduce relationships between the tables to avoid
repeating information

user_id first last registered user_id email


203 David Rivers 05/02/2016 203 [email protected]

204 Sarah Thorne 07/17/2016 204 [email protected]

205 Michael Walters 11/23/2015 205 [email protected]

203 [email protected]
Primary Key Foreign Key

• Connection via Foreign Key in one table pointing to the Primary Key in another

Database Basics and operations with MySQL


Entity Relationship (E/R) Diagrams

Database Basics and operations with MySQL


Begin

Programmability
Customizing Database Behavior
Database Basics and operations with MySQL
Indices
• Indices make data lookup faster
• Clustered – bound to the primary key, physically sorts data
• Non-Clustered – can be any field, references the primary index
• Structured as an ordered tree

PK Index

0-99 100-199 200-299 Range 1 Range 2 Range 3

Data ☰ ☰ ☰ ☰ ☰ ☰ ☰ Links ☰ ☰ ☰ ☰ ☰ ☰ ☰

Database Basics and operations with MySQL


Views
• Views are prepared queries for displaying sections of our data
CREATE VIEW v_employee_names AS
SELECT e.employee_id,
e.first_name,
e.last_name
FROM uni_ruse.employees AS e

SELECT * FROM v_employee_names

• Evaluated at run time – they do not increase performance

Database Basics and operations with MySQL


Procedures, Functions and Triggers
• A database can further be customized with reusable code

• Procedures – carry out a predetermined action


• E.g. get all employees with salary above 35000

• Functions – receive parameters and return a result


• E.g. get the age of a person using their birthdate and current date

• Triggers – watch for activity in the database and react to it


• E.g. when a record is deleted, write it to an archive

Database Basics and operations with MySQL


Procedures
CREATE PROCEDURE udp_get_employees_salary_above_35000()
BEGIN
SELECT first_name, last_name FROM employees
WHERE salary > 35000;
END

CALL udp_get_employees_salary_above_35000

Database Basics and operations with MySQL


Functions
CREATE FUNCTION udf_get_age (dateValue DATE)
RETURNS INT
BEGIN
DECLARE result INT;
SET result = TIMESTAMPDIFF(YEAR, dateValue, NOW());
RETURN result;
END

SELECT udf_get_age('1988-12-21');

Database Basics and operations with MySQL


Summary
• RDBMS stores and manages data

• We communicate with the DB engine via SQL

• MySQL is a multiplatform RDBMS using SQL

• Table relations reduce repetition and complexity

• Databases can be customized with functions and procedures


Database Basics and operations with MySQL
Chapter 2.
Data Definition and Data Types

Database Basics and operations with MySQL


Data Types in MySQL Server
Numeric, String and Data Types
Database Basics and operations with MySQL
Numeric Data Types
• Numeric data types have certain range
• Their range can be changed if they are:
• Signed - represent numbers both in the positive and negative ranges
• Unsigned - represent numbers only in the positive range
• E.g. signed and unsigned INT:
Signed Range Unsigned Range
Min Value Max Value Min Value Max Value
-2147483648 2147483648 0 4294967295

Database Basics and operations with MySQL


Numeric Data Types
• INT [(M)] [UNSIGNED]
• TINYINT, SMALLINT, MEDIUMINT, BIGINT
• DOUBLE [(M, D)] [UNSIGNED]
Decimals after
Digits stored for value
floating point
• E.g. DOUBLE[5, 2] – 999.99
• DECIMAL [(M, D )] [UNSIGNED] [ZEROFILL]

Database Basics and operations with MySQL


String Types
• String column definitions include attributes that specify the
character set or collation
Determines the storage
• CHARACTER SET (Encoding)
of each character (single
• E.g. utf8, ucs2 or multiple bytes)
• CHARACTER COLLATION – rules for encoding comparison
• E.g. latin1_general_cs, Traditional_Spanish_ci_ai etc.
Determines the sorting
order and case-sensitivity
• Set and collation can be defined at the database, table or column level

Database Basics and operations with MySQL


CHARACTER COLLATION - Example
• ORDER BY with different collations

latin1_swedish_ci latin1_german1_ci latin1_german2_ci

Muffler Muffler Müller


MX Systems Müller Muffler
Müller MX Systems MX Systems
MySQL MySQL MySQL

Database Basics and operations with MySQL


String Types
• CHAR [(M)] - up to 30 characters
• VARCHAR(M) – up to 255 characters
• TEXT [(M)] – up to 65 535 characters
• TINYTEXT, MEDIUMTEXT, LONGTEXT
• BLOB - Binary Large OBject [(M)] - 65 535 (216 − 1) characters
• TINYBLOB, MEDIUMBLOB, LONGBLOB

Column name Column Type


title VARCHAR(CHAR)
content TEXT(LONGTEXT)
picture BLOB(LONGBLOB)

Database Basics and operations with MySQL


Date Types
• DATE - for values with a date part but no time part
• TIME - for values with time but no date part
• DATETIME - values that contain both date and time parts
• TIMESTAMP - both date and time parts
Column name Column Type
DATETIME and
birthdate DATE
TIMESTAMP have
last_time_online TIMESTAMP
different time
start_at TIME
ranges
deleted_on DATETIME
Database Basics and operations with MySQL
Date Types
• MySQL retrieves values for a given date type in a standard output
format
• E.g. as a string in either 'YYYY-MM-DD' or 'YY-MM-DD'
Data Type Column Type
DATE '0000-00-00'
TIME '00:00:00'
DATETIME '0000-00-00 00:00:00'
TIMESTAMP '0000-00-00 00:00:00'
YEAR 0000

Database Basics and operations with MySQL


Database Modeling
Data Definition using GUI Clients
Database Basics and operations with MySQL
Working with IDEs

• We will manage databases with HeidiSQL

• Enables us:
• To create a new database
• To create objects in the database (tables, stored procedures, relationships and
others)
• To change the properties of objects
• To enter records into the tables

Database Basics and operations with MySQL


Creating a New Database
• Select the instance Create new -> Database from the context
menu

Database Basics and operations with MySQL


Creating Tables
• Right click on database Select Create new -> Table

Set up table name

Add new record

Database Basics and operations with MySQL


Creating Tables
• A Primary Key is used to uniquely identify and index records

• Click on row Create new index -> Primary from the context menu of
the desired row

Database Basics and operations with MySQL


Creating Tables
• Auto increment – on the "Default" field

Database Basics and operations with MySQL


Storing and Retrieving Data
• We can add, modify and read records with GUI Clients

• To insert or edit a record, click inside the cell

Database Basics and operations with MySQL


CREATE TABLE people
(
id INT NOT NULL,
email VARCHAR(50) NOT NULL,
first_name VARCHAR(50),
last_name VARCHAR(50)
);

Basic SQL Queries


Data Definition using SQL

Database Basics and operations with MySQL


SQL Queries
• We communicate with the database engine using SQL
• Queries provide greater control and flexibility
• To create a database using SQL:
Database name

CREATE DATABASE employees;

• SQL keywords are conventionally capitalized


Database Basics and operations with MySQL
Table Creation in SQL
Table name

CREATE TABLE people


( Custom properties
id INT NOT NULL,
email VARCHAR(50) NOT NULL,
first_name VARCHAR(50),
last_name VARCHAR(50)
);
Column name Data type
Database Basics and operations with MySQL
Retrieve Records in SQL
• Get all information from a table
Table name

SELECT * FROM employees;


• You can limit the columns and number of records

SELECT first_name, last_name FROM employees


LIMIT 5;
List of columns
Number of records
Database Basics and operations with MySQL
Table Customization
Adding Rules, Constraints and Relationships
Database Basics and operations with MySQL
Custom Column Properties
• Primary Key
id INT NOT NULL PRIMARY KEY
• Auto-Increment (Identity)
id INT AUTO_INCREMENT PRIMARY KEY
• Unique constraint – no repeating values in entire table
email VARCHAR(50) UNIQUE
• Default value – if not specified (otherwise set to NULL)
balance DECIMAL(10,2) DEFAULT 0
Database Basics and operations with MySQL
Altering Tables
Changing Table Properties After Creation
Database Basics and operations with MySQL
Altering Tables Using SQL
• A table can be changed using the keywords ALTER TABLE

ALTER TABLE employees;


Table name
• Add new column

ALTER TABLE employees


ADD salary DECIMAL;
Column name Data type
Database Basics and operations with MySQL
Altering Tables Using SQL
• Delete existing column
Column name
ALTER TABLE people
DROP COLUMN full_name;

• Modify data type of existing column


ALTER TABLE people
MODIFY COLUMN email VARCHAR(100);
Column name New data type
Database Basics and operations with MySQL
Altering Tables Using SQL
• Add primary key to existing column
Constraint name
ALTER TABLE people
ADD CONSTRAINT pk_id
PRIMARY KEY (id); Column name
(more than one for composite key)
• Add unique constraint
Constraint name
ALTER TABLE people
ADD CONSTRAINT uq_email
UNIQUE (email)
Columns name(s)
Database Basics and operations with MySQL
Altering Tables Using SQL
• Set default value

Default value
ALTER TABLE people
ALTER COLUMN balance SET DEFAULT 0;
Column name

Database Basics and operations with MySQL


Deleting Data and Structures
Dropping and Truncating
Database Basics and operations with MySQL
Deleting from Database

• Deleting structures is called dropping


• You can drop keys, constraints, tables and entire databases

• Deleting all data in a table is called truncating

• Both of these actions cannot be undone – use with caution!

Database Basics and operations with MySQL


Dropping and Truncating
• To delete all the entries in a table
TRUNCATE TABLE employees;
Table name
• To drop a table – delete data and structure

DROP TABLE employees;


Table name
• To drop entire database
Database name
DROP DATABASE uni_ruse;

Database Basics and operations with MySQL


Dropping and Truncating
• To remove a constraining rule from a column
• Primary keys, value constraints and unique fields
Table name
ALTER TABLE employess
DROP CONSTRAINT pk_id; Constraint name

• To remove DEFAULT value (if not specified, revert to NULL)

ALTER TABLE employess Table name


ALTER COLUMN clients
DROP DEFAULT; Columns name
Database Basics and operations with MySQL
Summary
• Table columns have a fixed type
• We can use GUI Clients to create and customize tables
• SQL provides greater control

CREATE TABLE people


(
id INT NOT NULL,
email VARCHAR(50) NOT NULL,
first_name VARCHAR(50),
last_name VARCHAR(50)
);

Database Basics and operations with MySQL


Chapter 3.
Create, Retrieve, Update, Delete
(CRUD) using SQL queries

Database Basics and operations with MySQL


Query Basics
SQL Introduction
Database Basics and operations with MySQL
SQL Queries – Few Examples
• Select first, last name and job title about employees:
SELECT first_name, last_name, job_title FROM employees;
• Select projects which start on 01-06-2003:
SELECT * FROM projects WHERE start_date='2003-06-01';
• Inserting data into table:
INSERT INTO projects(name, start_date)
VALUES('Introduction to SQL Course', '2006-01-01');

Database Basics and operations with MySQL


SQL Queries – Few Examples
• Update end date of specific projects:
UPDATE projects
SET end_date = '2006-08-31'
WHERE start_date = '2006-01-01';

• Delete specific projects:

DELETE FROM projects


WHERE start_date = '2006-01-01';

Database Basics and operations with MySQL


Retrieving Data
Using SQL SELECT
Database Basics and operations with MySQL
Capabilities of SQL SELECT
Projection Selection
Take a subset of the columns Take a subset of the rows

Join
Combine tables by
some column
Table 1 Table 2
Database Basics and operations with MySQL
SELECT – Examples
• Selecting all columns from the "departments" table
SELECT * FROM departments;
department_id name manager_id
1
List of columns Engineering Table name 12
2 Tool design 4
(* for3all) Sales 273
… … …

• Selecting specific columns department_id name


1 Engineering
SELECT department_id, name 2 Tool design
FROM departments 3 Sales
… …
Database Basics and operations with MySQL
Column Aliases
• Aliases rename a table or a column heading
SELECT employee_id AS id, first_name, last_name
FROM employees;

id Display name
first_name last_name
1 Guy Gilbert
2 Kevin Brown
… … …

• You can shorten fields or clarify abbreviations


SELECT c.duration,
c.acg AS 'Access Control Gateway'
FROM calls AS c;

Database Basics and operations with MySQL


Concatenation
• You can concatenate column names or strings using the concat()
function
• String literals are enclosed in ['](single quotes)
• Table and column names containing special symbols use [`] (backtick)

SELECT concat(`first_name`,' ',`last_name`) AS 'full_name',


`job_title` as 'Job Title',
`id` AS 'No.'
FROM `employees`;

Database Basics and operations with MySQL


Problem: Employee Summary
• Find information about all employees, listing their:
• Full Name
• Job title
• Salary

• Use concatenation to display first and last names as one field

• Note: Query Hospital database

Database Basics and operations with MySQL


Employee Summary - Solution
Concatenation

SELECT concat(`first_name`,' ',`last_name`) AS


'full_name',
`job_title` as 'job_title',
Column alias
`salary` AS `salary`
FROM `employees` WHERE salary >= 1000;

Database Basics and operations with MySQL


Filtering the Selected Rows
• Use DISTINCT to eliminate duplicate results
SELECT DISTINCT `department_id`
FROM `employees`;
• You can filter rows by specific conditions using the WHERE clause
SELECT `last_name`, `department_id`
FROM `employees`
WHERE `department_id` = 1;
• Other logical operators can be used for greater control
SELECT `last_name`, `salary`
FROM `employees`
WHERE `salary` <= 20000;
Database Basics and operations with MySQL
Other Comparison Conditions
• Conditions ca be combined using NOT, OR, AND and brackets
SELECT `last_name` FROM `employees`
WHERE NOT (`manager_id` = 3 OR `manager_id` = 4);

• Using BETWEEN operator to specify a range:


SELECT `last_name`, `salary`FROM `employees`
WHERE `salary` BETWEEN 20000 AND 22000;

• Using IN / NOT IN to specify a set of values:


SELECT `first_name`, `last_name`, `manager_id`
FROM `employees`
WHERE `manager_id` IN (109, 3, 16);

Database Basics and operations with MySQL


Comparing with NULL
• NULL is a special value that means missing value
• Not the same as 0 or a blank space
• Checking for NULL values
SELECT `last_name`, `manager_id`
FROM `employees`
WHERE `manager_id` = NULL; This is always false!
SELECT `last_name`, `manager_id`
FROM `employees`
WHERE `manager_id` IS NULL;

SELECT `last_name`, `manager_id`


FROM `employees`
WHERE `manager_id` IS NOT NULL;

Database Basics and operations with MySQL


Sorting with ORDER BY
• Sort rows with the ORDER BY clause
• ASC: ascending order, default LastName HireDate
• DESC: descending order ASC is the default
Gilbert 1998-07-31
sorting order
Brown 1999-02-26
SELECT `last_name`, `hire_date` Tamburello 1999-12-12
FROM `employees` … …
ORDER BY `hire_date`;
LastName HireDate
Valdez 2005-07-01
SELECT `last_name`, `hire_date` Tsoflias 2005-07-01
FROM `employees` Abbas 2005-04-15
ORDER BY `hire_date` DESC; … …
Database Basics and operations with MySQL
Views
• Views are virtual tables made from others tables, views or joins
between them

• Usage:

• To simplify writing complex queries

• To limit access to data for certain users

Database Basics and operations with MySQL


Views
Table 1
Column 1 Column 2 Column 3

v_table1_table2
Column 1 Column 2 Column 3

Table 2
Column 1 Column 2 Column 3

Database Basics and operations with MySQL


Views - Example
• Get employee names and salaries, by department
CREATE VIEW `v_hr_result_set` AS
SELECT
CONCAT(`first_name`,' ',`last_name`) AS 'Full Name', `salary`
FROM `employees` ORDER BY `department_id`;

SELECT * FROM `v_hr_result_set`;

Database Basics and operations with MySQL


Problem: Top Paid Employee
• Create a view that selects all information about the top paid employee
• Name the view v_top_paid_employee

SELECT * FROM `v_top_paid_employee`;

• Note: Query Geography database

Database Basics and operations with MySQL


Solution: Top Paid Employee

CREATE VIEW `v_top_paid_employee`


AS
SELECT * FROM `employees`
ORDER BY `salary` DESC LIMIT 1;

Sorting column Greatest value first

Database Basics and operations with MySQL


Writing Data in Tables
Using SQL INSERT

Database Basics and operations with MySQL


Inserting Data Values for
• The SQL INSERT command all columns
INSERT INTO `towns` VALUES (33, 'Paris');

INSERT INTO projects(`name`, `start_date`) Specify


VALUES ('Reflective Jacket', NOW()) columns

• Bulk data can be recorded in a single query, separated by comma


INSERT INTO `employees_projects`
VALUES (229, 1),
(229, 2),
(229, 3), …
Database Basics and operations with MySQL
Inserting Data
• You can use existing records to create a new table
CREATE TABLE `customer_contacts`
New table name
AS SELECT `customer_id`, `first_name`, `email`, `phone`
FROM `customers`;

Existing source
• Or into an existing table List of columns

INSERT INTO projects(name, start_date)


SELECT CONCAT(name,' ', ' Restructuring'), NOW()
FROM departments;
Database Basics and operations with MySQL
Modifying Existing Records
Using SQL UPDATE and DELETE
Database Basics and operations with MySQL
Deleting Data
Condition
• Deleting specific rows from a table
DELETE FROM `employees`
WHERE `employee_id` = 1;

• Note: Don’t forget the WHERE clause!

• Delete all rows from a table (TRUNCATE works faster than DELETE)

TRUNCATE TABLE users;

Database Basics and operations with MySQL


Updating Data
• The SQL UPDATE command
New values
UPDATE `employees`
SET `last_name` = 'Brown'
WHERE `employee_id` = 1;

UPDATE `employees`
SET `salary` = `salary` * 1.10,
`job_title` = CONCAT('Senior',' ', `job_title`)
WHERE `department_id` = 3;
• Note: Don’t forget the WHERE clause!
Database Basics and operations with MySQL
Summary

• We can easy manipulate our database with SQL queries


SELECT *
FROM `projects`
WHERE `start_date` = '2006-01-01';

• Queries provide a flexible and powerful


method to manipulate records

Database Basics and operations with MySQL


Chapter 4.
Functions and Wildcards
in MySQL Server

Database Basics and operations with MySQL


Functions in MySQL Server
Database Basics and operations with MySQL
SQL Functions
• String Functions – for manipulating text, both from table values or
user input
• E.g. concatenate column values

• Math Functions – calculations and working with aggregate data


• E.g. perform geometry and currency operations

• Date and Time Functions


• E.g. find length of timespan

• Other

Database Basics and operations with MySQL


String Functions
Database Basics and operations with MySQL
String Functions
• SUBSTRING() – extracts part of a string

SUBSTRING(String, Position)

SUBSTRING(String, Position, Length)

SUBSTRING(String FROM Position FOR Length)

Database Basics and operations with MySQL


SUBSTRING - Example
• Get short summary of article

SELECT `article_id`, `author`, `content`,


SUBSTRING(`content`, 1, 200) AS 'Summary'
FROM `articles`;

Database Basics and operations with MySQL


Problem: Find Book Titles
• Write a query to find all book titles that start with "The"
• Query book_library database

Database Basics and operations with MySQL


Solution: Find Book Titles
SELECT title FROM books WHERE
SUBSTRING(title, 1, 3) = "The";

Database Basics and operations with MySQL


String Functions
• REPLACE – replaces specific string with another
• Performs a case-sensitive match

String to replace

REPLACE(String, Pattern, Replacement)

Field from table Replacement


pattern

Database Basics and operations with MySQL


REPLACE - Example
• Censor the word blood from album names

SELECT REPLACE(`title`, 'blood', '*****')


AS 'Title'
FROM `album`;

Database Basics and operations with MySQL


Problem: Replace Titles
• Write a query to find all book titles that start with "The" and replace
the substring with "***"
• Query book_library database

Database Basics and operations with MySQL


Solution: Replace Titles

UPDATE books
SET title = REPLACE(title,"The","***")
WHERE SUBSTRING(title, 1, 3) = "The";
SELECT title from books
WHERE SUBSTRING(title, 1, 3) = "***";

Database Basics and operations with MySQL


String Functions
• LTRIM & RTRIM – remove spaces from either side of string
LTRIM(String)
RTRIM(String)
• CHAR_LENGTH – count number of characters
CHAR_LENGTH(String)
• LENGHT – get number of used bytes (double for Unicode)

LENGTH(String)

Database Basics and operations with MySQL


String Functions
• LEFT & RIGHT – get characters from beginning or end of string

LEFT(String, Count)
RIGHT(String, Count)

• Example: name shorthand (first 3 letters)

SELECT `id`, `start`,


LEFT(`name`, 3) AS 'Shorthand'
FROM `games`;

Database Basics and operations with MySQL


String Functions
• LOWER & UPPER – change letter casing
LOWER(String)
UPPER(String)

• REVERSE – reverse order of all characters in string


REVERSE(String)
• REPEAT – repeat string
REPEAT(String, Count)

Database Basics and operations with MySQL


String Functions
• LOCATE – locate specific pattern (substring) in string
If omitted, begins at 1

LOCATE(Pattern, String,[Position])
• INSERT – insert substring at specific position
INSERT(String, Position, Length, Substring)

Number of characters
to delete
Database Basics and operations with MySQL
Arithmetical Operators and Numeric
Functions
Database Basics and operations with MySQL
Arithmetical Operators
• Supported common arithmetic operators
Name Description
DIV Integer division
/ Division operator
- Minus Operator
%, MOD Modulo operator
+ Addition operator
* Multiplication operator
- (arg) Change sign of argument

Database Basics and operations with MySQL


Numeric Functions
• Used primarily for numeric manipulation and/or mathematical calculations

• PI – get the value of Pi (15 –digit precision)


SELECT PI() +0.000000000000000

• ABS – absolute value

ABS(Value)

Database Basics and operations with MySQL


Numeric Functions
• SQRT – square root

SQRT(Value)

• POW – raise value to desired exponent

POW(Value, Exponent)

Database Basics and operations with MySQL


Math Functions
• CONV – Converts numbers between different number bases
CONV(Value,from_base,to_base)

• ROUND – obtain desired precision Can be negative


ROUND(Value, Precision)
• FLOOR & CEILING – return the nearest integer
FLOOR(Value)
CEILING(Value)

Database Basics and operations with MySQL


Math Functions
• SIGN – returns +1, -1 or 0, depending on value sign

SIGN(Value)

• RAND – get a random value in range [0,1]


• If Seed is not specified, one is assigned at random

RAND()
RAND(Seed)

Database Basics and operations with MySQL


Date Functions
Database Basics and operations with MySQL
Date Functions
• EXTRACT – extract a segment from a date as an integer

EXTRACT(Part FROM Date)

• Part can be any part and format of date or time

year, %Y, %y YEAR(Date)


month, %M, %m MONTH(Date)
day, %w, %D DAY(Date)
• For a full list, see the official documentation

Database Basics and operations with MySQL


Date Functions
• TIMESTAMPDIFF – find difference between two dates

TIMESTAMPDIFF(Part, FirstDate, SecondDate)

• Part can be any part and format of date or time

Database Basics and operations with MySQL


Date Functions - Example

• Show employee experience

SELECT `employee_id`, `first_name`, `last_name`,


TIMESTAMPDIFF(year, `hire_date`, '2017-05-31')
AS 'Years In Service'
FROM `employees`;

Database Basics and operations with MySQL


Problem: Days Lived
• Write a query to calculate how many days have authors lived
• Use TIMESTAMPDIFF
• Query book_library database

Database Basics and operations with MySQL


Days Lived - Solution
SELECT concat(first_name, ' ', last_name) as 'Full Name', TIMESTAMPDIFF(DAY,
born, died) as 'Days Lived'
FROM authors;

Database Basics and operations with MySQL


Date Functions
• DATE_FORMAT – formats the date value according to the format

SELECT DATE_FORMAT('2017/05/31', '%Y %b %D') AS 'Date';

• NOW – obtain current date and time

SELECT NOW();

Database Basics and operations with MySQL


Wildcards
Selecting results by partial match

Database Basics and operations with MySQL


Wildcards
• Used to substitute any other character(s) in a string
• '%' - represents zero, one, or multiple characters
• '_' - represents a single character
• Can be used in combinations

• Used with LIKE operator in a WHERE clause


• Similar to Regular Expressions

Database Basics and operations with MySQL


Wildcards - Examples
• Find any values that start with "a"
WHERE CustomerName LIKE 'a%';

• Find any values that have "r" in second position


WHERE CustomerName LIKE '_r%';

• Finds any values that starts with "a" and ends with "o"

WHERE ContactName LIKE 'a%o';

Database Basics and operations with MySQL


Wildcard Characters
• Supported characters also include:
• \ – specify prefix to treat special characters as normal
• [charlist] – specifying which characters to look for
• [!charlist] – excluding characters

SELECT * FROM `customers`


WHERE `city` LIKE '[a-c]%';

"a", "b", or "c"

Database Basics and operations with MySQL


Problem: Harry Potter Books
• Write a query to retrieve information about the titles of all Harry
Potter books
• Use Wildcards
• Query book_library database

Database Basics and operations with MySQL


Harry Potter Books - Solution
SELECT title FROM books
WHERE title LIKE 'Harry Potter%';

Database Basics and operations with MySQL


Using Regular Expression
• REGEXP - pattern matching using regular expressions
SELECT `employee_id`, `first_name`, `last_name`
FROM `employees`
WHERE `first_name` REGEXP '^\[^K\]{3}\$';

Regular expression

Database Basics and operations with MySQL


Summary
• MySQL Server provides various built-in
functions
• Numerical functions
• String functions

• Using Wildcards, we can obtain results


by partial string matches
• Regular expressions

Database Basics and operations with MySQL


Chapter 5.
Data Aggregation - How to get
data insights?

Database Basics and operations with MySQL


Grouping
Consolidating data based on criteria
Database Basics and operations with MySQL
Grouping
• Grouping allows taking data into separate groups based on a
common property
Grouping column

employee department_name salary


Adam Database Support 5,000 Can be
John Database Support 15,000 aggregated
Jane Application Support 10,000
George Application Support 15,000
Lila Application Support 5,000
Fred Software Support 15,000
Database Basics and operations with MySQL
GROUP BY
• With GROUP BY you can get each separate group and use an
"aggregate" function over it (like Average, Min or Max):

SELECT e.`job_title`, count(employee_id)


FROM `employees` AS e Grouping
GROUP BY e.`job_title`; Columns

Database Basics and operations with MySQL


DISTINCT

• With DISTINCT you will get all unique values:

SELECT DISTINCT e.`job_title`


FROM `employees` AS e; Unique
Values

Database Basics and operations with MySQL


Problem: Departments Total Salaries
• Write a query which prints the total sum of salaries for each
department in the uni_ruse database
• Order them by DepartmentID (ascending)
employee department_name salary
Adam Database Support 5,000
department_id total_salary
John Database Support 15,000
1 20,000
Jane Application Support 10,000
2 30,000
George Application Support 15,000
3 15,000
Lila Application Support 5,000
Fred Software Support 15,000

Database Basics and operations with MySQL


Solution: Departments Total Salaries
Grouping
Column

SELECT e.`department_id`, New Column Alias


SUM(e.`salary`) AS 'Total Salary'
FROM `employees` AS e Table Alias
GROUP BY e.`department_id` Grouping
ORDER BY e.`department_id`; Columns

Database Basics and operations with MySQL


Aggregate Functions
COUNT, SUM, MAX, MIN, AVG…
Database Basics and operations with MySQL
Aggregate Functions
• Used to operate over one or more groups performing data analysis on every
one
• MIN, MAX, AVG, COUNT etc.

• They usually ignore NULL values

SELECT e.`department_id`,
MIN(e.`salary`) AS 'MinSalary'
FROM `employees` AS e
GROUP BY e.`department_id`;
Database Basics and operations with MySQL
COUNT
• COUNT - counts the values (not nulls) in one or more columns based
on grouping criteria
employee department_name salary
Adam Database Support 5,000 department_name SalaryCount
John Database Support 15,000 Database Support 2
Jane Application Support 10,000 Application Support 3
George Application Support 15,000 Software Support 1
Lila Application Support 5,000
Fred Software Support 15,000

Database Basics and operations with MySQL


COUNT Syntax
• Note that we when we use COUNT we will ignore any employee with
NULL salary. Grouping
Column
New Column Alias
SELECT e.`department_id`,
COUNT(e.`salary`) AS 'Salary Count'
FROM `employees` AS e
GROUP BY e.`department_id`;
Grouping
Columns
Database Basics and operations with MySQL
SUM
• SUM - sums the values in a column
employee department_name salary
Adam Database Support 5,000
department_name total_salary
John Database Support 15,000
Database Support 20,000
Jane Application Support 10,000
Application Support 30,000
George Application Support 15,000
Software Support 15,000
Lila Application Support 5,000
Fred Software Support 15,000

Database Basics and operations with MySQL


SUM Syntax
• If any department has no salaries NULL will be displayed.
Grouping
Column

SELECT e.`department_id`, New Column Alias


SUM(e.`salary`) AS 'TotalSalary'
FROM `employees` AS e Table Alias
GROUP BY e.`department_id`;
Grouping
Columns
Database Basics and operations with MySQL
MAX
• MAX - takes the maximum value in a column.
employee department_name salary
Adam Database Support 5,000
department_name max_salary
John Database Support 15,000
Database Support 15,000
Jane Application Support 10,000
Application Support 15,000
George Application Support 15,000
Software Support 15,000
Lila Application Support 5,000
Fred Software Support 15,000

Database Basics and operations with MySQL


MAX Syntax
Grouping
Column

SELECT e.`department_id`, New Column Alias


MAX(e.`salary`) AS 'MaxSalary'
FROM `employees` AS e Table Alias
GROUP BY e.`department_id`;
Grouping
Columns
Database Basics and operations with MySQL
MIN
• MIN takes the minimum value in a column.
employee department_name salary
Adam Database Support 5,000
department_name min_salary
John Database Support 15,000
Database Support 5,000
Jane Application Support 10,000
Application Support 5,000
George Application Support 15,000
Software Support 15,000
Lila Application Support 5,000
Fred Software Support 15,000

Database Basics and operations with MySQL


MIN Syntax
Grouping
Column

SELECT e.`department_id`, New Column Alias


MIN(e.`salary`) AS 'MinSalary'
FROM `employees` AS e Table Alias
GROUP BY e.`department_id`;
Grouping
Columns
Database Basics and operations with MySQL
AVG
• AVG calculates the average value in a column.
employee department_name salary
Adam Database Support 5,000
department_name average_salary
John Database Support 15,000
Database Support 10,000
Jane Application Support 10,000
Application Support 10,000
George Application Support 15,000
Software Support 15,000
Lila Application Support 5,000
Fred Software Support 15,000

Database Basics and operations with MySQL


AVG Syntax
Grouping
Column
New Column Alias
SELECT e.`department_id`,
AVG(e.`salary`) AS 'AvgSalary'
FROM `employees` AS e Table Alias
GROUP BY e.`department_id`;
Grouping
Columns
Database Basics and operations with MySQL
Having
Using predicates while grouping
Database Basics and operations with MySQL
Having Clause
• The HAVING clause is used to filter data based on aggregate values.
• We cannot use it without grouping before that

• Any Aggregate functions in the "HAVING" clause and in the


"SELECT" statement are executed one time only

• Unlike HAVING, the WHERE clause filters rows before the aggregation

Database Basics and operations with MySQL


Having Clause: Example
• Filter departments which have total salary more or equal 15,000.

Aggregated value
employe department_name salary Total
e Salary
Adam Database Support 5,000 department_name average_salary
20,000
John Database Support 15,000 Database Support 10,000
Jane Application Support 10,000 Software Support 15,000
George Application Support 15,000 10,000
Lila Application Support 5,000
Fred Software Support 15,000 15,000

Database Basics and operations with MySQL


HAVING Syntax
Aggregate Grouping
Function Column

SELECT e.`department_id`, New


SUM(e.salary) AS 'TotalSalary' Column Alias
FROM `employees` AS e
GROUP BY e.`department_id` Grouping
HAVING `TotalSalary`< 250000; Columns
Having
Predicate
Database Basics and operations with MySQL
Summary
• Grouping
• Aggregate Functions
• Having

SELECT
SUM(e.`salary) AS 'TotalSalary'
FROM `employees` AS e
GROUP BY e.`department_id`
HAVING SUM(e.`salary`) < 250000;

Database Basics and operations with MySQL


Chapter 6.
Table Relations - Database Design
and Rules

Database Basics and operations with MySQL


Database Design
Fundamental Concepts
Database Basics and operations with MySQL
Steps in Database Design

1 2 3
Identification of Defining table Defining primary
the entities columns keys

4 5 6
Modeling Defining
Filling test data
relationships constraints

Database Basics and operations with MySQL


Identification of Entities
• Entity tables represent objects from the real world
• Most often they are nouns in the specification
• For example:

We need to develop a system that stores information about


students, which are trained in various courses. The courses
are held in different towns. When registering a new student
the following information is entered: name, faculty number,
photo and date.

• Entities: Student, Course, Town

Database Basics and operations with MySQL


Identification of the Columns
• Columns are clarifications for the entities in the text of the
specification, for example:
We need to develop a system that stores information about
students, which are trained in various courses. The courses
are held in different towns. When registering a new student
the following information is entered: name, faculty number,
photo and date.

• Students have the following characteristics:


• Name, faculty number, photo, date of enlistment and a list of courses they
visit

Database Basics and operations with MySQL


How to Choose a Primary Key?
• Always define an additional column for the primary key
• Don't use an existing column
• Must be an integer number
• Must be declared as a PRIMARY KEY
• Use auto_increment to implement auto-increment
• Put the primary key as a first column

• Exceptions
• Entities that have well known ID, e.g. countries (BG, DE, US) and currencies
(USD, EUR, BGN)

Database Basics and operations with MySQL


Identification of Relationships
• Relationships are dependencies between the entities:
We need to develop a system that stores information about
students, which are trained in various courses. The courses are
held in different towns. When registering a new student the
following information is entered: name, faculty number, photo
and date.

• "Students are trained in courses" – many-to-many relationship.

• "Courses are held in towns" – many-to-one (or many-to-many) relationship

Database Basics and operations with MySQL


Table Relations
Relational Database Model in Action
Database Basics and operations with MySQL
Relationships
• Relationships between tables are based on interconnections:
PRIMARY KEY / FOREIGN KEY
Primary key Foreign key Primary key
towns
countries
id name country_id
1 Sofia 1 id name
2 Varna 1 1 Bulgaria
3 Munich 2 2 Germany
4 Berlin 2 3 Russia
5 Moscow 3
Relationships 9

Database Basics and operations with MySQL


Relationships
• The foreign key is an identifier of a record located in another
table (usually its primary key)

• By using relationships we avoid repeating data in the database

• Relationships have multiplicity:


• One-to-many – e.g. country / towns
• Many-to-many – e.g. student / course
• One-to-one – e.g. example driver / car

Database Basics and operations with MySQL


One-to-Many/Many-to-One
Primary key Primary key Foreign key

Mountains Peaks
mountain_id name peak_id mountain_id
1 Causasus 61 1
66 1

Relation

Database Basics and operations with MySQL


Setup
CREATE TABLE mountains( Primary key
mountain_id INT PRIMARY KEY,
mountain_name VARCHAR(50)
);
CREATE TABLE peaks(
Table Peaks
peak_id INT PRIMARY KEY,
mountain_id INT,
CONSTRAINT fk_peaks_mountains
Foreign Key
FOREIGN KEY (mountain_id)
REFERENCES mountains(mountain_id)
);

Database Basics and operations with MySQL


Foreign Key
Constraint
Name

CONSTRAINT fk_peaks_mountains
FOREIGN KEY (mountain_id) Foreign Key
REFERENCES mountains(mountain_id);
Referent Table Primary Key

Database Basics and operations with MySQL


Many-to-Many
Primary key
Primary key
employees projects
employee_id name project_id name
1 … 4 …
40 … 24 …

Mapping table
employees_projects

employee_id project_id
1 4
40 24
Database Basics and operations with MySQL
Setup
CREATE TABLE employees(
employee_id INT PRIMARY KEY,
employee_name VARCHAR(50) Table Employees
);

CREATE TABLE projects(


Table Projects
project_id INT PRIMARY KEY,
project_name VARCHAR(50)
);

Database Basics and operations with MySQL


Setup
Mapping Table
CREATE TABLE employees_projects(
employee_id INT,
project_id INT, Primary Key
CONSTRAINT pk_employees_projects
PRIMARY KEY(employee_id, project_id),
CONSTRAINT fk_employees_projects_employees
FOREIGN KEY(employee_id) Foreign Key
REFERENCES employees(employee_id),
CONSTRAINT fk_employees_projects_projects
FOREIGN KEY(project_id)
REFERENCES projects(project_id)
);
Foreign Key

Database Basics and operations with MySQL


One-to-One
Primary key Primary key
Foreign key
cars drivers
car_id driver_id driver_id driver_name
1 166 166 …
2 102 102 …

Relation

Database Basics and operations with MySQL


Setup
CREATE TABLE drivers( Primary key
driver_id INT PRIMARY KEY,
driver_name VARCHAR(50)
);
One driver
CREATE TABLE cars( per car
car_id INT PRIMARY KEY,
driver_id INT UNIQUE,
CONSTRAINT fk_cars_drivers Foreign Key
FOREIGN KEY (driver_id)
REFERENCES drivers(driver_id)
);

Database Basics and operations with MySQL


Foreign Key
Constraint
Name

CONSTRAINT fk_cars_drivers
FOREIGN KEY (driver_id) Foreign Key
REFERENCES drivers(driver_id)
Referent Table Primary Key

Database Basics and operations with MySQL


Table 1 Table 2

Retrieving Related Data


Using Simple JOIN statements

Database Basics and operations with MySQL


Joins
• Table relations are useful when combined with JOINS
• With JOINS we can get data from two tables simultaneously
• JOINS require at least two tables and a "join condition"
• Example: Select from Tables

SELECT * FROM table_a


JOIN table_b ON
table_b.common_column = table_a.common_column

Join Condition
Database Basics and operations with MySQL
Problem: Peaks in Rila
• Report all peaks for "Rila" mountain.
• Report includes mountain's name, peak's name and also peak's elevation
• Peaks should be sorted by elevation descending
• Use database "Geography".

Database Basics and operations with MySQL


Solution: Peaks in Rila
Cross Table Selection

SELECT m.mountain_range, p.peak_name, p.elevation


FROM peaks AS p
JOIN mountains AS m ON m.id = p.mountain_id
WHERE m.mountain_range = 'Rila'
ORDER BY p.elevation DESC; Join Condition

Sort

Database Basics and operations with MySQL


Cascade Operations
Cascade Delete/Update
Database Basics and operations with MySQL
Definition
• Cascading allows when a change is made to certain entity, this change to apply
to all related entities
Foreign key
Primary key Primary key

orders order_items
order_id order_name item_id order_id
1 … 4 1
22 … 24 22
87 1
Cascade delete

Database Basics and operations with MySQL


CASCADE DELETE
• CASCADE can be either DELETE or UPDATE.

• Use CASCADE DELETE when:


• The related entities are meaningless without the "main" one

• Do not use CASCADE DELETE when:


• You make "logical delete"
• You preserve history
• Keep in mind that in more complicated relations it won't work with circular references

Database Basics and operations with MySQL


CASCADE UPDATE
• Use CASCADE UPDATE when:
• The primary key is NOT identity (not auto-increment) and therefore it can be
changed
• Best used with UNIQUE constraint

• Do not use CASCADE UPDATE when:


• The primary is identity (auto-increment)

• Cascading can be avoided using triggers or procedures

Database Basics and operations with MySQL


Foreign Key Delete Cascade
Table Drivers
CREATE TABLE drivers(
driver_id INT PRIMARY KEY,
driver_name VARCHAR(50)
);
Table Cars
CREATE TABLE cars(
car_id INT PRIMARY KEY, Foreign Key
driver_id INT,
CONSTRAINT fk_car_driver FOREIGN KEY(driver_id)
REFERENCES drivers(driver_id) ON DELETE CASCADE
);

Database Basics and operations with MySQL


Foreign Key Update Cascade
Table Drivers
CREATE TABLE drivers(
driver_id INT PRIMARY KEY,
driver_name VARCHAR(50)
);

CREATE TABLE cars( Table Cars


car_id INT PRIMARY KEY,
Foreign Key
driver_id INT,
CONSTRAINT fk_car_driver FOREIGN KEY(driver_id)
REFERENCES drivers(driver_id) ON UPDATE CASCADE
);

Database Basics and operations with MySQL


E/R Diagrams
Entity / Relationship Diagrams
Database Basics and operations with MySQL
Relational Schema
• Relational schema of a DB is the collection of:
• The schemas of all tables
• Relationships between the tables
• Any other database objects (e.g. constraints)

• The relational schema describes the structure of the database


• Doesn't contain data, but metadata

• Relational schemas are graphically displayed in Entity / Relationship


diagrams (E/R Diagrams)

Database Basics and operations with MySQL


E/R Diagram
• Click on "Database" then select "Reverse Engineer"

Database Basics and operations with MySQL


E/R Diagram

Database Basics and operations with MySQL


E/R Diagram

Database Basics and operations with MySQL


Summary
• We design databases by specification entities and their
characteristics

• Two types of relations:


• One-to-many
• Many-to-many

• We visualize relations via E/R diagrams


Database Basics and operations with MySQL
Chapter 7.
Joins, Subqueries and Indices -
Data Retrieval and Performance

Database Basics and operations with MySQL


JOINS
Gathering Data From Multiple Tables

Database Basics and operations with MySQL


Data from Multiple Tables
• Sometimes you need data from several tables:
Employees Departments
employee_name department_id department_id department_name

Edward 3 3 Sales
John NULL 4 Marketing
5 Purchasing

employee_name department_id department_name

Edward 3 Sales
Database Basics and operations with MySQL
Cartesian Product
• This will produce Cartesian product:
SELECT last_name, name AS department_name
FROM employees, departments;
• The result:
last_name department_name

Gilbert Engineering
Brown Engineering
… …
Gilbert Sales
Brown Sales

Database Basics and operations with MySQL


Cartesian Product
• Each row in the first table is paired with all the rows in the second
table
• When there is no relationship defined between the two tables

• Formed when:
• A join condition is omitted
• A join condition is invalid

• To avoid, always include a valid JOIN condition

Database Basics and operations with MySQL


JOINS
• JOINS – used to collect data from two or more tables
• Types:

INNER JOIN LEFT JOIN RIGHT JOIN

OUTER
(UNION) CROSS JOIN
JOIN
Database Basics and operations with MySQL
Tables

id name course_id id name

1 Alice 1 1 HTML5
2 Michael 1 2 CSS3
3 Caroline 2 3 JavaScript
4 David 5 4 PHP
5 Emma NULL 5 MySQL

Database Basics and operations with MySQL


INNER JOIN

▪ Produces a set of records which match in both tables


students_name courses_name
SELECT students.name, courses.name Alice HTML5
FROM students
Michael HTML5
INNER JOIN courses
Caroline CSS3
ON students.course_id = courses.id
David MySQL
Join Conditions
Database Basics and operations with MySQL
LEFT JOIN

▪ Matches every entry in left table regardless of match in the right


students_name courses_name
SELECT students.name, courses.name Alice HTML5
FROM students
Michael HTML5
LEFT JOIN courses
Caroline CSS3
ON students.course_id = courses.id
David MySQL
Join Conditions Emma NULL
Database Basics and operations with MySQL
RIGHT JOIN
▪ Matches every entry in right table regardless of match in the left

students_name courses_name

Alice HTML5
Michael HTML5
SELECT students.name, courses.name
Caroline CSS3
FROM students
RIGHT JOIN courses NULL JavaScript
ON students.course_id = courses.id NULL PHP
David MySQL
Join Conditions
Database Basics and operations with MySQL
OUTER (FULL JOIN)

▪ Returns all records in both tables regardless of any match


▪ Less useful than INNER, LEFT or RIGHT JOINs and it's not
implemented in MySQL
▪ We can use UNION of a LEFT and RIGHT JOIN

Database Basics and operations with MySQL


UNION of LEFT and RIGHT JOIN
SELECT students.name, courses.name
FROM students students_name courses_name
LEFT JOIN courses
ON students.course_id = courses.id Alice HTML5
Michael HTML5
UNION Caroline CSS3
David MySQL
SELECT students.name, courses.name Emma NULL
FROM students NULL JavaScript
RIGHT JOIN courses NULL PHP
ON students.course_id = courses.id

Database Basics and operations with MySQL


CROSS JOIN
▪ Produces a set of associated rows of two tables
▪ Multiplication of each row in the first table with each in
second
▪ The result is a Cartesian product, when there's no condition in
the WHERE clause
SELECT * FROM courses AS c
CROSS JOIN students AS s;
No Join Conditions
Database Basics and operations with MySQL
Courses Cross Join Students
id name id name course_id
1 HTML5 1 Alice 1
2 CSS3 2 Michael 1
3 JavaScript 3 Caroline 2
4 PHP 4 David 5
5 MySQL Result 5 Emma NULL
course_id course_name student_id student_name
1 HTML5 1 Alice
1 HTML5 2 Michael
1 HTML5 3 Caroline
… … … …
Database Basics and operations with MySQL
Join Overview
employee_name department_id department_id department_name
Sally 13 7 Executive
John 10 8 Sales
Michael 22 10 Marketing
Bob 11 12 HR
Robin 7 18 Accounting
Jessica 15 22 Engineering

Relation
Database Basics and operations with MySQL
Join Overview: INNER JOIN

employee_name department_id department_id department_name

Sally 13 7 Executive
John 10 8 Sales
Michael 22 10 Marketing
Bob 11 12 HR
Robin 7 18 Accounting
Jessica 15 22 Engineering

Database Basics and operations with MySQL


Join Overview: LEFT JOIN
employee_name department_id department_id department_name

Sally 13 7 Executive
John 10 8 Sales
Michael 22 10 Marketing
Bob 11 12 HR
Robin 7 15 Shipping And
Receiving
Jessica 15
18 Accounting
22 Engineering
NULL NULL

Database Basics and operations with MySQL


Join Overview: RIGHT JOIN
employee_name department_id department_id department_name

Sally 13 7 Executive
John 10 8 Sales
Michael 22 10 Marketing
Bob 11 12 HR
Robin 7 18 Accounting
Jessica 15 22 Engineering

Database Basics and operations with MySQL


Problem: Managers
• Get information about the first 5 managers in the “uni_ruse" database
• id
• full_name
• department_id
• department_name

Database Basics and operations with MySQL


Solution: Managers

SELECT e.employee_id, CONCAT(first_name, " ",


last_name) AS `full_name`, d.department_id, d.name
FROM employees AS e
RIGHT JOIN departments AS d
ON d.manager_id = e.employee_id
ORDER BY e.employee_id LIMIT 5;

Database Basics and operations with MySQL




Subqueries
Query Manipulation on Multiple Levels

Database Basics and operations with MySQL


Subqueries

• Subqueries – SQL query inside a larger one


• Can be nested in SELECT, INSERT, UPDATE, DELETE
• Usually added within a WHERE clause

id name course_id
SELECT * FROM students 1 Alice 1
WHERE course_id = 1; 2 Michael 1

Subquery

Database Basics and operations with MySQL


Problem: Higher Salary
• Count the number of employees who receive salary, higher than the average
• Use "uni_ruse" database

employee_id first_name last_name …


216 Mike Seamans … count
178 Barbara Moreland … 88
… … … …

Table "employees"

Database Basics and operations with MySQL


Solution: Higher Salary
SELECT COUNT(e.employee_id) AS `count`
FROM employees AS e
WHERE e.salary >
(
SELECT AVG(salary) AS 'average_salary'
FROM employees
);

Database Basics and operations with MySQL


Indices
Clustered and Non-Clustered Indices

Database Basics and operations with MySQL


Indices
• Structures associated with a table or view that speeds retrieval of
rows
• Usually implemented as B-trees

• Indices can be built-in the table (clustered) or stored externally (non-


clustered)

• Adding and deleting records in indexed tables is slower!


• Indices should be used for big tables only (e.g. 50 000 rows)

Database Basics and operations with MySQL


Clustered Indices
• Clustered index determine the order of data
• Very useful for fast execution of WHERE, ORDER BY and GROUP BY clauses

• Maximum 1 clustered index per table Keys


• If a table has no clustered index,
its data rows are stored in an 0-99 100-199 200-299
unordered structure (heap)

Data ☰ ☰ ☰ ☰ ☰ ☰ ☰

Database Basics and operations with MySQL


Non-Clustered Indices
• Useful for fast retrieving a single record or a range of records
• Each key value entry has a pointer to the data row that contains the key value
Keys
• Maintained in a separate
0-99 100-199 200-299
structure in the DB

Pointers 1885,1885 6587,6589 8052,8053

Data ☰ ☰ ☰ ☰ ☰ ☰ ☰

Database Basics and operations with MySQL


Indices Syntax

CREATE INDEX
ix_users_first_name_last_name
ON users(first_name, last_name);

Columns
Table Name

Database Basics and operations with MySQL


Summary
• Joins
SELECT * FROM employees AS e
JOIN departments AS d ON
d.department_id = e.department_id

• Subqueries are used to nest queries

• Indices improve SQL search performance if used properly

Database Basics and operations with MySQL


Chapter 8.
Functions and Triggers –
User-defined Functions, Procedures,
Triggers and Transactions

Database Basics and operations with MySQL


User-Defined Functions
Encapsulating custom logic

Database Basics and operations with MySQL


User-Defined Functions

• Extend the functionality of a MySQL Server


• Modular programming – write once, call it any number of times
• Faster execution – doesn't need to be reparsed and reoptimized with each
use
• Break out complex logic into shorter code blocks

• Functions can be:


• Scalar – return single value or NULL
• Table-Valued – return a table

Database Basics and operations with MySQL


Problem: Count Employees by Town

• Write a function ufn_count_employees_by_town(town_name) that:

• Accepts town name as parameter

• Returns the count of employees in the database who live in that town

Database Basics and operations with MySQL


Solution: Count Employees by Town

Function Name
CREATE FUNCTION ufn_count_employees_by_town(town_name VARCHAR(20))
RETURNS DOUBLE
BEGIN
DECLARE e_count DOUBLE;
SET e_count := (SELECT COUNT(employee_id) FROM employees AS e
INNER JOIN addresses AS a ON a.address_id = e.address_id
INNER JOIN towns AS t ON t.town_id = a.town_id
WHERE t.name = town_name);
RETURN e_count; Function Logic
END

Database Basics and operations with MySQL


Result: Count Employees by Town
• Examples of expected output:
Employees
Function Call count
SELECT ufn_count_employees_by_town('Sofia'); 3

SELECT ufn_count_employees_by_town('Berlin'); 1

SELECT ufn_count_employees_by_town(NULL); 0

Database Basics and operations with MySQL


Stored Procedures
Sets of queries stored on DB Server
Database Basics and operations with MySQL
Stored Procedures
• Stored procedures are logic removed from the application and placed
on the database server
• Can greatly cut down traffic on the network
• Improve the security of your database server
• Separate data access routines from the business logic

• Accessed by programs using different platforms and API's

Database Basics and operations with MySQL


Creating Stored Procedures
• CREATE PROCEDURE
• Example:
Procedure Name
DELIMITER $$
CREATE PROCEDURE usp_select_employees_by_seniority()
BEGIN
SELECT * Procedure Logic
FROM employees
WHERE ROUND((DATEDIFF(NOW(), hire_date) / 365.25)) < 15;
END $$

Database Basics and operations with MySQL


Executing and Dropping
Stored Procedures
• Executing a stored procedure by CALL

CALL usp_select_employees_by_seniority();

• DROP PROCEDURE

DROP PROCEDURE usp_select_employees_by_seniority;

Database Basics and operations with MySQL


Defining Parameterized Procedures

• To define a parameterized procedure use the syntax:

CREATE PROCEDURE usp_procedure_name


(parameter_1_name parameter_type,
parameter_2_name parameter_type,…)

Database Basics and operations with MySQL


Parameterized Stored Procedures – Example
Procedure Name
DELIMITER $$
CREATE PROCEDURE usp_select_employees_by_seniority(min_years_at_work INT)
BEGIN
SELECT first_name, last_name, hire_date,
ROUND(DATEDIFF(NOW(),DATE(hire_date)) / 365.25,0) AS 'years' Procedure Logic
FROM employees
WHERE ROUND(DATEDIFF(NOW(),DATE(hire_date)) / 365.25,0) > min_years_at_work
ORDER BY hire_date;
END $$
Usage
CALL usp_select_employees_by_seniority(15);

Database Basics and operations with MySQL


Returning Values
CREATE PROCEDURE usp_add_numbers
(first_number INT,
second_number INT, Creating procedure
OUT result INT)
BEGIN
SET result = first_number + second_number
END $$
DELIMITER ;
Executing procedure
SET @answer=0;
CALL usp_add_numbers(5, 6,@answer);
SELECT @answer;
Display results
-- 11

Database Basics and operations with MySQL


Problem: Employees Promotion
• Write a stored procedure that raises employees salaries by
department name (as parameter) by 5%
• Use uni_ruse database

Database Basics and operations with MySQL


Solution: Employees Promotion
CREATE PROCEDURE usp_raise_salaries(department_name varchar(50))
BEGIN
UPDATE employees e
INNER JOIN departments AS d
ON e.department_id = d.department_id
SET salary = salary * 1.05
WHERE d.name = department_name;
END

Database Basics and operations with MySQL


Result: Employees Promotion
• Procedure result for 'Sales' department:
CALL usp_raise_salaries('Sales');

Data before procedure call: Data after procedure call:


employee_id salary employee_id salary
268 48 100.00 268 50 505.00
273 72 100.00 273 75 705.00
… … … …

Database Basics and operations with MySQL


What is a Transaction?
Executing operations as a whole
Database Basics and operations with MySQL
Transactions
• Transaction is a sequence of actions (database operations) executed
as a whole
• Either all of them complete successfully or none of the them

• Example of transaction
• A bank transfer from one account into another (withdrawal + deposit)
• If either the withdrawal or the deposit fails the whole operation is cancelled

Database Basics and operations with MySQL


Transactions: Lifecycle (Rollback)
Read Write

Durable Write Sequence Durable,


starting of reads and consistent,
state writes ending state
Rollback

Database Basics and operations with MySQL


Transactions: Lifecycle (Commit)
Read Write

Durable Write Sequence Commit Durable,


starting of reads and consistent,
state writes ending state

Database Basics and operations with MySQL


Transactions Behavior
• Transactions guarantee the consistency and the integrity of the
database
• All changes in a transaction are temporary
• Changes are persisted when COMMIT is executed.
• At any time all changes can be canceled by ROLLBACK

• All of the operations are executed as a whole.

Database Basics and operations with MySQL


Checkpoints in games
DIE

Castle 1-1 Castle 1-2

Mario SURVIVE

Database Basics and operations with MySQL


What are Transactions?
ROLLBACK

STATE 1 STATE 2

Queries COMMIT

Database Basics and operations with MySQL


Problem: Employees Promotion By ID

• Write a transaction that raises an employee's salary by id only if the employee


exists in the database
• If not, no changes should be made
• Use uni_ruse database

Database Basics and operations with MySQL


Solution: Employees Promotion
CREATE PROCEDURE usp_raise_salary_by_id(id int)
BEGIN
START TRANSACTION;
IF((SELECT count(employee_id) FROM employees WHERE employee_id like
id)<>1) THEN
ROLLBACK;
ELSE
UPDATE employees AS e SET salary = salary + salary*0.05
WHERE e.employee_id = id;
END IF;
END

Database Basics and operations with MySQL


Transactions Properties

• Modern DBMS servers have built-in transaction support


• Implement “ACID” transactions
• E.g. Oracle, MySQL, MS SQL Server, …

• ACID means:
• Atomicity
• Consistency
• Isolation
• Durability

Database Basics and operations with MySQL


Triggers
Maintaining the integrity of the data
Database Basics and operations with MySQL
What Are Triggers?
• Triggers - small programs in the database itself, activated by database
events application layer
• UPDATE, DELETE or INSERT queries
• Called in case of specific event

• We do not call triggers explicitly


• Triggers are attached to a table

Database Basics and operations with MySQL


MySQL Types of Triggers
Before After
Trigger
Trigger

Event Event

Database Basics and operations with MySQL


Events
• There are three different events that can be applied within a trigger:

Events

Insert Update Delete

Database Basics and operations with MySQL


Problem: Triggered
• Create a table deleted_employees with fields:
• employee_id – primary key
• first_name, last_name, middle_name, job_title, deparment_id, salary

• Add a trigger to employees table that logs deleted employees into the
deleted_employees table
• Use uni_ruse database

Database Basics and operations with MySQL


Solution: Triggered

CREATE TABLE deleted_employees(


employee_id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(20),
last_name VARCHAR(20),
middle_name VARCHAR(20),
job_title VARCHAR(50),
department_id INT,
salary DOUBLE
);

Database Basics and operations with MySQL


Solution: Triggered
CREATE TRIGGER tr_deleted_employees
AFTER DELETE
ON employees
FOR EACH ROW
BEGIN
INSERT INTO deleted_employees
(first_name,last_name,middle_name,job_title,department_id,salary)
VALUES(OLD.first_name,OLD.last_name,OLD.middle_name,OLD.job_title,OL
D.department_id,OLD.salary);
END;
The OLD and NEW keywords allow you
to access columns before/after trigger
action

Database Basics and operations with MySQL


Result: Triggered
• Trigger action result on DELETE:
• NOTE: Remove foreign key checks before trying to delete employees
• DO NOT submit foreign key restriction changes in the Judge System

DELETE FROM employees WHERE employee_id IN (1);

Data in deleted_employees table:


employee_id first_name last_name …
1 Guy Gilbert …

Database Basics and operations with MySQL


Summary
• We can optimize with User-defined Functions

• Transactions improve security and consistency

• Stored Procedures encapsulate repetitive logic

• Triggers execute before certain events on tables

Database Basics and operations with MySQL


Project 609854‐EPP‐1‐2019‐1‐FR‐EPPKA2‐CBHE‐JP ‐ ASEAN FACTORI 4.0:
From Automation and Control Training to the Overall Roll‐out of Industry 4.0 across South East Asian Nations

REFERENCES
1. Robin Dewson, Beginning SQL Server for Developers, 4th Edition, Apress Publishing, pp. 705,
ISBN: 1484202813, 2014;

2. Walter Shields, SQL QuickStart Guide: The Simplified Beginner's Guide to Managing,
Analyzing, and Manipulating Data With SQL (QuickStart Guides™ ‐ Technology), ClydeBank
Media LLC, pp. 242, ISBN: 1945051752, 2019;

3. Vinicius Grippa, Sergey Kuzmichev, Learning MySQL: Get a Handle on Your Data, 2nd Edition,
O'Reilly Media, pp. 629, ISBN: 1492085928, 2021;

4. Joel Murach, Murach's MySQL, 3rd Edition, Mike Murach & Associates Publishing, pp. 628,
ISBN: 1943872368, 2019;

5. Rick Silva, MySQL Crash Course: A Hands‐on Introduction to Database Development, No


Starch Press, pp. 352, ISBN: 1718503008, 2023;

6. Sveta Smirnova, Alkin Tezuysal, MySQL Cookbook: Solutions for Database Developers and
Administrators, 4th Edition, O'Reilly Media, pp. 971, ISBN: 1492093165, 2022;

7. Thomas Pettit, Scott Cosentino, The MySQL Workshop: A practical guide to working with data
and managing databases with MySQL, Packt Publishing, pp. 726, ISBN: 1839214902, 2022;

8. Adam Aspin, Querying MySQL: Make your MySQL database analytics accessible with SQL
operations, data extraction, and custom queries, BPB Publications, pp. 672, ISBN:
9355512678, 2022;

9. Rick Silva, MySQL Crash Course: A Hands‐on Introduction to Database Development, No


Starch Press, pp. 323, ISBN: 1718503008, 2023.

You might also like