SQL

Def et Utilité :


Pasted image 20240424164125.pngStructured Query Language est un langage qui doit permettre aux utilisateurs techniques et non techniques de manipuler des bases de données relationnels.
De nombreuses déclinaisons existent :

Id Make/Model # Wheels # Doors Type
1 Ford Focus 4 4 Sedan
2 Tesla Roadster 4 2 Sports
3 Kawakasi Ninja 2 0 Motorcycle
4 McLaren Formula 1 4 0 Race
5 Tesla S 4 4 Sedan

Documentation :


Cette documentation suit l'apprentissage de ce site :
https://sqlbolt.com/

SELECT :


SELECT column, another_column,FROM mytable;

sert à sélectionner des données spécifiques d'une base de données. Voici ce que fait chaque partie de la requête :


- `FROM mytable` : Indique la table à partir de laquelle les données doivent être extraites. Ici, les données sont extraites de la table appelée `mytable`.
### Contraintes : 
----
Les contraintes permettent de filtrer nos résultats de manière plus précise : 
```SQL
SELECT column, another_column, … FROM mytable WHERE condition AND/OR _another_condition_ AND/OR …;
Operator Condition SQL Example
=, !=, < <=, >, >= Standard numerical operators col_name != 4
BETWEEN … AND … Number is within range of two values (inclusive) col_name BETWEEN 1.5 AND 10.5
NOT BETWEEN … AND … Number is not within range of two values (inclusive) col_name NOT BETWEEN 1 AND 10
IN (…) Number exists in a list col_name IN (2, 4, 6)
NOT IN (…) Number does not exist in a list col_name NOT IN (1, 3, 5)
Par exemple :
SELECT name, age
FROM users
WHERE age >= 18
    AND (name = 'Alice' OR name = 'Bob');

Comment faire des recherches de text précises ?

Operator Condition Example
= Case sensitive exact string comparison (notice the single equals) col_name = "abc"
!= or <> Case sensitive exact string inequality comparison col_name != "abcd"
LIKE Case insensitive exact string comparison col_name LIKE "ABC"
NOT LIKE Case insensitive exact string inequality comparison col_name NOT LIKE "ABCD"
% Used anywhere in a string to match a sequence of zero or more characters (only with LIKE or NOT LIKE) col_name LIKE "%AT%"
(matches "AT", "ATTIC", "CAT" or even "BATS")
_ Used anywhere in a string to match a single character (only with LIKE or NOT LIKE) col_name LIKE "AN_"
(matches "AND", but not "AN")
IN (…) String exists in a list col_name IN ("A", "B", "C")
NOT IN (…) String does not exist in a list col_name NOT IN ("D", "E", "F")
Exemple :
SELECT * FROM movies WHERE title LIKE "toy story%";

DISTINCT :


DISTINCT a pour but de supprimer des résultats les doublons :

SELECT DISTINCT column, another_column,FROM mytable WHERE _condition(s)_;

ORDER BY :


ORDER BY a pour but de mettre en ordre les résultats selon un critère.

SELECT column, another_column,FROM mytable WHERE _condition(s)_ ORDER BY column ASC/DESC;
SELECT column, another_column,FROM mytable WHERE _condition(s)_ ORDER BY column ASC/DESC LIMIT num_limit OFFSET num_offset;
SELECT title FROM movies
ORDER BY title ASC
LIMIT 5 OFFSET 5;

JOIN :


Le but de join est de travailler et récupérer des résultats sur plusieurs fiches SQL .

INNER JOIN :


SELECT column, another_table_column,FROM mytable INNER JOIN another_table ON mytable.id = another_table.id WHERE _condition(s)_ ORDER BY column,ASC/DESC LIMIT num_limit OFFSET num_offset;

LEFT JOIN, RIGHT JOIN, FULL JOIN :


Ces mots clés sont utiles pour les tables qui sont asymétriques et ne possèdent pas de mot clé en commun.

SELECT column, another_column,FROM mytable INNER/LEFT/RIGHT/FULL JOIN another_table ON mytable.id = another_table.matching_id WHERE _condition(s)_ ORDER BY column,ASC/DESC LIMIT num_limit OFFSET num_offset;

NULL VALUE :


Il faut éviter autant que faire ce peut les value NULL qui peuvent empêcher l'exploitation des données.

SELECT column, another_column,FROM mytable WHERE column IS/IS NOT NULL AND/OR _another_condition_ AND/OR;

Expressions :


Les expressions permettent d'intégrer une logique mathématique pour transformer les valeurs reçues par exemple.

SELECT particle_speed / 2.0 AS half_particle_speed FROM physics_data WHERE ABS(particle_position) * 10.0 > 500;

Aggregates :


Function Description
COUNT(*), **COUNT(column) A common function used to counts the number of rows in the group if no column name is specified. Otherwise, count the number of rows in the group with non-NULL values in the specified column.
MIN(column) Finds the smallest numerical value in the specified column for all rows in the group.
MAX(column) Finds the largest numerical value in the specified column for all rows in the group.
**AVG(**column) Finds the average numerical value in the specified column for all rows in the group.
SUM(column) Finds the sum of all numerical values in the specified column for the rows in the group.

Grouped Aggregate :

SELECT AGG_FUNC(_column_or_expression_) AS aggregate_description,FROM mytable WHERE _constraint_expression_ GROUP BY column;
SELECT AVG(salary) AS average_salary FROM employees WHERE department = 'Sales' GROUP BY region;
SELECT role, AVG(years_employed) as Average_years_employed
FROM employees
GROUP BY role;

HAVING et GROUP BY :


SELECT group_by_column, AGG_FUNC(_column_expression_) AS aggregate_result_alias,FROM mytable WHERE _condition_ GROUP BY column **HAVING _group_condition_**;

Ordre d'execution :


SELECT DISTINCT column, AGG_FUNC(_column_or_expression_),FROM mytable JOIN another_table ON mytable.column = another_table.column WHERE _constraint_expression_ GROUP BY column HAVING _constraint_expression_ ORDER BY _column_ ASC/DESC LIMIT _count_ OFFSET _COUNT_;
  1. FROM :
    • C'est la première étape de l'exécution. SQL détermine d'abord quelle(s) table(s) est/sont impliquée(s) dans la requête.
  2. JOIN (si présent) :
    • Si la requête implique des jointures entre plusieurs tables, elles sont résolues après la spécification des tables dans la clause FROM.
  3. WHERE :
    • Cette clause filtre les lignes avant tout regroupement, agrégation, ou tri. Seules les lignes qui satisfont la condition spécifiée sont inclues dans les étapes suivantes.
  4. GROUP BY :
    • Après le filtrage initial, les lignes restantes sont regroupées en fonction des valeurs des colonnes spécifiées dans cette clause.
  5. AGGREGATION :
    • Les fonctions d'agrégation (comme SUM, AVG, COUNT, etc.) sont appliquées aux groupes formés par la clause GROUP BY.
  6. HAVING :
    • Cette clause filtre les groupes formés en fonction des résultats des fonctions d'agrégation. Contrairement à WHERE, HAVING opère après l'agrégation.
  7. SELECT :
    • Les colonnes ou expressions spécifiées sont sélectionnées et préparées pour la sortie. Cela inclut les colonnes directes, les expressions et les résultats des fonctions d'agrégation.
  8. DISTINCT (si présent) :
    • Si spécifié, cette opération élimine les doublons dans les résultats après le traitement de SELECT.
  9. ORDER BY :
    • Cette étape trie les résultats finaux selon les colonnes ou critères spécifiés. C'est une des dernières étapes avant que les données soient retournées à l'utilisateur.
  10. LIMIT / OFFSET (si présent) :
    • Ces clauses limitent le nombre de lignes à retourner et déterminent à partir de quelle ligne commencer à retourner les résultats. Elles sont appliquées tout à la fin du traitement de la requête.

INSERT :


Certaines bases de données contiennent des templates, des shema qui définissent des types de données dans des champs.

INSERT INTO mytable VALUES (value_or_expr, another_value_or_expr,), (value_or_expr_2, another_value_or_expr_2,),;

par exemple :

INSERT INTO boxoffice **(movie_id, rating, sales_in_millions)** VALUES (1, 9.9, 283742034 / 1000000);

Donc si on ne précise pas les champs tout est inséré dans l'ordre par défaut

UPDATE :


UPDATE mytable SET column = value_or_expr, other_column = another_value_or_expr,WHERE condition;

Il faut faire très attention avec les requêtes update qui peuvent détruire des bases de données.
Exemple :

UPDATE movies
SET director = "John Lasseter"
WHERE id = 2;

DELETE :


Sert à supprimer des lignes dans une table :

DELETE FROM mytable WHERE condition;

CREATE TABLE :


CREATE TABLE IF NOT EXISTS mytable ( column _DataType_ _TableConstraint_ DEFAULT _default_value_, another_column _DataType_ _TableConstraint_ DEFAULT _default_value_,);
CREATE TABLE IF NOT EXISTS employees ( id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, salary DECIMAL(10, 2) DEFAULT 0.00 );
CREATE TABLE Database (
    Name TEXT,
    Version FLOAT,
    Download_count INTEGER
);

Comment peut-on préciser quel type de données correspond à quel champ ?

Data type Description
INTEGERBOOLEAN The integer datatypes can store whole integer values like the count of a number or an age. In some implementations, the boolean value is just represented as an integer value of just 0 or 1.
FLOATDOUBLEREAL The floating point datatypes can store more precise numerical data like measurements or fractional values. Different types can be used depending on the floating point precision required for that value.
CHARACTER(num_chars)VARCHAR(num_chars)TEXT The text based datatypes can store strings and text in all sorts of locales. The distinction between the various types generally amount to underlaying efficiency of the database when working with these columns.

Both the CHARACTER and VARCHAR (variable character) types are specified with the max number of characters that they can store (longer values may be truncated), so can be more efficient to store and query with big tables.
DATEDATETIME SQL can also store date and time stamps to keep track of time series and event data. They can be tricky to work with especially when manipulating data across timezones.
BLOB Finally, SQL can store binary data in blobs right in the database. These values are often opaque to the database, so you usually have to store them with the right metadata to requery them.
Il existe aussi d'autres contraintes que l'on peut créer, par exemple limiter un nombre à un maximum
Constraint Description
PRIMARY KEY This means that the values in this column are unique, and each value can be used to identify a single row in this table.
AUTOINCREMENT For integer values, this means that the value is automatically filled in and incremented with each row insertion. Not supported in all databases.
UNIQUE This means that the values in this column have to be unique, so you can't insert another row with the same value in this column as another row in the table. Differs from the PRIMARY KEY in that it doesn't have to be a key for a row in the table.
NOT NULL This means that the inserted value can not be NULL.
CHECK (expression) This allows you to run a more complex expression to test whether the values inserted are valid. For example, you can check that values are positive, or greater than a specific size, or start with a certain prefix, etc.
FOREIGN KEY This is a consistency check which ensures that each value in this column corresponds to another value in a column in another table.

For example, if there are two tables, one listing all Employees by ID, and another listing their payroll information, the FOREIGN KEY can ensure that every row in the payroll table corresponds to a valid employee in the master Employee list.

ALTER TABLE :


ADD :


ALTER TABLE mytable ADD column _DataType_ _OptionalTableConstraint_ DEFAULT default_value;
ALTER TABLE movies ADD Aspect_ration FLOAT

DROP :


ALTER TABLE mytable DROP column_to_be_deleted;

RENAME :


ALTER TABLE mytable RENAME TO new_table_name;

DROP TABLE :


Drop table supprime une table, toutes ses données, métadonnées, et le schéma de la table :

DROP TABLE IF EXISTS mytable;

UNION :


La commande union permet de mettre bout à bout des requêtes SQL.

SELECT * FROM table1
UNION
SELECT * FROM table2

Commandes avancées :


Exemples :


Cette section est dédiée à des exemples de requêtes sympa pour en apprendre plus sur la syntaxe.

SELECT city, longitude FROM north_american_cities
WHERE longitude < -87.629798
ORDER BY longitude ASC;
SELECT title, domestic_sales, international_sales, rating
FROM movies
  JOIN boxoffice
    ON movies.id = boxoffice.movie_id
WHERE domestic_sales <= international_sales
ORDER BY rating DESC;
SELECT title, year
FROM movies
  JOIN boxoffice
    ON movies.id = boxoffice.movie_id
WHERE year % 2 = 0;
SELECT role, AVG(years_employed) as Average_years_employed
FROM employees
GROUP BY role;
SELECT director, SUM(domestic_sales + international_sales) as Cumulative_sales_from_all_movies
FROM movies
    INNER JOIN boxoffice
        ON movies.id = boxoffice.movie_id
GROUP BY director;