0% found this document useful (0 votes)
3 views47 pages

Chapter 5 SQL

The document provides an overview of Structured Query Language (SQL), detailing its purpose in managing data within databases and its use across various Database Management Systems (DBMS). It covers the three main components of SQL: Data Query Language (DQL), Data Manipulation Language (DML), and Data Definition Language (DDL), along with examples of SQL commands for data retrieval, manipulation, and organization. Additionally, it discusses advanced SQL concepts such as joins, nested queries, and aggregate functions, providing practical examples throughout.

Uploaded by

hiba exol
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)
3 views47 pages

Chapter 5 SQL

The document provides an overview of Structured Query Language (SQL), detailing its purpose in managing data within databases and its use across various Database Management Systems (DBMS). It covers the three main components of SQL: Data Query Language (DQL), Data Manipulation Language (DML), and Data Definition Language (DDL), along with examples of SQL commands for data retrieval, manipulation, and organization. Additionally, it discusses advanced SQL concepts such as joins, nested queries, and aggregate functions, providing practical examples throughout.

Uploaded by

hiba exol
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/ 47

Data Base course

L2 computer-science
by Betouati fatiha
2024-2025
University Mostaganeme
Chapitre 05 : Structured Query Langage
(SQL)
Introduction
 SQL stands for Structured Query Language. It is a simple
programming language used to manage data in a database. It is
based on the relational model.

 All DBMS use SQL (ORACLE, MYSQL, SQL SERVER, DB2,


PARADOX, ACCESS, etc.).

 SQL offers a standardized interface for all Database


Management Systems (DBMS), regardless of their data storage
method
Introduction
SQL includes three different languages:

DQL (Data Query Language - DQL): This is the most


important part; it allows retrieving data that meet specific
criteria. Queries are made to the database to obtain relevant
data in response.

DML (Data Manipulation Language - DML): It enables


the deletion, addition, or modification of data.

 DDL (Data Definition Language - DDL): It defines the


structure of tables (creating tables, defining data types,
sizes, and attributs).
Data Query Language - DQL
A. Projection using simple queries

 Information retrieval in a database is performed using the SQL


SELECT command.

 The SELECT statement (or projection expression).

SYNTAX: SELECT field1, field2 …


FROM table;

 The selection formula uses the columns of the tables present in


the FROM clause.
Data Query Language - DQL
A. Projection using simple queries

Example:
Employee (N_empl, Last_Name, First_Name, Position, Birth_Date,
Hire_Date, Address, City, Region, Postal_Code).
R1: Display the Last Name and First Name of Employees?

SELECT Last_Name, First_Name


FROM Employee;

 This command displays all the fields from the Employee table.

SELECT *
FROM Employee;
Data Query Language - DQL

 The DISTINCT clause removes duplicate


records, keeping only unique ones.

SYNTAX : SELECT DISTINCT Field1, Field2, …


FROM table;

Example: Display all the cities where employees live.

SELECT DISTINCT city


FROM Employee;
Data Query Language - DQL
B. Selection (WHERE Clause)

In SQL, selections are expressed using the WHERE clause followed by


a logical condition, which can be defined using:
 Arithmetic operators: =, >, <, !=, <=, >=, +, -, /, * …
 Logical operators: AND, OR, NOT
 String comparison operators: IN, BETWEEN, LIKE, IS NULL …

Syntaxe : SELECT colunm name


FROM table-name
WHERE condition
Data Query Language - DQL
B. Sélection (clause WHERE)

Example: List of employees whose position is Sales Manager.

SELECT Last_Name, First_Name


FROM Employees
WHERE Position = ' Sales Manager’

B.1. Using the Attributes BETWEEN, IN, LIKE:

 BETWEEN: Used to check if an attribut value (character, date,


numeric) is between two values.

SELECT * FROM Employé


WHERE Birth_Date BETWEEN #01/01/2000# AND #01/01/2004#;
Data Query Language - DQL
B. Sélection (clause WHERE)

B.1. Using the Attributes BETWEEN, IN, LIKE:


 IN: Checks if the value of an attribut matches one of the specified
values in the list

 NOT IN: Checks if the value of an attribut does not match any of
the specified values in the list.

Example: List of employees who do not live in Algiers, Oran, or


Annaba.

SELECT *
FROM Employees
WHERE City NOT IN (' Algiers’, 'Oran', 'Annaba');
Data Query Language - DQL
 LIKE: Selects records by comparing the value of a character-type
attribute to a specified string.

Note:
The character * (or %) represents any number of characters.
The character ? represents a single arbitrary character.

Example 1: List of employees whose name starts with 'Bet':

SELECT Last_Name, First_Name


FROM Employees
Where Last_Name like "Bet*";
Data Query Language - DQL
C. Use of expressions in SELECT
 In SELECT, you can define a new column (calculated
column) and insert descriptive instructions
SELECT *, salary*0.10 as [New_salary]
FROM Employees;

Note: The keyword AS is used to assign an alias to a column.


This allows you to temporarily rename a column to make the query
result more readable.
Example: Expression on character strings
Display the Last name and first name of employees in a single
column.
SELECT Last _name +" "+ first _name as [Name]
FROM Employees;
Data Query Language - DQL
D: Use of Functions
There are three main types of functions in SQL:
 Mathematical functions (also known as aggregate functions),
 Date functions,
 String functions.

D.1.aggregate functions

Aggregate functions are used in the SELECT clause; they apply to a


calculated or non-calculated attribute. They perform a calculation
on all the values of that attribute and produce a single result.
Data Query Language - DQL
D.1.aggregate functions
The 5 aggregate functions are:
Min(field): returns the minimum value of the field,
Max(field): returns the maximum value of the field,
Count(field): returns the number of values in the field (equivalent to
the number of records)
Avg(field): returns the average of all values in the field (average =
moyenne),
Sum(field): returns the sum of all values in the field.
Data Query Language - DQL
D.1.aggregate functions
Example:
Book (Book_ID, Title, Purchase_Date, Price, Reading_Date, Collection, Printing_Year, Pages,
AuthorId*)

Q1: Provide the maximum, minimum, and average number of pages of the books.
SELECT max (Pages) as [Max], min (pages) as [Min], avg (pages) as [average]
FROM Book;

Exercise: Write the following queries


1. Number of books in the Library database?
2. Purchase date of my first book?
3. Price of the most expensive book?
4. Title of the least expensive book?
5. Average price of the books?
Data Query Language - DQL
D.2. Date Functions

Date constants are enclosed with # to distinguish them from numeric expressions.
Example 1: #24/05/2012#

Among the date functions, we have:


 YEAR(), MONTH(), DAY(): These extract the year, month, and day respectively
from a date value.
 DATE(): Returns the current system date.
 DateDiff(): Calculates the difference between two dates.

Example:
SELECT DAY(date_birth) AS date_Birth
FROM employees;
Data Query Language - DQL
Query: Get the age of each employees

select year(date())-year(date_Birth) As age


from employees;
Note: We can calculate the age of an employee using DateDiff():
DATEDIFF(date_part, start_date, end_date)
SELECT DATEDIFF('yyyy', date_Birth, DATE()) AS age
FROM employees;

Date Calculations:
•DATE() : returns today's date.
•DATE() + 1 : returns tomorrow's date.
•DATE() - 1 : returns yesterday's date.
Data Query Language - DQL
Exercise:
 Which books were purchased last year?
 List of employees hired in 2001?
 Extract the day from the current date?
 Which books have you read in the last seven days?

D.3. String Functions:

LEN(): This function returns the length of a string.


Example:
SELECT LEN(Nom) AS NameLength FROM employees;
Data Query Language - DQL
D.3. String Functions:

LEFT(): This function extracts a specified number of characters from


the beginning of a string (attribute).

SELECT LEFT(first_name, 3) AS Initials FROM employees;

Query: Get the number of employees in the Wilaya of Algiers.

SELECT Count (*)


From employees
Where left (postal_code, 2) = ‘16’;
Data Query Language - DQL
RIGHT(): This function extracts a specified number of characters
from the end of a string.
SELECT RIGHT(First_name, 3) AS LastCharacters FROM employees;

SUBSTR(): This function extracts a specified part of a string.


In MS Access, use the MID() function instead:

SELECT MID(nom, 2, 3) AS MiddlePart FROM employees;


Data Query Language - DQL
E. Sorting Data: ORDER BY
The "ORDER BY" clause allows sorting the records of a table based
on one or more attributes in ascending (ASC) or descending (DESC)
order.
Note: By default, sorting is in ascending (ASC) order.
Example 1: List of employees in alphabetical order.

SELECT First_name, Last_name


FROM employees
ORDER BY First_name, Last_name ; -- or ORDER BY 1, 2
Example 2: Sort book titles in descending order for books purchased before
2024
SELECT Title
FROM Book
WHERE YEAR(Purchase_Date) < 2024
ORDER BY titre DESC;
Data Query Language - DQL
F. Grouping Records – GROUP BY

 The GROUP BY clause allows us to partition the tuples of a


relation in order to form groups of tuples based on a grouping
criterion.

 You can apply aggregation functions to each group to calculate


aggregated values such as SUM, COUNT, AVG, etc.
SELECT column1, function(column2)
FROM table
GROUP BY column1
Note: Every attribute listed in the SELECT clause must also appear
the GROUP BY clause.
Data Query Language - DQL
Example: Suppose we have a table Sales with the following attributs:
Product, Quantity, UnitPrice.
The result of this query will be
Product Quantity UnitPrice
Laptop 3 1000
Mouse 10 25 Product TotalSales
Keyboard 5 50 Laptop 5200
Laptop 2 1100 Mouse 430
Mouse 6 30 Keyboard 250

Query: Give the total sales for each product

SELECT Product, SUM(Quantity * UnitPrice) AS TotalSales


FROM Sales
GROUP BY Product;
Data Query Language - DQL
F.1. Having Clause
 The HAVING condition in SQL is almost similar to WHERE,
with the only difference being that HAVING allows filtering of
groups using functions such as: SUM(), COUNT(), AVG(), MIN(),
or MAX().

 Only the groups for which the condition specified in the HAVING
clause is true will be included in the final result.

Syntax:
SELECT column1, function(column2)
FROM table_name
GROUP BY column1
HAVING function(column2) operator value
Data Query Language - DQL
Example:
Query: Give the total sales for each product where the total sales
amount is greater than 100.

SELECT Product, SUM(Quantity * UnitPrice) AS


TotalSales
FROM Sales
GROUP BY Product
HAVING SUM(Quantity * UnitPrice) > 300;

Product TotalSales
Laptop 5200
Mouse 430
Data Query Language - DQL
G: Multi-table Selection Queries (Joins)

 A join creates a connection between two tables based on the


equality of an attribute from each table (natural join).

G.1. Join between 2 tables:

Syntax:
SELECT field1, field2, ...
FROM table1, table2
WHERE table1.field1 = table2.field2;
Note: field1 must be a primary key in table1 and field2 a foreign key
in table2, or vice versa.
Data Query Language - DQL
Example 1: List of orders with dates and sellers (the seller is an
employee)
Employees (N_empl, Last_Name, First_Name, Birth_Date, ...)
Order (Order_Num, Client_Code*, Order_Date, N_empl*, ...)

SELECT Order_Num, Order_Date, Last_Name, First_Name


FROM Employees E, Order C
WHERE E.N_empl = C.N_empl;

 With E as an alias for the Employee table and C as an alias for the
Order table.
Example 2: Display the number of sales per seller
Data Query Language - DQL
G: Multi-table Selection Queries (Joins)

Note: The join can be expressed in the following form:

SYNTAX 2:

SELECT field1, field2, …


FROM table1 JOIN table2 ON table1.field1 = table2.field2

SELECT Name, Order_Num


FROM Employee E JOIN Order C
ON (E.N_empl = C.N_empl);
Data Query Language - DQL
G.3. Joining a Table with Itself (Self-Join)

 A self-join, also known as an internal join of a table with itself, is


an operation where a table is joined (or combined) with itself in
an SQL query.

Example: Retrieve the name of each employee and the name of


their supervisor.
Emp_ID Name Supervisor_ID
1 Alice NULL
2 Bob 1
3 Charlie 1
4 Diana 2
Data Query Language - DQL
G.3. Joining a Table with Itself (Self-Join)

SELECT
E.Name AS Employee_Name,
S.Name AS Supervisor_Name
FROM
Employee E JOIN Employee S ON E.Supervisor_ID = S.Emp_ID;

Employee_Name Supervisor_Name
Bob Alice
Charlie Alice
Diana Bob
Data Query Language - DQL
H. Nested Queries:

 Nested queries, also known as subqueries, are SQL queries that


are embedded inside another SQL query.

Example 1: Retrieve all orders made by the seller named ‘Rayene’


(order number and order date), sorted by date.

SELECT Order_Num, Order_Date


FROM Orders
WHERE N_empl = (
SELECT N_empl FROM employees
WHERE first_namey = ‘Rayene'
)
ORDER BY Order_Date;
Data Query Language - DQL
Example 2: List of sellers hired before the employee named ‘ALI’.
Employee table: (Emp_ID, Name, Position, Birth_Date, Hire_Date, ...)

SELECT Emp_ID, Name, Hire_Date


FROM Employee
WHERE Hire_Date < (
SELECT Hire_Date
FROM Employee
WHERE Name = 'ALI'
)
ORDER BY Name;
Data Query Language - DQL
H.2. Nested Queries Returning Multiple Values:

Example: Provide a list of orders and clients from the Wilaya of Algiers.
 Client (Client_Code, Company, ..., Postal_Code, ...)
 Order (Order_Num, Order_Date, Client_Code,* Emp_ID*, ...)
You can use nested queries to join two queries.

SELECT Order_Num, Client_Code, Order_Date


FROM Orders
WHERE Client_Code IN (
SELECT Client_Code
FROM Client
WHERE Postal_Code LIKE '16%'
)
ORDER BY Order_Num;
Data Query Language - DQL
J. Intersection

 In SQL, the INTERSECT operation is used to retrieve records that


appear in both result sets of two separate queries.

SELECT column1, column2, ...


FROM table1
INTERSECT
SELECT column1, column2, ...
FROM table2;

Example:
Employees (ID, Name, Dept_ID*)
Departments (Dept_ID, Name)
Data Query Language - DQL
Query: Find the employees who work in both the “IT" department
and the "Finance department.
Dept_ID Name ID Name Dept_ID
10 HR 1 Alice 10
20 IT 2 Bob 20
30 Finance 3 Charlie 10

SELECT ID, Name


FROM Employees E, Departments D
WHERE E.Dept_ID = D.Dept_ID AND D.Name = ‘IT'
INTERSECT
SELECT ID, Name
FROM Employees E, Departments D
WHERE E.Dept_ID = D.Dept_ID AND D.Name =
‘Finance';
Data Query Language - DQL
J. Intersection
Using Subqueries
Alternatively, you can use subqueries to achieve the same result:
sql

SELECT ID, Name


FROM Employees
WHERE Dept_ID IN
(SELECT Dept_ID FROM Departments WHERE Name = 'IT')
AND Dept_ID IN
(SELECT Dept_ID FROM Departments WHERE Name = 'Finance');

Note: This query selects employees who belong to both the "IT" and
"Finance " departments by checking that their Dept_ID appears in both
subqueries.
Data Query Language - DQL
K. Difference with the MINUS clause
The difference can be expressed in certain versions of SQL using the
MINUS clause.

Query: Find employees who work in the "Sales" department but not
in the "HR" department.

SELECT ID, Name


FROM Employees E, Departments D
WHERE E.IDdep = D.IDdep AND D.Name = 'Sales'
MINUS
SELECT ID, Name
FROM Employees
WHERE IDdep = (SELECT IDdep FROM Departments
WHERE Name = 'HR');
Data Query Language - DQL
K. Difference with the Not in clause

SELECT E.ID, E.Name


FROM Employees E, Departments D
WHERE E.Dept_ID = D.Dept_ID AND D.Name = 'Sales'
AND E.ID NOT IN (
SELECT E1.ID
FROM Employees E1, Departments D1
WHERE E1.Dept_ID = D1.Dept_ID AND D1.Name = 'HR'
);
Data Query Language - DQL
K. Difference with the NOT EXISTS clause

SELECT E.ID, E.Name


FROM Employees E, Departments D
WHERE E.Dept_ID = D.Dept_ID AND D.Name = 'Sales'
AND NOT EXISTS (
SELECT *
FROM Employees E1, Departments D1
WHERE E1.Dept_ID = D1.Dept_ID
AND D1.Name = 'HR'
AND E.ID = E1.ID
);
Data Query Language - DQL
L. Division

 SQL does not have a specific operator for division, but we can
express the semantics of this algebraic operator using logical
operators.
Example: Find employees who are assigned to all departments with
the same name.
SELECT ID, Name
FROM Employees E
WHERE NOT EXISTS (
SELECT *
FROM Departments D
WHERE NOT EXISTS (
SELECT ID
FROM Employees E2
WHERE E2.Dept_ID = D.Dept_ID
AND E2.ID = E.ID)
);
Data Manipulation Queries (DML language):
A) Insertion Query: SQL allows you to insert data into a table.
INSERT INTO TABLE VALUES (val1, val2, …, valn);

Let's assume we have a table Employees with columns (Name, Age,


Salary)
INSERT INTO Employees VALUES ('Abed Mostapha', 30, 45000);

B) Inserting an Incomplete Record


Example: Let's assume we have a table Employees with columns
(Name, Age, Salary)
INSERT INTO table (field1, field2, ..., fieldn) VALUES (val1, val2,.,
valn);

INSERT INTO Employees(Name, Age) VALUES ('Mohamed', 40);


Data Manipulation Queries (DML language):
C) Modifying Records
C.1) In a Single Table:

SYNTAX:
UPDATE <table name>
SET <attribute name> = <value>
WHERE <condition>;

Example: Increase the salary of the employee Abed Mostapha by 10%

UPDATE employees
SET salaire = salary * 10 / 100
WHERE nom = 'Abed Mostapha';
Data Manipulation Queries (DML language):
C) Modifying Records
C.2) In Multiple Tables:
UPDATE table1, table2, ..., table_n
SET field1 = value1, field2 = value2,
...
WHERE join_condition
AND other_conditions;
Example: Given the tables:
AUTHOR (Num_AUT, lastName, FirstName, BirthDate, DateOfDeath)
BOOK(Num_book, Title, PurchaseDate, Price, ReadingDate, Num_AUT)
Query: Remove the value of ReadingDate from all books written by the author HUGO.

UPDATE BOOK B, AUYHOR A


SET B.ReadingDate = NULL
WHERE A.Num_AUT = B.Num_AUT
AND A. lastName = 'HUGO';
Data Manipulation Queries (DML language):
D) Deleting a Record:
SYNTAX
DELETE
FROM <Table Name>
WHERE <Condition>;
Example: Delete the record corresponding to the employee Abed
Mostapha.

DELETE
FROM Employees
WHERE FistNom = 'Abed and LastName=‘ Mostapha';
Data Definition Language (DDL)
 It is used to define the structure of the database tables: specifying
table names, attributs, their types, properties, integrity constraints,
primary keys, foreign keys, value constraints, and mandatory
constraints.
1. Creating a Table:
SYNTAX: CREATE TABLE <table_name> ( attribute1 type1 [PRIMARY
KEY], attribute2 type2, ...);
Commonly used data types include:

 Char(length) – Fixed-length character string


 Integer – Whole numbers
 Currency – Monetary values
 Float – Floating-point numbers
 Date – Date values
 Counter – Auto-incrementing number (Auto Number)
Data Definition Language (DDL)
CREATE TABLE T3 (
id COUNTER PRIMARY KEY,
nom CHAR,
salary CURRENCY
);
2. Deleting a Table:
SYNTAX: DROP TABLE <table_name>;

Example: Delete the table employees.

DROP TABLE employees;


Data Definition Language (DDL)
3. Modifying the Structure of a Table:

 Modifying a table means adding, changing, or deleting fields


(columns) in a table.
3.1. Adding an attribut
SYNTAX: ALTER TABLE <table_name>
ADD COLUMN (attribute1 type1);

Example: ALTER TABLE T3 ADD COLUMN age INTEGER;


Data Definition Language (DDL)
3.2. Modifying an attribut:
This involves changing the data type of an attribut.

SYNTAX:
ALTER TABLE <table_name>
ALTER COLUMN attribute type;
Example: ALTER TABLE T3 ALTER COLUMN salaire FLOAT;
3.3. Deleting a Field:

SYNTAX: ALTER TABLE <table_name> DROP COLUMN field;

Example: ALTER TABLE T3 DROP COLUMN salary;

You might also like