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

MCIT DB SQL

The document provides an introduction to database fundamentals and SQL, covering topics such as database definitions, testing methodologies, entity relationship diagrams (ERD), and SQL commands. It details the limitations of file-based systems, the structure of databases, and the mapping of ERD to tables, as well as installation instructions for MySQL and various SQL commands including DDL, DCL, and DML. Additionally, it discusses different types of joins, subqueries, and aggregate functions in SQL.

Uploaded by

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

MCIT DB SQL

The document provides an introduction to database fundamentals and SQL, covering topics such as database definitions, testing methodologies, entity relationship diagrams (ERD), and SQL commands. It details the limitations of file-based systems, the structure of databases, and the mapping of ERD to tables, as well as installation instructions for MySQL and various SQL commands including DDL, DCL, and DML. Additionally, it discusses different types of joins, subqueries, and aggregate functions in SQL.

Uploaded by

Ahmed Mawrdy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

9/27/2024 1

INTRODUCTION TO DATABASE SQL


FUNDAMENTALS
INTRODUCTION TO DATABASE
Agenda:
1- Database Fundamentals:
▪ What is Database?
▪ What do we test?
▪ Entity Relationship Diagram.
▪ Mapping ERD to Tables.

2- Introduction to SQL:
▪ What is SQL.
▪ Preparing MySQL Environment.
▪ Data Definition Language (DDL)
▪ Data Control Language (DCL)
▪ Data Manipulation Language (DML)
File Based System Limitations:

▪ Separation and Isolation of Data.


▪ Duplication of Data.
▪ Program Data dependence.
What is Database?
What is Database?
Database: A Collection of Related Data.​

Database Management System (DBMS): A Software that facilitates the creation


and maintenance of a computerized database.

Database System: DBMS with the data itself (Software + Database).​


What do we test?
1 Structural Database Testing.
(Example: Mapping between tables and Entities).

2 Functional Database Testing.


(Example: Validating Null values, Length of values).

3 Non-functional testing.
(Example: Stress testing).
Entity Relationship Diagram (ERD):
It identifies information required by the business by displaying the relevant
Entities and Relationships between them.

Entity: it’s a thing in the real world with independent existence and can
be described with a set of attributes.
Entity Relationship Diagram (ERD):
There should be always relationships between entities and there shouldn’t
be an entity without any relationship.
Attributes:
1Single or simple Attributes. (Ex: ID, SSN).

2Multi Valued Attribute (Ex: Hobbies).

3- Composite Attribute (Ex: Name).

4Derived Attribute (Ex: Age) can be calculated from


another attribute.

5Candidate Keys: the unique identifiers attributes for


each entity (SSN)
Strong Entity:
It has a unique identifier or a key attribute.
It’s represented in a single rectangle.

Weak Entity:
It doesn’t have a key attribute.
It must be fully dependent on another entity.
It’s represented in a double rectangle.
Relationships:
For each relationship, We need to identify:
1- Degree of relationship
2- Cardinality
3- Participation
Degree of relationship:
It’s the number of participating entities.
Binary Relationship Unary Relationship Ternary Relationship
(Two Entities) (Entity and itself) (Three Entities)
Cardinality
It specifies the maximum number of relationships.

The relationship of D1 in Department to E1 and E2 in Employee


can be defined as One-to-Many.

Similarly, The Relationship of E3 in Employee to D2 in Department


can be defined as One-to-One.
Cardinality

One to One One to Many Many to One Many to Many


Participation
It specifies the minimum number of relationships instances that each entity can participate with.

Must May

It means that every student must have It means that courses may have
enrolled at least in one course students enrolled in it
Relationships
For each relationship, We need to identify:

Degree of relationship Cardinality Participation

It’s the number of It specifies the maximum It specifies the minimum


participating entities. number of relationships. number of relationships
instances that each entity can
1Binary Relationship (Two 1 to 1 participate with.
Entities) 1 to Many
2Unary Relationship (Entity Many to Many Must (Double Lines)
and itself) Many to 1 May (Single Line)
3Ternary Relationship (Three
Entities)
4N-ary Relationship
Tables:
In relational database terms, a table is responsible for storing data in the database. Database
tables consist of rows(records) and columns.

Every Table should have a primary key (may be one column or more than one column).
Primary Key:
A column which values are unique.
Can’t contain null values.
Database Constraints:
1 Primary Key Constraints:
Not Null.
Unique.

2 Not Null. (Enforces the field to have a value).

3 Unique Key. (All values in the column are different).

4 Check Constraints. (Check constraints on a salary column Minimum 1000, Max 2000).
Mapping ERD To Tables
1- Mapping Strong Entity:
1Single or Separate attributes are represented by separate columns.

2Composite Attributes (Each sub part of Composite attribute is represented by a column (first
name, Last name).

3Primary key is chosen from the candidate key (Shortest Unique combination in storage) if we
have more than one candidate key, we choose the less in storage (Numbers is chosen over text –
less storage-
1- Mapping Strong Entity:
4Multi valued attribute is made in a new table person-Hobbies (Primary key of Person as a
foreign Key & Hobbies Column), and the combination of the FK and the Hobbies are the
primary key of this table.

5Derived Attribute usually we don’t store it in our DB, however each time we need to deal with
it, it will be called and the calculation will be processed which may affect our performance in
the DB system. So we would store it in our DB if we use it frequently.
1- Mapping Strong Entity:
Person (SSN, Address, First_Name, Last_Name, BirthDate)

Person-Hobbies (SSN, Hobby_ID)


2- Mapping Weak Entity:
▪ Add the PK of the owner Entity as a FK in the table of the weak entity.
▪ Combination of FK with any other Column as a PK for the Weak entity table.

Dependents(employee_id, dependent_name)
3- Mapping One to Many Relationship:
▪ Binary: Adding PK of one side as a FK in Many side (PK of customer as FK in order).

▪ Order(order_id, order_date, customer_id)


3- Mapping One to Many Relationship:
▪ Unary: Adding the PK of one side as a FK in Many side (in case the Unary relationship, the PK
will be same as they are the same entity, so we would change the name of the FK in any
other name so we can know what it actually represents.

▪ Employee(employee_id, name, salary, manager_id).


4- Mapping Many to Many Relationship:
▪ We take the PK for the participating Entities and
make them as FK in a new table representing this
relationship.

▪ The combination of both of FKs will be the PK of this


new table.

▪ In case there is an attribute on the Relationship itself,


it will be added to this table alongside with both FKs.

▪ joinedInTable(student_id, course_id, joining_date).


5- Mapping One to One Relationship:
▪ It depends on the Participation Type.

May-Must:
▪ PK of May side as a FK in the Must side.
▪ License(license_id, license_date, person_id)

Must-Must:
▪ We merge both tables in a new table and we can
choose any PK of them as a new PK of the new
Table.

▪ Customer(custID, Name, NIC, DOB, CardID,


ExpDate, Type, CardNO, StartDate)
5- Mapping One to One Relationship:
May-May
We can apply one of these 3 options:

▪ Taking the PK of first side as a FK in the second side.


▪ Taking the PK of the second side as a FK in the first side.
▪ Taking the PKs of both sides as FKs and make a new table representing the relationship of them,
Combination of them is the PK.

-First 2 options are recommended.

Student(student_id, name, course_id)


Or
Course(course_id, course_name, student_id)
6- Mapping Ternary Relationship:
▪ We ignore the cardinality or the participation of the relationship.

▪ We create a new table representing the relationship with the PKs


of each participating entity as a FK in the new table.

▪ Prescribtions(doctor_id, medicine_id, patient_id)


INTRODUCTION TO SQL
Installing MySQL:
On this link drive please download the following

1. Install visual studio 2019 or 2017.


2. Install MySQL for Visual studio.
3. Install python if not installed on your machine.
4. Install MySQL connector python.
5. Install MySQL installer Web community and follow the next steps.
Installing MySQL cont.:
Installing MySQL cont.:
Installing MySQL cont.:
Installing MySQL cont.:
Installing MySQL cont.:
Installing MySQL cont.:

Then click next until you get to


This page.

Then enter a password.


Installing MySQL cont.:
Click on Execute
Installing MySQL cont.:

Click Next and Finish until you get here.


Then enter Your Password, Then Click on Check then Next. Then Next and Finish Again.
Installing MySQL cont.:

Finally you should get to this page, click finish.


Installing MySQL cont.:
SQL and MySQL:
SQL stands for Structured Query Language.

SQL is a query language, whereas MySQL is a relational DBMS that uses SQL to query a
database.

You can use SQL to access, update, and manipulate the data stored in a database. However,
MySQL is a database that stores the existing data in a database in an organized manner.

SQL is used for writing queries for databases, MySQL facilitates data storing, modifying, and
management in a tabular format.
SQL Syntax
▪ SQL follows some unique set of rules and guidelines called syntax. Here, we are providing
all the basic SQL syntax.

▪ SQL is not case sensitive. Generally SQL keywords are written in uppercases.

▪ You can perform most of the action in a database with SQL statements.

SQL Commands:
Data Definition Language (DDL):
▪ It’s used to create and modify the structure of database objects in a database.

▪ It’s used to Create, Edit and Delete objects.

❑ CREATE
❑ ALTER
❑ DROP
❑ TRUNCATE
❑ RENAME
CREATE
It’s used to create Tables Or Database

Col Data
Constraint
Name Type(size)
ALTER TABLE
It is used to add, delete, modify or rename columns in an existing table.

DROP COLUMN
It’s used to delete a column in the table.
MODIFY COLUMN
It’s used to change the data type of a column.

RENAME COLUMN
It’s used to RENAME an existing COLUMN in a database.
DROP TABLE
used to delete an existing table in a database.

TRUNCATE TABLE
used to delete the data inside a table, but not the table itself.
Data Control Language (DCL):
It’s used to give access privileges to the data.

GRANT
▪ It gives DML privileges to certain users.

REVOKE
▪ It removes the privileges given to certain users.
For More Info and Examples about Revoke:
https://www.mysqltutorial.org/mysql-revoke.aspx
Data Manipulation Language(DML):
It’s used to access and manipulate data in existing tables.
INSERT
It’s used to insert a record in the table.

There are 2 ways to insert our data.


UPDATE
It’s used to modify the existing records in a table.

Note:
If WHERE Clause isn’t written, All records in the table will be updated.
DELETE
It’s used to delete existing records in a table.

Note:
If WHERE Clause isn’t written, All records in the table will be deleted.
Difference between DELETE and TRUNCATE
DELETE TRUNCATE
Syntax: Syntax:
DELETE FROM Table_Name; TRUNCATE TABLE Table_Name;
or
DELETE FROM Table_Name
WHERE Condition;

Delete all the data and keeps the structure of the Delete all the data and keeps the structure of the
table (If WHERE Clause isn’t used) table.

Removes the rows one by one so it’s slower. It actually Deletes the table at once and creates a
new one. So it’s faster.

WHERE Clause can be used WHERE Clause can’t be user(No conditions)


SELECT
It’s used to select data from a database.

▪ It selects Columns ID and First_Name Only.

▪ It selects all Columns that have Hassan.

▪ It selects all the table content.


OPERATORS
Operators
Comparison Operators
2- Logical Operators
1- AND, OR
2- Logical Operators
1- AND, OR
2- Logical Operators
2- Between
2- Logical Operators
3- IN
2- Logical Operators
4- LIKE

▪This will get any first name that has


letter h in the middle of the name

▪This will get any first name that has


letter h after 2 chars and any number
of chars of it.
2- Logical Operators
5- NOT
ALIAS
ORDER BY
DISTINCT

▪ SELECT DISTINCT eliminates duplications in the columns.

▪ When two or more columns are mentioned after DISTINCT, it returns values that aren’t
duplicated for both of the columns together.
Assignment:

▪ Now we need to add a database table to apply our queries on it for


this assignment.
▪ Please download the SQL script file that is attached with the
material.

• To add a SQL script to your MySQL workbench, please follow steps in


this video:

1. From products table: Return all the products with these columns
(name, unit price, new price [unit price*1.1]).
JOINS
SQL JOINs
▪ A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
JOIN Types:
INNER JOIN
▪ It returns records that have matching values in both tables.
▪ We can get these common records using two methods as mentioned below.
USING Clause
INNER JOIN
▪ INNER JOIN 3 tables:
INNER JOIN
▪ INNER JOIN 3 tables:
INNER JOIN
▪ INNER JOIN 3 tables:
OUTER JOINs
▪ OUTER JOIN is classified into 3 main types.
LEFT JOIN
▪ It returns all records from the left table (table1), and the matching records from the right table (table2).
The result is 0 records from the right side, if there is no match.
LEFT JOIN (Inclusive)
LEFT JOIN (Exclusive)
RIGHT JOIN
▪ It returns all records from the right table (table2), and the matching records from the left table (table1).
The result is 0 records from the left side, if there is no match.
RIGHT JOIN (Inclusive)
RIGHT JOIN (Exclusive)
SELF JOIN
▪ A self join is a regular join, but the table is joined with itself.
SELF JOIN
▪ We handle them as two separate tables, the first one for the employees and the other is for the managers.
SELF JOIN
▪ A self join is a regular join, but the table is joined with itself.
CROSS JOIN
▪ It JOINS tables by matching every row from one table with every row from another table. If there are
X rows in the first table, and Y rows in the second table, the result set will have exactly X times Y rows.
UNION
▪ It JOINS tables by matching every row from one table with every row from another table. If there are
X rows in the first table, and Y rows in the second table, the result set will have exactly X times Y rows.
UNION
▪ It JOINS tables by matching every row from one table with every row from another table. If there are
X rows in the first table, and Y rows in the second table, the result set will have exactly X times Y rows.
FULL JOIN
▪ It returns all records when there is a match in left (table1) or right (table2) table records.

**It’s not supported by MySQL but supported by SQL server.


FULL JOIN
▪ IN MySQL we can use UNIONs to emulate the functionality of FULL OUTER JOIN.
▪ We should use UNION ALL to avoid removing duplicates.
Exercise:
▪ Display all columns in customers table and orders table using UNION ALL.
Exercise:
▪ Display all columns in customers table and orders table using UNION ALL.
Sub Queries
▪ A MySQL subquery is a query nested within another query.

▪ It’s used when we want to get something in reference to something else.


All (TRUE if all of the subquery values meet the
condition)
▪ All is a multi row operator, we should use it when a
SubQuery will provide more than one result.

▪ It means that the condition will be true only if the


operation is true for all values in the range.

▪ Office_id 2 employees:
ANY (TRUE if any of the subquery values meet the
condition)
▪ ANY is a multi row operator, we should use it when a
subQuery will provide more than one result.

▪ It means that the condition will be true if the operation


is true for any of the values in the range.

▪ Office_id 5 employees :
AGGREGATE functions
▪ COUNT() >> It doesn’t count NULL values
▪ MAX()
▪ MIN()
▪ AVG() >> It doesn’t take into consideration the NULL values.
▪ SUM()
GROUP BY
▪ It groups rows that have the same values in a certain column.
▪ It is often used with aggregate functions to group the result-set
by one or more columns.
Exercise:
▪ Display customer_id, first_name and number of orders for each customer and order them by number of
orders.
Exercise:
▪ Display customer_id, first_name and number of orders for each customer and order them by number of
orders.
HAVING
▪ It is a condition used with Aggregate functions instead of WHERE.
Exercise:
▪ Display the office_id, maximum salary, avg salary and the city for each department, given that its average
should be greater than 90000, and sort them by office_id.
Exercise:
▪ Display the office_id, maximum salary, avg salary and the city for each department, given that its average
should be greater than 90000, and sort them by office_id.
Order of operations:
THANK YOU!

You might also like