SlideShare une entreprise Scribd logo
1  sur  32
Zouhair ELHADARI
www.hadari.jimdo.com
Centre de BTS Dakhla
2ème année BTS DSI
Administration des SBGD relationnels
Chapitre 2
Introduction au langage SQL
2ème année BTS DSI
Prof:EL HADARI zouhair 2
 Langage de requêtes (Structured Query Language )
 Origine
◦ 1975 : QUEL
◦ 1976 : Structured English QUEry Langage (SEQUEL) par
IBM
◦ 1981 : SQL par IBM
 Standard ANSI-ISO, Normes SQL-86,89, SQL2-92
 SGBDR : Oracle, Sybase, DB2, Ingres, MS SQL
Server, MySQL, MS Access ...
3
le langage des SGBD Relationnels
2ème année BTS DSI
Prof:EL HADARI zouhair
Plan du cours
 Manipulation de tables et BD.
 Requêtes de consultation de tables
◦ Projection, Sélection, Jointure
◦ Tri, Agrégation, Partitionnement
 Requêtes de Modification de tables
◦ Ajout
◦ Suppression
4
2ème année BTS DSI
Prof:EL HADARI zouhair
Administration de Base de Données
Création d'une base de données
Syntaxe :
CREATE DATABASE NomBdd;
Destruction totale d'une base de données
Syntaxe :
DROP DATABASE NomBdd;
5
2ème année BTS DSI
Prof:EL HADARI zouhair
Types SQL
6
Type Taille
(Octets)
Signification
Int 4 Valeur Entière
SmallInt 2 Valeur Entière
TinyInt 1 Valeur Entière
float 4/8 Valeur Décimale
Char
(longueur)
Fixe (max
255)
Chaîne de
caractères
VarChar
(longueur)
Var (max
255)
Chaîne de
caractères
Text Var (max
231-1)
Chaîne de
caractères
Image Var (max
231-1)
Chaîne binaire
Type Taille
(Octets)
Signification
Bit 1 Valeur Binaire
Binary Fixe (max
255)
Chaîne binaire
Varbinary Var (max
255)
Chaîne binaire
Money 8 Valeur en $
DateTime 24 octets Nb Jours depuis
1/1/1900 + Heure
2ème année BTS DSI
Prof:EL HADARI zouhair
Création de table
Syntaxe :
CREATE TABLE nomTable (
Attribut Domaine [Contraintes ...],
...
Attribut Domaine [Contraintes ...],
[Contraintes ... ]
);
7
2ème année BTS DSI
Prof:EL HADARI zouhair
Création de table - Exemple
Créer la table Stock1(Pièce, NbP, Fournisseur)
8
CREATE TABLE Stock1 (
Pièce VARCHAR(20) NOT NULL,
NbP INT,
Fournisseur CHAR(20) NOT NULL,
PRIMARY KEY (Pièce, Fournisseur)
);
2ème année BTS DSI
Prof:EL HADARI zouhair
Modification et Suppression de Relation
Modification de Schéma de relation (Syntaxe variable !)
Exemple pour Oracle v6 :
ALTER TABLE Table
[ADD (définition_attribut | Contrainte), [définition_attribut |
Contrainte] ... )]
[MODIFY (définition_attribut [, définition_attribut ]... )]
[DROP CONSTRAINT contrainte]
Suppression complète d'une relation (et de son schéma) :
DROP TABLE Table;
Attention, toutes les données de la table sont perdues !
9
!
2ème année BTS DSI
Prof:EL HADARI zouhair
Plan du cours
 Manipulation de tables et BD.
 Requêtes de consultation de tables
◦ Projection, Sélection, Jointure
◦ Tri, Agrégation, Partitionnement
 Requêtes de Modification de tables
◦ Ajout
◦ Suppression
10
2ème année BTS DSI
Prof:EL HADARI zouhair
Projection
Syntaxe SQL :
SELECT [UNIQUE1] liste_attributs2 FROM Table ;
Équivalent AR :
liste_attributs R(Table)
1 Permet d'éliminer les doublons (on trouvera aussi DISTINCT)
2 On peut mettre une étoile * pour demander tous les attributs
On peut renommer un attribut en ajoutant AS NomAttribut
11
2ème année BTS DSI
Prof:EL HADARI zouhair
Projection - Exemples
12
Soit la relation Étudiants(#num, nom, prénom, âge, ville, CodePostal)
Donner les noms, les prénoms et les âges de tous les étudiants.
Afficher toute la relation Étudiant.
SELECT nom, prénom, age FROM Étudiants;
SELECT * FROM Étudiants;
Donner les numéros des étudiants dans une colonne nommée Numéro.
SELECT #num AS Numéro FROM Étudiants;
2ème année BTS DSI
Prof:EL HADARI zouhair
Sélection
Syntaxe SQL :
SELECT * FROM table WHERE condition;
Équivalent AR :
condition R(Table)
La condition peut formée sur des noms d'attributs ou des constantes
avec
 des opérateurs de comparaison : =, >, <, <=, >=, <>1
 des opérateurs logiques : AND, OR, NOT
 des opérateurs : IN, BETWEEN+AND, LIKE, EXISTS, IS
 _ qui remplace un caractère et % qui remplace une chaîne de
caractères
1 La différence est parfois notée !=
13
2ème année BTS DSI
Prof:EL HADARI zouhair
Sélection – Exemples
14
Quels sont tous les étudiants âgés de 20 ans ou plus ?
SELECT * FROM Étudiants WHERE (Age >= 20);
Quels sont tous les étudiants âgés de 19 à 23 ans ?
SELECT * FROM Étudiants WHERE Age IN (19, 20, 21, 22, 23);
SELECT * FROM Étudiants WHERE Age BETWEEN 19 AND 23;
Quels sont tous les étudiants habitant Dakhla?
SELECT * FROM Étudiant WHERE Ville LIKE ‘%Dakhla%' ;
Quels sont tous les étudiants dont la ville est inconnue/connue ?
SELECT * FROM Étudiants WHERE Ville IS NULL ;
SELECT * FROM Étudiants WHERE Ville IS NOT NULL ;
Sur la relation Étudiants(#Num, Nom, Prénom, Age, Ville, CodePostal)
2ème année BTS DSI
Prof:EL HADARI zouhair
Produit Cartésien
Syntaxe SQL :
SELECT *
FROM table1 [Alias1], ..., tablen [Aliasn],
Équivalent AR :
Table1  ...  Table n
15
2ème année BTS DSI
Prof:EL HADARI zouhair
-Jointure
Syntaxe SQL :
SELECT *
FROM table1 [Alias1], ..., tablen [Aliasn],
WHERE condition;
Équivalent AR :
Table1  ...  Table n
Autre Syntaxe :
SELECT * FROM table1 INNER JOIN table2 ON
condition;
16
2ème année BTS DSI
Prof:EL HADARI zouhair
Jointure - Exemples
Soient les relations Produit (#prod, nomProd, fournisseur, pu)
DétailCommande (.#num ,#cmd, #prod, pu, qte,
remise)
Quels sont les numéros de commande correspondant à l'achat d'une
table ?
Même requête, mais avec des alias pour les noms de relation :
17
SELECT dc.#num
FROM Produit p, DétailCommande dc
WHERE p.#prod = dc.#prod
AND nomProd LIKE "%table%";
SELECT DétailCommande.#num
FROM Produit, DétailCommande
WHERE Produit.#prod =DétailCommande.#prod
AND nomProd LIKE "%table%";
2ème année BTS DSI
Prof:EL HADARI zouhair
Jointures par requêtes
imbriquées
Une jointure peut aussi être effectuée à l'aide d'une
sous-requête.
SELECT *
FROM Stock
WHERE #prod IN ( SELECT #prod
FROM Produit)
Principe : Le mot-clef "IN" permet ici de sélectionner
les tuples #prod appartenant à la sous-requête.
◦ La sous-requête ne doit retourner qu'une colonne !
◦ Les tables de sous-requêtes ne sont pas visibles depuis
l'extérieur
18
Sous-requête imbriquée
!
2ème année BTS DSI
Prof:EL HADARI zouhair
Une requête complexe
A partir des relations suivantes : Produit(#prod, libellé, pu)
Stock(#prod, #dép, qté)
Dépôt(#dép, adr, volume)
Quels sont les produits qui sont en rupture de stock ? (sans et avec
imbrication)
19
SELECT p.#prod, p.libellé, d.#dép, d.Adr
FROM Produit p, Dépôt d, Stock s
WHERE p.#prod = s.#prod
AND s.#dép = d.#dép
AND s.qte <= 0
SELECT p.#prod, p.libellé, d.#dép, d.Adr
FROM Produit p, Dépôt d
WHERE p.#prod IN ( SELECT s.#prod
FROM Stock s
WHERE s.qté <= 0
AND p.#prod = s.#prod
AND s.#dép = d.#dép )
2ème année BTS DSI
Prof:EL HADARI zouhair
Union, Intersection et Différence
Table1  Table2 : SELECT liste_attributs FROM
table1
UNION
SELECT liste_attributs FROM table2 ;
Table1  Table2 : SELECT liste_attributs FROM table1
INTERSECT
SELECT liste_attributs FROM table2 ;
Table1 - Table2 : SELECT liste_attributs FROM
table1
EXCEPT
SELECT liste_attributs FROM table2 ;
20
2ème année BTS DSI
Prof:EL HADARI zouhair
Tri de résultats
Syntaxe :
Cette clause se place derrière la clause WHERE
ORDER BY attribut [ordre] [, attribut [ordre] ...]
On peut préciser un ordre croissant ASC ou décroissant DESC.
Exemple
Trier Stock par numéro de produit croissant et par quantité
décroissante
21
SELECT *
FROM Stock
WHERE qte > 0
ORDER BY #prod ASC, qte DESC
2ème année BTS DSI
Prof:EL HADARI zouhair
Agrégation des résultats
Il est possible d'utiliser des fonctions f d'agrégation dans le
résultat d'une sélection.
Syntaxe :
SELECT f ( [ ALL | DISTINCT ] expression)
FROM ...
où f peut être COUNT nombre de tuples
SUM somme des valeurs d'une
colonne
AVG moyenne des valeurs d'une
colonne
MAX maximum des valeurs d'une
colonne
MIN minimum des valeurs d'une
colonne
Pour COUNT, on peut aussi utiliser COUNT(*)
Seul COUNT prend en compte les valeurs à NULL. 22
2ème année BTS DSI
Prof:EL HADARI zouhair
Fonctions d'agrégation - Exemples
23
Matière Coef Note
Maths 4 15
Sc Nat 3 9
Sc Phy 3 12
Français 2 13
Sc Hum 2 11
Anglais 1 10
Sport 1 12
Résultats Mohamed
SELECT COUNT(*) FROM Résultats WHERE Note > 12
 2
SELECT MAX(Note) FROM Résultats  15
SELECT SUM(Note*Coef)/Sum(Coef) FROM Résultats
 12,06
Quelle la somme pondérée des notes ?
Quelle est la meilleure note ?
SELECT SUM(Note*Coef) FROM Résultats  193
Quelle est la plus mauvaise note ?
SELECT MIN(Note) FROM Résultats  9
Quelle est la moyenne (pondérée) de Mohamed?
Dans combien de matières Mohamed a-t-il eu plus de 12
?
2ème année BTS DSI
Prof:EL HADARI zouhair
Partitionnement des résultats
Syntaxe
GROUP BY liste_attributs
HAVING condition avec fonction
Cette clause regroupe les résultats par valeur selon la condition
Dans l'ordre, on effectue
 la sélection SELECT
 le partitionnement GROUP BY
 on retient les partitions intéressantes HAVING
 on trie avec ORDER BY.
24
2ème année BTS DSI
Prof:EL HADARI zouhair
Partitionnement des résultats -
Exemples
25
Matière Coef Note
Maths 4 15
Sc Nat 3 9
Sc Phy 3 12
Français 2 13
Sc Hum 2 11
Anglais 1 10
Sport 1 12
Résultats
SELECT coef, Avg(note) as Moyenne
FROM Résultats
GROUP BY coef;
Coef Moyenne
1 11
2 12
3 10.5
4 15
Quelle est la note moyenne pour chaque coefficient ?
Quels sont les coefficients auxquels participe une seule
matière ?
SELECT coef
FROM Résultats GROUP BY coef
HAVING count(*)=1;
Coef
4
2ème année BTS DSI
Prof:EL HADARI zouhair
Plan du cours
 Manipulation de tables et BD.
 Requêtes de consultation de tables
◦ Projection, Sélection, Jointure
◦ Tri, Agrégation, Partitionnement
 Requêtes de Modification de tables
◦ Ajout
◦ Suppression
26
2ème année BTS DSI
Prof:EL HADARI zouhair
Ajouts de tuples dans une
relation
Syntaxe :
Pour insérer un tuple complètement spécifié :
INSERT INTO Table VALUES (val1,..., valn);
Pour insérer un tuple incomplètement spécifié :
INSERT INTO Table (liste_attributs)VALUES (val1,..., valn);
On peut insérer un tuple à partir d'une relation ayant le
même schéma.
INSERT INTO Table
SELECT *
FROM ...
27
2ème année BTS DSI
Prof:EL HADARI zouhair
Exemples d'insertion
Sur les relations Étudiants (#Num, Nom, Prénom, Age, Ville, CodePostal)
ClubThéâtre(#Num, Nom, Prénom)
Ajouter l'étudiant Mohamed Ali, 21 ans, habitant à Casablanca avec
le numéro 634.
28
INSERT INTO Étudiants
VALUES (634, ‘Mohamed', ‘Ali', ‘Casablanca', ' 20 000 ', 21);
Ajouter tous les étudiants Casaoui dans le Club de Théâtre
INSERT INTO ClubThéâtre
SELECT #Num, Nom, Prénom
FROM Étudiants
WHERE CodePostal LIKE ’20 000’;
2ème année BTS DSI
Prof:EL HADARI zouhair
Modification de tuples
Syntaxe :
UPDATE Table
SET attribut1 = expr1, ..., attributn = exprn
FROM ...
WHERE ...
Les expressions peuvent être
 une constante
 une valeur NULL
 une clause SELECT
29
2ème année BTS DSI
Prof:EL HADARI zouhair
Mise à jour - Exemple
UPDATE Étudiants
SET Age = Age + 1;
30
Sur la relation Étudiants (#Num, Nom, Prénom, Age, Ville, CodePostal)
Augmenter d'un an l'age de tous les étudiants.
On a appris que tous les étudiants de Casa ont déménagé à Rabat.
UPDATE Étudiants
SET Ville = ‘Rabat', CodePostal = ‘2500'
WHERE Ville = ‘Casa';
2ème année BTS DSI
Prof:EL HADARI zouhair
Suppression de Tuples
Syntaxe :
DELETE FROM Table
[WHERE condition]
Remarque :
Si on supprime tous les tuples d'une relation,
le schéma de relation existe toujours !
Exemple :
Retirer de la liste tous les étudiants de plus de 22 ans.
31
DELETE FROM Étudiants
WHERE Age > 22;
!
2ème année BTS DSI
Prof:EL HADARI zouhair
Fin du Chapitre
2ème année BTS DSI
Prof:EL HADARI zouhair 32

Contenu connexe

En vedette

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

En vedette (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

introduction au langage sql.ppsx

  • 1. Zouhair ELHADARI www.hadari.jimdo.com Centre de BTS Dakhla 2ème année BTS DSI Administration des SBGD relationnels
  • 2. Chapitre 2 Introduction au langage SQL 2ème année BTS DSI Prof:EL HADARI zouhair 2
  • 3.  Langage de requêtes (Structured Query Language )  Origine ◦ 1975 : QUEL ◦ 1976 : Structured English QUEry Langage (SEQUEL) par IBM ◦ 1981 : SQL par IBM  Standard ANSI-ISO, Normes SQL-86,89, SQL2-92  SGBDR : Oracle, Sybase, DB2, Ingres, MS SQL Server, MySQL, MS Access ... 3 le langage des SGBD Relationnels 2ème année BTS DSI Prof:EL HADARI zouhair
  • 4. Plan du cours  Manipulation de tables et BD.  Requêtes de consultation de tables ◦ Projection, Sélection, Jointure ◦ Tri, Agrégation, Partitionnement  Requêtes de Modification de tables ◦ Ajout ◦ Suppression 4 2ème année BTS DSI Prof:EL HADARI zouhair
  • 5. Administration de Base de Données Création d'une base de données Syntaxe : CREATE DATABASE NomBdd; Destruction totale d'une base de données Syntaxe : DROP DATABASE NomBdd; 5 2ème année BTS DSI Prof:EL HADARI zouhair
  • 6. Types SQL 6 Type Taille (Octets) Signification Int 4 Valeur Entière SmallInt 2 Valeur Entière TinyInt 1 Valeur Entière float 4/8 Valeur Décimale Char (longueur) Fixe (max 255) Chaîne de caractères VarChar (longueur) Var (max 255) Chaîne de caractères Text Var (max 231-1) Chaîne de caractères Image Var (max 231-1) Chaîne binaire Type Taille (Octets) Signification Bit 1 Valeur Binaire Binary Fixe (max 255) Chaîne binaire Varbinary Var (max 255) Chaîne binaire Money 8 Valeur en $ DateTime 24 octets Nb Jours depuis 1/1/1900 + Heure 2ème année BTS DSI Prof:EL HADARI zouhair
  • 7. Création de table Syntaxe : CREATE TABLE nomTable ( Attribut Domaine [Contraintes ...], ... Attribut Domaine [Contraintes ...], [Contraintes ... ] ); 7 2ème année BTS DSI Prof:EL HADARI zouhair
  • 8. Création de table - Exemple Créer la table Stock1(Pièce, NbP, Fournisseur) 8 CREATE TABLE Stock1 ( Pièce VARCHAR(20) NOT NULL, NbP INT, Fournisseur CHAR(20) NOT NULL, PRIMARY KEY (Pièce, Fournisseur) ); 2ème année BTS DSI Prof:EL HADARI zouhair
  • 9. Modification et Suppression de Relation Modification de Schéma de relation (Syntaxe variable !) Exemple pour Oracle v6 : ALTER TABLE Table [ADD (définition_attribut | Contrainte), [définition_attribut | Contrainte] ... )] [MODIFY (définition_attribut [, définition_attribut ]... )] [DROP CONSTRAINT contrainte] Suppression complète d'une relation (et de son schéma) : DROP TABLE Table; Attention, toutes les données de la table sont perdues ! 9 ! 2ème année BTS DSI Prof:EL HADARI zouhair
  • 10. Plan du cours  Manipulation de tables et BD.  Requêtes de consultation de tables ◦ Projection, Sélection, Jointure ◦ Tri, Agrégation, Partitionnement  Requêtes de Modification de tables ◦ Ajout ◦ Suppression 10 2ème année BTS DSI Prof:EL HADARI zouhair
  • 11. Projection Syntaxe SQL : SELECT [UNIQUE1] liste_attributs2 FROM Table ; Équivalent AR : liste_attributs R(Table) 1 Permet d'éliminer les doublons (on trouvera aussi DISTINCT) 2 On peut mettre une étoile * pour demander tous les attributs On peut renommer un attribut en ajoutant AS NomAttribut 11 2ème année BTS DSI Prof:EL HADARI zouhair
  • 12. Projection - Exemples 12 Soit la relation Étudiants(#num, nom, prénom, âge, ville, CodePostal) Donner les noms, les prénoms et les âges de tous les étudiants. Afficher toute la relation Étudiant. SELECT nom, prénom, age FROM Étudiants; SELECT * FROM Étudiants; Donner les numéros des étudiants dans une colonne nommée Numéro. SELECT #num AS Numéro FROM Étudiants; 2ème année BTS DSI Prof:EL HADARI zouhair
  • 13. Sélection Syntaxe SQL : SELECT * FROM table WHERE condition; Équivalent AR : condition R(Table) La condition peut formée sur des noms d'attributs ou des constantes avec  des opérateurs de comparaison : =, >, <, <=, >=, <>1  des opérateurs logiques : AND, OR, NOT  des opérateurs : IN, BETWEEN+AND, LIKE, EXISTS, IS  _ qui remplace un caractère et % qui remplace une chaîne de caractères 1 La différence est parfois notée != 13 2ème année BTS DSI Prof:EL HADARI zouhair
  • 14. Sélection – Exemples 14 Quels sont tous les étudiants âgés de 20 ans ou plus ? SELECT * FROM Étudiants WHERE (Age >= 20); Quels sont tous les étudiants âgés de 19 à 23 ans ? SELECT * FROM Étudiants WHERE Age IN (19, 20, 21, 22, 23); SELECT * FROM Étudiants WHERE Age BETWEEN 19 AND 23; Quels sont tous les étudiants habitant Dakhla? SELECT * FROM Étudiant WHERE Ville LIKE ‘%Dakhla%' ; Quels sont tous les étudiants dont la ville est inconnue/connue ? SELECT * FROM Étudiants WHERE Ville IS NULL ; SELECT * FROM Étudiants WHERE Ville IS NOT NULL ; Sur la relation Étudiants(#Num, Nom, Prénom, Age, Ville, CodePostal) 2ème année BTS DSI Prof:EL HADARI zouhair
  • 15. Produit Cartésien Syntaxe SQL : SELECT * FROM table1 [Alias1], ..., tablen [Aliasn], Équivalent AR : Table1  ...  Table n 15 2ème année BTS DSI Prof:EL HADARI zouhair
  • 16. -Jointure Syntaxe SQL : SELECT * FROM table1 [Alias1], ..., tablen [Aliasn], WHERE condition; Équivalent AR : Table1  ...  Table n Autre Syntaxe : SELECT * FROM table1 INNER JOIN table2 ON condition; 16 2ème année BTS DSI Prof:EL HADARI zouhair
  • 17. Jointure - Exemples Soient les relations Produit (#prod, nomProd, fournisseur, pu) DétailCommande (.#num ,#cmd, #prod, pu, qte, remise) Quels sont les numéros de commande correspondant à l'achat d'une table ? Même requête, mais avec des alias pour les noms de relation : 17 SELECT dc.#num FROM Produit p, DétailCommande dc WHERE p.#prod = dc.#prod AND nomProd LIKE "%table%"; SELECT DétailCommande.#num FROM Produit, DétailCommande WHERE Produit.#prod =DétailCommande.#prod AND nomProd LIKE "%table%"; 2ème année BTS DSI Prof:EL HADARI zouhair
  • 18. Jointures par requêtes imbriquées Une jointure peut aussi être effectuée à l'aide d'une sous-requête. SELECT * FROM Stock WHERE #prod IN ( SELECT #prod FROM Produit) Principe : Le mot-clef "IN" permet ici de sélectionner les tuples #prod appartenant à la sous-requête. ◦ La sous-requête ne doit retourner qu'une colonne ! ◦ Les tables de sous-requêtes ne sont pas visibles depuis l'extérieur 18 Sous-requête imbriquée ! 2ème année BTS DSI Prof:EL HADARI zouhair
  • 19. Une requête complexe A partir des relations suivantes : Produit(#prod, libellé, pu) Stock(#prod, #dép, qté) Dépôt(#dép, adr, volume) Quels sont les produits qui sont en rupture de stock ? (sans et avec imbrication) 19 SELECT p.#prod, p.libellé, d.#dép, d.Adr FROM Produit p, Dépôt d, Stock s WHERE p.#prod = s.#prod AND s.#dép = d.#dép AND s.qte <= 0 SELECT p.#prod, p.libellé, d.#dép, d.Adr FROM Produit p, Dépôt d WHERE p.#prod IN ( SELECT s.#prod FROM Stock s WHERE s.qté <= 0 AND p.#prod = s.#prod AND s.#dép = d.#dép ) 2ème année BTS DSI Prof:EL HADARI zouhair
  • 20. Union, Intersection et Différence Table1  Table2 : SELECT liste_attributs FROM table1 UNION SELECT liste_attributs FROM table2 ; Table1  Table2 : SELECT liste_attributs FROM table1 INTERSECT SELECT liste_attributs FROM table2 ; Table1 - Table2 : SELECT liste_attributs FROM table1 EXCEPT SELECT liste_attributs FROM table2 ; 20 2ème année BTS DSI Prof:EL HADARI zouhair
  • 21. Tri de résultats Syntaxe : Cette clause se place derrière la clause WHERE ORDER BY attribut [ordre] [, attribut [ordre] ...] On peut préciser un ordre croissant ASC ou décroissant DESC. Exemple Trier Stock par numéro de produit croissant et par quantité décroissante 21 SELECT * FROM Stock WHERE qte > 0 ORDER BY #prod ASC, qte DESC 2ème année BTS DSI Prof:EL HADARI zouhair
  • 22. Agrégation des résultats Il est possible d'utiliser des fonctions f d'agrégation dans le résultat d'une sélection. Syntaxe : SELECT f ( [ ALL | DISTINCT ] expression) FROM ... où f peut être COUNT nombre de tuples SUM somme des valeurs d'une colonne AVG moyenne des valeurs d'une colonne MAX maximum des valeurs d'une colonne MIN minimum des valeurs d'une colonne Pour COUNT, on peut aussi utiliser COUNT(*) Seul COUNT prend en compte les valeurs à NULL. 22 2ème année BTS DSI Prof:EL HADARI zouhair
  • 23. Fonctions d'agrégation - Exemples 23 Matière Coef Note Maths 4 15 Sc Nat 3 9 Sc Phy 3 12 Français 2 13 Sc Hum 2 11 Anglais 1 10 Sport 1 12 Résultats Mohamed SELECT COUNT(*) FROM Résultats WHERE Note > 12  2 SELECT MAX(Note) FROM Résultats  15 SELECT SUM(Note*Coef)/Sum(Coef) FROM Résultats  12,06 Quelle la somme pondérée des notes ? Quelle est la meilleure note ? SELECT SUM(Note*Coef) FROM Résultats  193 Quelle est la plus mauvaise note ? SELECT MIN(Note) FROM Résultats  9 Quelle est la moyenne (pondérée) de Mohamed? Dans combien de matières Mohamed a-t-il eu plus de 12 ? 2ème année BTS DSI Prof:EL HADARI zouhair
  • 24. Partitionnement des résultats Syntaxe GROUP BY liste_attributs HAVING condition avec fonction Cette clause regroupe les résultats par valeur selon la condition Dans l'ordre, on effectue  la sélection SELECT  le partitionnement GROUP BY  on retient les partitions intéressantes HAVING  on trie avec ORDER BY. 24 2ème année BTS DSI Prof:EL HADARI zouhair
  • 25. Partitionnement des résultats - Exemples 25 Matière Coef Note Maths 4 15 Sc Nat 3 9 Sc Phy 3 12 Français 2 13 Sc Hum 2 11 Anglais 1 10 Sport 1 12 Résultats SELECT coef, Avg(note) as Moyenne FROM Résultats GROUP BY coef; Coef Moyenne 1 11 2 12 3 10.5 4 15 Quelle est la note moyenne pour chaque coefficient ? Quels sont les coefficients auxquels participe une seule matière ? SELECT coef FROM Résultats GROUP BY coef HAVING count(*)=1; Coef 4 2ème année BTS DSI Prof:EL HADARI zouhair
  • 26. Plan du cours  Manipulation de tables et BD.  Requêtes de consultation de tables ◦ Projection, Sélection, Jointure ◦ Tri, Agrégation, Partitionnement  Requêtes de Modification de tables ◦ Ajout ◦ Suppression 26 2ème année BTS DSI Prof:EL HADARI zouhair
  • 27. Ajouts de tuples dans une relation Syntaxe : Pour insérer un tuple complètement spécifié : INSERT INTO Table VALUES (val1,..., valn); Pour insérer un tuple incomplètement spécifié : INSERT INTO Table (liste_attributs)VALUES (val1,..., valn); On peut insérer un tuple à partir d'une relation ayant le même schéma. INSERT INTO Table SELECT * FROM ... 27 2ème année BTS DSI Prof:EL HADARI zouhair
  • 28. Exemples d'insertion Sur les relations Étudiants (#Num, Nom, Prénom, Age, Ville, CodePostal) ClubThéâtre(#Num, Nom, Prénom) Ajouter l'étudiant Mohamed Ali, 21 ans, habitant à Casablanca avec le numéro 634. 28 INSERT INTO Étudiants VALUES (634, ‘Mohamed', ‘Ali', ‘Casablanca', ' 20 000 ', 21); Ajouter tous les étudiants Casaoui dans le Club de Théâtre INSERT INTO ClubThéâtre SELECT #Num, Nom, Prénom FROM Étudiants WHERE CodePostal LIKE ’20 000’; 2ème année BTS DSI Prof:EL HADARI zouhair
  • 29. Modification de tuples Syntaxe : UPDATE Table SET attribut1 = expr1, ..., attributn = exprn FROM ... WHERE ... Les expressions peuvent être  une constante  une valeur NULL  une clause SELECT 29 2ème année BTS DSI Prof:EL HADARI zouhair
  • 30. Mise à jour - Exemple UPDATE Étudiants SET Age = Age + 1; 30 Sur la relation Étudiants (#Num, Nom, Prénom, Age, Ville, CodePostal) Augmenter d'un an l'age de tous les étudiants. On a appris que tous les étudiants de Casa ont déménagé à Rabat. UPDATE Étudiants SET Ville = ‘Rabat', CodePostal = ‘2500' WHERE Ville = ‘Casa'; 2ème année BTS DSI Prof:EL HADARI zouhair
  • 31. Suppression de Tuples Syntaxe : DELETE FROM Table [WHERE condition] Remarque : Si on supprime tous les tuples d'une relation, le schéma de relation existe toujours ! Exemple : Retirer de la liste tous les étudiants de plus de 22 ans. 31 DELETE FROM Étudiants WHERE Age > 22; ! 2ème année BTS DSI Prof:EL HADARI zouhair
  • 32. Fin du Chapitre 2ème année BTS DSI Prof:EL HADARI zouhair 32