Chapter 5 SQL
Chapter 5 SQL
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.
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?
This command displays all the fields from the Employee table.
SELECT *
FROM Employee;
Data Query Language - DQL
NOT IN: Checks if the value of an attribut does not match any of
the specified values in the list.
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.
D.1.aggregate functions
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;
Date constants are enclosed with # to distinguish them from numeric expressions.
Example 1: #24/05/2012#
Example:
SELECT DAY(date_birth) AS date_Birth
FROM employees;
Data Query Language - DQL
Query: Get the age of each 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?
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.
Product TotalSales
Laptop 5200
Mouse 430
Data Query Language - DQL
G: Multi-table Selection Queries (Joins)
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*, ...)
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)
SYNTAX 2:
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:
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.
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
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.
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);
SYNTAX:
UPDATE <table name>
SET <attribute name> = <value>
WHERE <condition>;
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.
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:
SYNTAX:
ALTER TABLE <table_name>
ALTER COLUMN attribute type;
Example: ALTER TABLE T3 ALTER COLUMN salaire FLOAT;
3.3. Deleting a Field: