You are on page 1of 73

Databases - SQL

Agenda
1. Relational databases
2. SQL
3. Tables
4. Data Definition Language
5. Data Manipulation Language
6. Data Query Language
7. Primary and foreign keys
8. Table relationships
9. Joins
10. SQL extras
11. Database modeling exercises
12. Optional:
a. Transactions
b. ACID
c. Views
d. Procedures
© 2019 Software Development Academy. All Rights Reserved. 2
Relational databases

© 2019 Software Development Academy. All Rights Reserved. 3


Relational databases

A database is an organised collection of data.

Relational databases store data in multiple tables that are linked through
different kinds of relationships.

While one database can store multiple datasets, a table stores only one
dataset.

© 2019 Software Development Academy. All Rights Reserved. 4


Relational databases - examples
1. Bookstore database - must store information related to books, customers and orders:
a. books information table: author, title and release year,
b. customers information table: first name, last name and phone number,
c. orders information table: the customer who ordered, books ordered, quantity and status.

2. Fitness gym database - must store information related to trainers, classes and subscriptions:
a. trainers information table: first name, last name and specialities,
b. classes information table: class name, description and schedule,
c. subscriptions information table: start date, end date and customer.

3. Cinema database - must store information related to movies, schedules and tickets:
a. movies information table: movie title and description,
b. schedule information table: which movie, which room, start and end time,
c. tickets: movie, adult/children ticket and seat number.

© 2019 Software Development Academy. All Rights Reserved. 5


SQL - Structured Query Language

© 2019 Software Development Academy. All Rights Reserved. 6


SQL

In order to interact with a relational database we can use the SQL (Structured
Query Language) language.

SQL provides us functionality to model, query, manipulate and control access to


our databases.

© 2019 Software Development Academy. All Rights Reserved. 7


SQL subsets

● DDL - data definition language. Helps users define what kind of data they
are going to store and how they are going to model this data.
● DML - data manipulation language. Allows users to insert, update and
delete data from the database.
● DQL - data query language. Helps users retrieve information from the
database.
● DCL - data control language. Allows users to restrict and control access to
the database.

© 2019 Software Development Academy. All Rights Reserved. 8


Tables

© 2019 Software Development Academy. All Rights Reserved. 9


Database table

● A table is a collection of data held in a two dimensional structure.

● The two dimensions are rows and columns.

● A table is identified by a name.

© 2019 Software Development Academy. All Rights Reserved. 10


Database table

Table name
employees Column name
Column data type id firstName lastName dateOfBirth
INT(6) VARCHAR(30) VARCHAR(30) DATE
1 John Smith 1980-01-04

Table row (record) 2 John Cage 1965-06-12


3 Jadine Mcclain 1990-09-09
4 Ibraheem Mcfadden 1994-03-03
5 Kade Christie 1970-11-11

Table field
Table column

Data item

© 2019 Software Development Academy. All Rights Reserved. 11


Column data types

The column data types define the type of information you can store in that
particular column:
● numeric data types such as int, tinyint, bigint, float, real, etc.,
● date and time data types such as Date, Time, Datetime, etc.,
● character and string data types such as char, varchar, text, etc.,
● logical values are represented by a TINYINT type value (0 or 1).

© 2019 Software Development Academy. All Rights Reserved. 12


Column properties

When defining a table the user can set certain properties on the columns:
● data type controls the type of values stored in the column,
● NOT NULL defines whether a column must be filled or not,
● AUTOINCREMENT states that the column value will be generated
automatically (incrementation of the last inserted value) - this only
works for numeric columns,
● UNIQUE states that there cannot be more than one row with the same
value for that particular column.

© 2019 Software Development Academy. All Rights Reserved. 13


DDL - Data Definition Language

© 2019 Software Development Academy. All Rights Reserved. 14


CREATE DATABASE
The CREATE DATABASE instruction allows CREATE DATABASE database_name;
you to create a new database.

When creating a new database, only thing Example:


CREATE DATABASE petclinic;
that you need to provide is the database
name.

After a database has been created you


can start defining the tables inside of it.

© 2019 Software Development Academy. All Rights Reserved. 15


CREATE TABLE
The CREATE TABLE instruction allows you CREATE TABLE table_name(
to create a new table in the database. col1_name column_1_definition,
col2_name column_2_definition,
When creating a new table you need to //.,
[table_constraints]
provide the table name along with its
);
column names, column definition and
constraints.
Example:
The column definition refers to the CREATE TABLE owners(
column data type and properties. firstName VARCHAR(25) NOT NULL,
lastName VARCHAR(25) NOT NULL
);

© 2019 Software Development Academy. All Rights Reserved. 16


ALTER TABLE
The ALTER TABLE ADD statement allows ALTER TABLE table_name
you to add one or more columns to a ADD new_column_name column_definition;
table.
ALTER TABLE table_name
The ALTER TABLE DROP statement allows
DROP COLUMN column_name;
you to remove one or more columns from
a table.
ALTER TABLE table_name
The ALTER TABLE MODIFY statement MODIFY column_name column_definition;
allows you to update one or more
columns .
Example:
ALTER TABLE owners
ADD dateOfBirth DATE NOT NULL;

© 2019 Software Development Academy. All Rights Reserved. 17


DROP TABLE
The DROP TABLE statement removes a DROP TABLE table_name [, table_name];
table and its data permanently from the
database.
Example:
DROP TABLE owners;
In MySQL, you can also remove multiple
tables using a single DROP TABLE
statement, each table is separated by a
comma.

© 2019 Software Development Academy. All Rights Reserved. 18


Exercises
1. Create a new database: humanResources.
2. Create a new table employees, with the following columns:
a. employeeId - Integer,
b. firstName - Varchar,
c. lastName - Varchar,
d. dateOfBirth - Date,
e. postalAddress - Varchar.
3. Alter table employees and add the following columns:
a. phoneNumber - Varchar,
b. email - Varchar,
c. salary - Integer.
4. Alter table employees and remove the postalAddress column.
5. Create a new table employeeAddresses, with country - Varchar column.
6. Remove table employeeAddresses.

© 2019 Software Development Academy. All Rights Reserved. 19


DML - Data Manipulation Language

© 2019 Software Development Academy. All Rights Reserved. 20


INSERT INTO
The INSERT INTO statement allows you to INSERT INTO table_name(col1, col2,//.)
insert one or more rows into a table. VALUES (val1, val2, //.),
(val1’, val2’, …’),
First, specify the table name and a list of (val1’’, val2’’, …’’);
comma-separated column names inside
parentheses after the INSERT INTO Example:
clause. INSERT INTO owners
(firstName, lastName, dateOfBirth)
Then, put a comma-separated list of VALUES
values of the corresponding columns ('Jim', 'Jameson', '1980-01-01');
inside the parentheses following the
VALUES keyword.

© 2019 Software Development Academy. All Rights Reserved. 21


UPDATE
The UPDATE statement modifies existing UPDATE table_name
data in a table. SET
column_name1 = newVal1,
Firstly, specify the name of the table that column_name2 = newVal2,
//.
you want to update data after the
[WHERE condition];
UPDATE keyword.

Secondly, specify which column you want Example:


to update and the new value in the SET UPDATE owners
clause. SET firstName = 'James';

Thirdly, specify which rows to be updated


using a condition in the WHERE clause.
The WHERE clause is optional. If you omit
it, the UPDATE statement will update all
rows in the table.
© 2019 Software Development Academy. All Rights Reserved. 22
DELETE FROM
To delete data from a table, you can use DELETE FROM table_name
the DELETE FROM statement. [WHERE condition];

Firstly, specify the table from which you


Example:
delete data.
DELETE FROM owners;
Secondly, use a condition to specify which
rows to delete in the WHERE clause. If the
row matches the condition, it will be
deleted. Notice that the WHERE clause is
optional. If you omit it, the DELETE
statement will delete all rows in the table.

Besides deleting data from a table, the


DELETE statement returns the number of
rows deleted.
© 2019 Software Development Academy. All Rights Reserved. 23
Exercises
1. Insert a new entry into employees table:
a. employeeId - 1,
b. firstName - John,
c. lastName - Johnson,
d. dateOfBirth - 1975-01-01,
e. phoneNumber - 0-800-800-314,
f. email - john@johnson.com,
g. salary - 1000.
2. Update dateOfBirth of John Johnson to 1980-01-01.
3. Delete everything from employees table.
4. Add two more entries in employees:
a. 1, 'John', 'Johnson', '1975-01-01', '0-800-800-888', 'john@johnson.com', 1000
b. 2, 'James', 'Jameson', '1985-02-02', '0-800-800-999', 'james@jameson.com', 2000

© 2019 Software Development Academy. All Rights Reserved. 24


DQL - Data Query Language

© 2019 Software Development Academy. All Rights Reserved. 25


SELECT FROM
The SELECT statement allows you to read SELECT select_list
data from one or more tables. FROM table_name
[WHERE condition];
Firstly, you specify a list of columns or
SELECT * FROM table_name;
expressions that you want to show in the
- selects all columns from the table
result.
SELECT col1, col2 FROM table_name;
Then you specify the table that you want - selects only col1 and col2 from table
to select from.

Example:
SELECT * FROM owners;

© 2019 Software Development Academy. All Rights Reserved. 26


WHERE clause
The WHERE clause allows you to specify a SELECT select_list
search condition for the rows returned by FROM table_name
a query. WHERE condition;

By specifying a condition, the SELECT


instruction will no longer return all of the
results but only those that match the
specified condition.

The search condition is a combination of


one or more predicates using the logical
operator AND, OR and NOT.

© 2019 Software Development Academy. All Rights Reserved. 27


WHERE clause COMPARISON operators
The WHERE clause allows you to specify a SELECT select_list
number of comparison operators: FROM table_name
● a=b WHERE condition;
● a>b, a>b, a<=b, a>=b
● a IN (value1, value2, value3)
Example:
● a IS NULL, a IS NOT NULL SELECT *
● a!=b FROM owners
● a BETWEEN b AND c WHERE lastName = 'Johnson';
● a LIKE b

© 2019 Software Development Academy. All Rights Reserved. 28


WHERE clause LOGICAL operators
The WHERE clause allows you to specify SELECT select_list
logical operators that can be used to FROM table_name
combine multiple comparison operators: WHERE condition;
● AND
● OR
Example:
● NOT SELECT *
FROM owners
WHERE lastName = 'Johnson' AND firstName
= 'James';

© 2019 Software Development Academy. All Rights Reserved. 29


AGGREGATE functions
An aggregate function performs a SELECT AVG(col1)
calculation on multiple values and returns FROM tableName;
a single value:
● AVG - takes multiple numbers and SELECT SUM(col1)
FROM tableName;
returns the average value of the
numbers, SELECT MAX(col1)
● SUM - returns the summation of all FROM tableName;
values,
● MAX - returns the highest value, SELECT MIN(col1)
● MIN - returns the lowest value, FROM tableName;
● COUNT - returns the number of rows.
SELECT COUNT(*)
FROM tableName;

Example: SELECT COUNT(*) FROM owners;


© 2019 Software Development Academy. All Rights Reserved. 30
Exercises
1. Select everything from table employees.
2. Select only firstName and lastName from table employees.
3. Select all employees with lastName Johnson.
4. Select all employees whose lastName starts with J.
5. Select all employees whose lastName contains so.
6. Select all employees born after 1980.
7. Select all employees born after 1980 and whose firstName is John.
8. Select all employees born after 1980 or whose firstName is John.
9. Select all employees whose lastName is not Jameson.
10. Select maximum salary.
11. Select minimum salary.
12. Select average salary.

© 2019 Software Development Academy. All Rights Reserved. 31


PRIMARY and FOREIGN Keys

© 2019 Software Development Academy. All Rights Reserved. 32


Primary key

A primary key is a column or a set of columns that uniquely identifies each


row in the table.

A primary key must contain unique values. If the primary key consists of
multiple columns, the combination of values in these columns must be unique.

A primary key column cannot have NULL values.

A table can have one an only one primary key.

© 2019 Software Development Academy. All Rights Reserved. 33


Primary key

Because MySQL works faster with integers, the data type of the primary key
column should be integer e.g., INT, BIGINT. And you should ensure sure that
value ranges of the integer type for the primary key are sufficient for storing all
possible rows that the table might have.

A primary key column often has the AUTO_INCREMENT attribute that


automatically generates a sequential integer whenever you insert a new row
into the table.

© 2019 Software Development Academy. All Rights Reserved. 34


PRIMARY key
The PRIMARY KEY constraint allows you CREATE TABLE table_name (
to define a primary key of a table when primary_key_column INT
you create or alter table. AUTO_INCREMENT PRIMARY KEY NOT NULL,
col2 col2_definition,
col3 col3_definition,
Typically, you define the primary key for a
//.
table in the CREATE TABLE statement. );

If a table, for some reasons, does not ALTER TABLE table_name


have a primary key, you can use the ADD PRIMARY KEY(column_list);
ALTER TABLE statement to add a primary
key.
Example:
ALTER TABLE owners
ADD PRIMARY KEY(ownerId);

© 2019 Software Development Academy. All Rights Reserved. 35


Foreign key

A foreign key is a column or group of columns in a table that links to a column


or group of columns in another table. The foreign key places constraints in the
related tables, so MySQL can maintain referential integrity.

The table containing the foreign key is called the child table, and the
referenced table is the parent table.

Typically, the foreign key columns of the child table often refer to the primary
key columns of the parent table.

© 2019 Software Development Academy. All Rights Reserved. 36


Foreign key

A table can have more than one foreign key where each foreign key references
to a primary key of the different parent tables.

Once a foreign key constraint is in place, the foreign key columns from the
child table must have the corresponding row in the parent key columns of the
parent table or values in these foreign key columns must be NULL.

© 2019 Software Development Academy. All Rights Reserved. 37


FOREIGN key
Firstly, specify the name of the foreign CREATE TABLE table_name(
primaryKeyColumn INT AUTO_INCREMENT PRIMARY
key constraint that you want to create. KEY NOT NULL,
The foreign key name is optional and is col2 col2_definition,
generated automatically if you skip it. col3 col3_definition,
CONSTRAINT [foreign_key_name] FOREIGN KEY
(column_name, //.)
Secondly, specify a list of REFERENCES parent_table(colunm_name,//.)
comma-separated foreign key columns );

after the FOREIGN KEY keywords. Example:


CREATE TABLE pets (
petId INT NOT NULL AUTO_INCREMENT,
Thirdly, specify the parent table followed
race VARCHAR(45) NOT NULL,
by a list of comma-separated columns to dateOfBirth DATE NOT NULL,
which the foreign key columns reference. ownerId INT NOT NULL,
PRIMARY KEY (petId),
CONSTRAINT fk_pets_owners
Foreign key name is unique. As a best FOREIGN KEY (ownerId)
practice use: REFERENCES owners (ownerId));
fk_childTableName_parentTableNam
e © 2019 Software Development Academy. All Rights Reserved. 38
Exercises
1. Alter table employees:
a. make employeeId column PRIMARY KEY, NOT NULL and AUTO INCREMENT.
2. See what happens when you add two more entries in employees, this time without setting the
employeeId manually:
a. 'Julie', 'Juliette', '1990-01-01', '0-800-900-111', 'julie@juliette.com', 5000
b. 'Sofie', 'Sophia', '1987-02-03', '0-800-900-222', 'sofie@sophia.com', 1700
3. Create a new table departments, with columns:
a. departmentId - Integer, PRIMARY KEY, NOT NULL, AUTO INCREMENT
b. name - Varchar, NOT NULL
4. Add two entries in table departments:
a. HR,
b. Finance.
5. Connect the two tables together - employees should have a reference to departments:
a. add departmentId - Integer column to employees table,
b. assign John to HR and Julie to Finance.

© 2019 Software Development Academy. All Rights Reserved. 39


Exercises
6. Delete entry HR from departments table:
a. Does this work?
b. Should we be able to delete it? If John is assigned to HR and we delete, is the data still
correct?
7. Create a foreign key in employees table to departments table:
a. departmentId column in employees should reference departmentId column in
departments,
b. remember the naming convention: fk_employees_departments.
8. Now try to delete entry HR from departments table:
a. Does this still work?
9. Now try to add a new employee and set its departmentId to 10:
a. Does this work? Should it?
b. Try to add this new employee and set its departmentId to 1. Does this work?
10. Try deleting the newly added employee:
a. Does it work? Should it?

© 2019 Software Development Academy. All Rights Reserved. 40


Table relationships

© 2019 Software Development Academy. All Rights Reserved. 41


Relationships

When designing a database, common sense dictates that we use different


tables for different types of entities.

Take for example an online store which has information about: customers,
orders, items, etc. We would have separate tables for all of these. But we also
need to have relationships between these tables. For instance a customer can
place several orders, an order belongs to only one customer, an order can
contain multiple items. These relationships need to be represented in the
database.

© 2019 Software Development Academy. All Rights Reserved. 42


Relationships

There are several types of database relationships:


● One to One relationships,
● One to Many and Many to One relationships,
● Many to Many relationships,
● Self Referencing relationships.

© 2019 Software Development Academy. All Rights Reserved. 43


One-to-One
One-to-One relationships occur when
there is only one record in the first table
that corresponds to only one record in
the related table.

This is achieved by adding a foreign key


from the primary key in the first table to
the primary key in the second table.

Keep in mind that this kind of relationship


is not very common. It is usually simpler
to combine the two tables into a single Example: a person has a single passport and a
larger one. passport belongs to a single person.

© 2019 Software Development Academy. All Rights Reserved. 44


One-to-Many
One-to-Many relationship is defined as a
relationship between two tables where a
row from one table can have multiple
matching rows in another table.

In order to model this you need to


identify the table representing the many
side of the relationship and add an
additional column with a foreign key
referencing the primary key of the table
representing the one side of the
relationship. Example: a pet belongs to a single owner while
the owner can have multiple pets.

© 2019 Software Development Academy. All Rights Reserved. 45


Many-to-Many
Many-to-Many relationship occurs when
multiple records in one table are
associated with multiple records in
another table.

In order to model this you can break the


many-to-many relationship into two
one-to-many relationships by using a
third table, called a join table. Each record
in a join table includes a match field that
contains the value of the primary keys of
the two tables it joins (in the join table,
these match fields are foreign keys).
These foreign key fields are populated Example: an order can have multiple items and an
with data as records in the join table are item can belong to multiple orders.
created from either table it joins.
© 2019 Software Development Academy. All Rights Reserved. 46
Self-referencing
Self-referencing is a relationship that
exists between the records within a table.

A table bears a self-referencing


relationship (also known as a recursive
relationship) to itself when a given record
in the table is related to another record
within the table.

In order to model this you need to add an


additional column with a foreign key
referencing the primary key of the same
table. Example: a person has a father which is also a
person.

© 2019 Software Development Academy. All Rights Reserved. 47


Exercises
1. Identify the type of relationship between employees and departments tables.
2. Add additional functionality to the employees table by allowing a specific employee to have a
manager. How would you model this considering the fact that the manager should also be an
employee?
3. Make Sophie the manager of John and James.
4. Add additional functionality:
a. database will store project information as well, projectId and description,
b. design the database in such a way that an employee will be able to work on multiple
projects and also multiple employees can work on the same project
5. Insert two projects to the database:
a. Python - Cinema Web App,
b. Java - Fitness Web App.
6. Assign John and James to the Python project and Julie and Sofie to the Java project.

© 2019 Software Development Academy. All Rights Reserved. 48


Joins

© 2019 Software Development Academy. All Rights Reserved. 49


Joins

A SQL Join statement is used to combine data or rows from two or more
tables based on a common field between them:
● CROSS JOIN
● INNER JOIN
● LEFT JOIN
● RIGHT JOIN

© 2019 Software Development Academy. All Rights Reserved. 50


CROSS JOIN
CROSS JOIN matches each row from the SELECT * FROM table1 JOIN table2
first table with each row of the second
table. SELECT * FROM table1, table2

If each table had 4 rows, we should be


Example:
getting a result of 16 rows. SELECT * FROM owners
JOIN pets

© 2019 Software Development Academy. All Rights Reserved. 51


INNER JOIN
INNER JOIN selects all rows from both SELECT column_name(s)
tables as long as the condition is met. FROM table1
INNER JOIN table2
ON table1.column = table2.column

Example:
SELECT *
FROM pets
INNER JOIN owners
ON pets.ownerId = owners.ownerId

© 2019 Software Development Academy. All Rights Reserved. 52


LEFT JOIN
LEFT JOIN returns all the rows of the table SELECT column_name(s)
on the left side of the join and matching FROM table1
rows of the table on the right side of the LEFT JOIN table2
join. For the rows for which there is no ON table1.column = table2.column
matching row on right side, the result-set
will contain null. Example:
SELECT *
FROM pets
LEFT JOIN owners
ON pets.ownerId = owners.ownerId

© 2019 Software Development Academy. All Rights Reserved. 53


RIGHT JOIN
RIGHT JOIN returns all the rows of the SELECT column_name(s)
table on the right side of the join and FROM table1
matching rows of the table on the left RIGHT JOIN table2
side of join. For the rows for which there ON table1.column = table2.column
is no matching row on left side, the
result-set will contain null. Example:
SELECT *
FROM pets
RIGHT JOIN owners
ON pets.ownerId = owners.ownerId
Table A Table B

© 2019 Software Development Academy. All Rights Reserved. 54


Exercises
1. Write a query to display the firstName, lastName and department name for all employees.
2. Write a query to display the firstName and lastName of the employees assigned to a
department.
3. Write a query to display the firstName and lastName of the employees assigned to the HR
department.
4. Write a query to display all employees that haven’t been assigned to a department.
5. Write a query to display all employees that work on the Java project.
6. Write a query to display the firstName, lastName, department name and project name for all
of the employees that work in the HR department.
7. Write a query to display the firstName, lastName, department name and project name for all
of the employees that work on the Java project.
8. Write a query to display the firstName, lastName, department name and project name for all
of the employees that work on the Java project and their last name starts with J.
9. Write a query to display only the projects that have employees assigned to them.
10. Write a query to display the departments that don’t have any employees.

© 2019 Software Development Academy. All Rights Reserved. 55


SQL extras

© 2019 Software Development Academy. All Rights Reserved. 56


SQL extras
● ORDER BY - is used to sort the result-set in ascending or descending order:
○ SELECT column1, column2, … FROM table_name ORDER BY column1 [ASC|DESC];
● GROUP BY statement groups rows that have the same values into summary rows, like “find
the number of customers in each country”:
○ SELECT column1, column2, … FROM table_name GROUP BY column1;
○ SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country;
● HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions:
○ SELECT column1, column2, … FROM table_name GROUP BY column1 HAVING condition;
○ SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country HAVING
COUNT(CustomerID) > 5;
● Aliases are used to give a table, or a column in a table, a temporary name:
○ SELECT column1 as newName, column2, … FROM table_name;
○ SELECT COUNT(CustomerID) as Nr Of Cust, Country FROM Customers GROUP BY Country;
● LIMIT is used to restrict the number of results retrieved from the database:
○ SELECT * FROM table_name LIMIT 5;
© 2019 Software Development Academy. All Rights Reserved. 57
Database modelling exercises

© 2019 Software Development Academy. All Rights Reserved. 58


Cinema database
Let’s design a database which will store the relevant information needed to operate a cinema.

What kind of information do we need to store? What are the different concepts a cinema needs to
interact with?

How is that information connected? What are the relationships between the different datasets?

What business needs and what kind of processes does the database have to satisfy?

Think about the process you go through when you go to a cinema or book a ticket online:
● you need to see a list of movies and the times they run,
● you need to see if there are any available seats,
● you need to be able to make a reservation for one or more seats,
● you need to be able to buy a ticket.

How would you model all this?


© 2019 Software Development Academy. All Rights Reserved. 59
Cinema database - exercises
1. List all movies.
2. List all movies running on 2020-01-01.
3. List all movies that are not yet scheduled to run in the cinema.
4. List all movies reserved by John Johnson.
5. List all the seat rows and numbers reserved by John Johnson.
6. List all tickets sold for Joker.
7. List the number of adult and children tickets sold for Joker.
8. List the average number of tickets sold for each movie.
9. List the highest number of tickets sold for a movie.
10. List the unreserved seats for Joker.

Example schema for this database can be found here:


https://gitlab.com/sda-international/program/common/databases/-/wikis/uploads/47ab287a9cf2827626e368a383e0490e/cinemaDatabaseSchema.png
The SQL script to import it to your local MySQL server can be found here:
https://gitlab.com/sda-international/program/common/databases/-/blob/master/cinemaDatabaseStructure.sql

© 2019 Software Development Academy. All Rights Reserved. 60


SDA scheduler database
Let’s design a database which will store all the relevant information needed for scheduling SDA
activity.

Think about the trainers, students, teams, classrooms, modules and attendance list. There are
multiple students in a team. A trainer can teach one or multiple modules. A team can have classes
in one or multiple classrooms. For the attendance, we usually say that a student was or wasn’t
present on a particular day.

What’s the difference between trainers and students? Do we need multiple tables to store their
information or would one suffice?

If a team consists of multiple students but a student can only belong to one team what kind of
relationship would we use?

If a module represents a trainer teaching a specific topic, for a specific team, in a specific location,
between certain dates, how would you model this?
© 2019 Software Development Academy. All Rights Reserved. 61
SDA scheduler database - exercises
1. List all students.
2. List all students for team Python1Tallin.
3. List all groups that had classes in location BucharestCowork.
4. List all groups that had classes in location Tallin Cozy Space in March 2020.
5. List all students that already finished the SQL module.
6. List all students with 100% attendance rate.
7. List all trainers that teach Java Fundamentals.
8. List all trainers that teach at BucharestCowork location.
9. List all trainers that taught students with 100% attendance rate.
10. List the trainer that taught the highest number of modules.

Example schema for this database can be found here:


https://gitlab.com/sda-international/program/common/databases/-/wikis/uploads/601e7bb7222edbfd5435c4e8a3470cf9/sdaDatabaseSchema.png
The SQL script to import it to your local MySQL server can be found here:
https://gitlab.com/sda-international/program/common/databases/-/blob/master/sdaDatabaseStructure.sql

© 2019 Software Development Academy. All Rights Reserved. 62


Optional topics

© 2019 Software Development Academy. All Rights Reserved. 63


Transactions

A transaction is a logical unit of work that contains one or more SQL


statements.

Transactions are atomic units of work that can be committed or rolled back.
When a transaction makes multiple changes to the database, either all the
changes succeed when the transaction is committed, or all the changes are
undone when the transaction is rolled back.

© 2019 Software Development Academy. All Rights Reserved. 64


Transactions
MySQL provides us with the following START TRANSACTION;
important statement to control OPERATION1;
transactions: OPERATION2;
COMMIT;
● To start a transaction, you use the
START TRANSACTION statement. Example:
START TRANSACTION;
● To commit the current transaction INSERT INTO owners
and make its changes permanent, (ownerId, firstName, lastName, dateOfBirth)
you use the COMMIT statement. VALUES
(100, 'Mark', 'Markes', '1980-01-01');
INSERT INTO pets
● To roll back the current transaction (race, dateOfBirth, ownerId)
and cancel its changes, you use the VALUES
ROLLBACK statement. ('Labrador', '2020-01-01', 100);
COMMIT;

© 2019 Software Development Academy. All Rights Reserved. 65


ACID

The ACID model is a set of database design principles that emphasize aspects
of reliability that are important for business data and mission-critical
applications.

MySQL fully satisfies the ACID requirements for a transaction-safe relational


database.

© 2019 Software Development Academy. All Rights Reserved. 66


ACID

● Atomicity - either all of the operations of a transaction are performed


successfully or none of them is. Transaction cannot be divided.
● Consistency - after committing a transaction all data will be valid
according to database's rules.
● Isolation - all transactions are performed separately.
● Durability - once a transaction has been committed, the changes it made
will be persisted.

© 2019 Software Development Academy. All Rights Reserved. 67


Views

A view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view
are fields from one or more real tables in the database.

A view always shows up-to-date data. The database engine recreates the data,
using the view's SQL statement, every time a user queries a view.

© 2019 Software Development Academy. All Rights Reserved. 68


Views
MySQL provides us with option of CREATE VIEW viewName
repeatedly running the same complex AS
query without writing it multiple times. SELECT table1.col3, table1.col4
FROM table1
INNER JOIN table2
● To create a new view you use the
ON table1.col1 = table2.col2
CREATE VIEW statement.
SELECT * FROM viewName;
● To query the view you can just select
from the view name. Example:
CREATE VIEW petsWithOwners
AS
SELECT *
FROM pets
RIGHT JOIN owners
ON pets.ownerId = owners.ownerId;

SELECT * FROM petsWithOwners;


© 2019 Software Development Academy. All Rights Reserved. 69
Procedures

A procedure (often called a stored procedure) is a subroutine like a


subprogram in a regular computing language, stored in database. A procedure
has a name, a parameter list and SQL statements.

The procedures code can be reused over and over again.

You can also pass parameters to a stored procedure, so that the stored
procedure can act based on the parameter value that is passed.

© 2019 Software Development Academy. All Rights Reserved. 70


Procedures
● Wrap your procedure between the DELIMITER //
DELIMITERS
● Firstly, specify the name of the stored CREATE PROCEDURE procedureName(
procedure that you want to create [IN param1Name VARCHAR(255)]
)
after the CREATE PROCEDURE
BEGIN
keywords. INSTRUCTION1;
● Secondly, specify a list of INSTRUCTION2;
comma-separated parameters for the END //
stored procedure in parentheses after
the procedure name. DELIMITER ;
● Thirdly, write the code between the
BEGIN and END blocks.
● A procedure is triggered by the CALL
function. CALL procedureName(param1Value);

© 2019 Software Development Academy. All Rights Reserved. 71


Procedures
We can write a procedure to retrieve all DELIMITER //
of the pets for a particular owner. CREATE PROCEDURE GetPetsByOwner(
IN ownerFirstName VARCHAR(255)
)
BEGIN
SELECT *
FROM pets
INNER JOIN owners
ON pets.petId = owners.ownerId
WHERE owners.firstName =
ownerFirstName;
END //
DELIMITER ;

CALL GetPetsByOwner('Jim');

© 2019 Software Development Academy. All Rights Reserved. 72


Thank you for your attention!

© 2019 Software Development Academy. All Rights Reserved. 73

You might also like