Language SQL- Select SQL Script - Select Reference: W3School - http://www.w3schools.com/sql/default.asp SQL SELECT Script L'instruction SELECT permet de sélectionner les données à partir d'une base de données. The SELECT statement is used to select data from a database. SELECT column_name,column_name FROM table_name; SELECT * FROM table_name 1
SQL SELECT WHERE Clause La clause WHERE est utilisée pour extraire uniquement les enregistrements que satisfaire au critère spécifié.the WHERE clause is used to extract only those records that fulfill a specified criterion. SELECT column_name,column_name FROM table_name WHERE column_name operator value; SQL SELECT WHERE Clause Operator Operator = Equal <> Description > Greater than < Less than Not equal. Note: In some versions of SQL this operator may be written as!= >= Greater than or equal <= Less than or equal BETWEEN LIKE IN Between an inclusive range Search for a pattern To specify multiple possible values for a column 2
Utiliser la base des données créée pendant le cours et écrire les scripts pour: Using the data created during the course, write the scripts for: Écrire une requête pour afficher tous les immeubles en Montreal/ Write a query to display all buildings in Montreal Écrire une requête pour afficher tous les immeubles qui ont le numero 1 dans l addresse / Write a query to display all buildings that have the number 1 in the address Écrire une requête pour afficher tous les immeubles qui commencent avec le code posta «H1» / Write a query to display all buildings that start with the post code "H1" Écrire une requête pour afficher tous les appartament qui la valeur du loyer est superieur ou egual a 500 / Write a query to display all the Apartments that the rent value is greater than or equal to 500 SQL AND & OR Operators L'opérateur AND affiche un enregistrement si la première condition ET la deuxième condition sont vraies. / The AND operator displays a record if both the first condition AND the second condition are true. L'opérateur OR affiche un enregistrement si la première condition OU la seconde condition est vraie. / The OR operator displays a record if either the first condition OR the second condition is true. Ex.: SELECT * FROM Customers WHERE City='Berlin' OR City='München'; SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; 3
SQL ORDER BY Le mot-clé ORDER BY est utilisé pour trier le résultat défini par une ou plusieurs colonnes / The ORDER BY keyword is used to sort the result-set by one or more columns. Le mot-clé ORDER BY classe les enregistrements par ordre croissant par défaut. Pour trier les enregistrements dans un ordre décroissant, vous pouvez utiliser le mot clé DESC. / The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword. SELECT column_name, column_name FROM table_name ORDER BY column_name ASC DESC, column_name ASC DESC; Utiliser la base des données créée pendant le cours et écrire les scripts pour: Using the data created during the course, write the scripts for: Écrire une requête pour afficher tous les villes en ordre alphabetique / Write a query to show all cities in order alphabetically. Écrire une requête pour afficher tous les immeubles en Montreal et em Quebec/ Write a query to display all buildings in Montreal and Quebec Écrire une requête pour afficher tous les addresse des Buildings en ordre DESC / Write a query to show all Building's address in order DESC. 4
SQL JOIN Une clause SQL JOIN est utilisée pour combiner des lignes de deux tables ou plus, basées sur un champ commun entre elles. / An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. Le type de jointure le plus courant est: SQL INNER JOIN (simple jointure). Un SQL INNER JOIN renvoie toutes les lignes de plusieurs tables où la condition de jointure est satisfaite. / The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN returns all rows from multiple tables where the join condition is met. SQL INNER JOIN Le INNER JOIN sélectionne toutes les lignes des deux tables tant qu'il existe une correspondance entre les colonnes des deux tables./ The INNER JOIN selects all rows from both tables as long as there is a match between the columns in both tables. SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name=table2.column_name; 5
SQL OUTER JOIN Le LEFT OUTER JOIN retourne toutes les lignes de la table de gauche (table1), avec les lignes correspondantes dans la table de droite (table2). Le résultat est NULL dans le côté droit lorsqu'il n'y a pas de correspondance./ The LEFT OUTER JOIN returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match. SELECT column_name(s) FROM table1 LEFT OUTER JOIN table2 ON table1.column_name=table2.column_name; Utiliser la base des données créée pendant le cours et écrire les scripts pour: Using the data created during the course, write the scripts for: Écrire une requête pour afficher tous les immeubles en Montreal, vous devez utiliser le mot Montreal pas le CityId/ Write a query to display all buildings in Montreal, You must use the word Montreal not the CityId. Écrire une requête pour afficher tous les immeubles et ses appartments /Write a query to view all buildings and its apartments. Écrire une requête pour afficher tous les immeubles, ses appartments et l adresse avec le nom da la ville /Write a query to view all buildings, its apartments and the address with the city name. 6
SELECT buildingaddress, cityname FROM building INNER JOIN city ON buildingcityid=cityid WHERE cityname = 'Montreal'; SELECT * FROM building INNER JOIN apartment on apartmentbuildingid = buildingid SELECT * FROM building INNER JOIN apartment on apartmentbuildingid = buildingid INNER JOIN city on buildingcityid=cityid; Utiliser la base des données créée pendant le cours et écrire les scripts pour: Using the data created during the course, write the scripts for: Écrire une requête pour afficher tous les immeubles, ses appartments et l adresse avec le nom da la ville, même si n a pas des appartments liées au immeuble/write a query to view all buildings, its apartments and the address with the city name, even if you don t have any apartment linked with building. Écrire une requête pour afficher tous les nome des utilisateurs, avec le nom da la ville, ordenées par nom de utilisateur/write a query to display all names of users, and the city name, order by name of the user. 7
SELECT name, cityname FROM user INNER JOIN city ON usercityid = cityid ORDER BY name ASC; SQL Aggregate Functions AVG() - Returns the average value SELECT AVG(column_name) FROM table_name COUNT() - Returns the number of rows SELECT COUNT(column_name) FROM table_name FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value SELECT MAX(column_name) FROM table_name MIN() - Returns the smallest value SELECT MIN(column_name) FROM table_name SUM() - Returns the sum SELECT SUM(column_name) FROM table_name 8
Utiliser la base des données créée pendant le cours et écrire les scripts pour: Using the data created during the course, write the scripts for: Écrire une requête pour afficher la moyenne des Rooms /Write a query to view the average rooms. Écrire une requête pour afficher le building qui a le loyer plus cher /Write a query to view building that has the most expensive rent. Écrire une requête pour afficher la somme des prix de loyer /Write a query to view the sum of the rents price. Écrire une requête pour afficher le nombre total de immeubles enregistrés /Write a query to display the total number of building registered. SELECT AVG(apartmentNumberRooms) FROM apartment; SELECT MAX(apartmentRentPrice), buildingaddress From apartment INNER JOIN building on buildingid=apartmentbuildingid; SELECT SUM(apartmentRentPrice) From apartment; SELECT count(*) as BUILDSUM FROM building; 9
SQL GROUP BY Statement L'instruction GROUP BY est utilisée conjointement avec les fonctions agrégées pour regrouper le jeu de résultats par une ou plusieurs colonnes.the GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name; Utiliser la base des données créée pendant le cours et écrire les scripts pour: Using the data created during the course, write the scripts for: Écrire une requête pour afficher la moyenne des Rooms by building /Write a query to view the rooms average by building. Écrire une requête pour afficher le loyer moins cher par building /Write a query to view less expensive apartment rent by building. Écrire une requête pour afficher la somme des prix de loyer par ville, ordenée par nom de ville /Write a query to view the sum of the rents price by city order by city name. Écrire une requête pour afficher le nombre total de immeubles par city /Write a query to display the total number of building by city. 10
SELECT AVG(apartmentNumberRooms), buildingaddress FROM apartment INNER JOIN building on buildingid=apartmentbuildingid GROUP BY buildingaddress; ------------------------------------------------------------------------------------------------- SELECT MIN(apartmentRentPrice), buildingaddress FROM apartment INNER JOIN building on buildingid=apartmentbuildingid GROUP BY buildingaddress; SELECT SUM(apartmentRentPrice), cityname FROM apartment INNER JOIN building on buildingid=apartmentbuildingid INNER join city on cityid=buildingcityid GROUP BY cityname; ------------------------------------------------------------------------------------------------- SELECT count(buildingid), cityname FROM building INNER join city on cityid=buildingcityid GROUP BY cityname; 11
SQL Scalar functions UCASE() - Converts a field to upper case SELECT UCASE(column_name) FROM table_name; LCASE() - Converts a field to lower case SELECT LCASE(column_name) FROM table_name; MID() - Extract characters from a text field SELECT MID(column_name,start,length) AS some_name FROM table_name; LENGTH() - Returns the length of a text field SELECT LENGTH (column_name) FROM table_name; ROUND() - Rounds a numeric field to the number of decimals specified SELECT ROUND(column_name,decimals) FROM table_name; NOW() - Returns the current system date and time SELECT NOW() FROM table_name; SELECT UCASE(cityName) FROM city; SELECT LCASE(cityName) FROM city; SELECT MID(cityName,2,3) AS some_name FROM city; SELECT LENGTH(cityName) AS some_name FROM city; SELECT ROUND(apartmentNumberRooms,0) FROM apartment; SELECT NOW() FROM city; 12
13