Language SQL- Select

Documents pareils
Exercices sur SQL server 2000

COMMANDES SQL... 2 COMMANDES DE DEFINITION DE DONNEES... 2

Instructions Mozilla Thunderbird Page 1

Application Form/ Formulaire de demande

Optimisation SQL. Quelques règles de bases

et Active Directory Ajout, modification et suppression de comptes, extraction d adresses pour les listes de diffusion

1. LA GESTION DES BASES DE DONNEES RELATIONNELLES

SQL Historique

ECR_DESCRIPTION CHAR(80), ECR_MONTANT NUMBER(10,2) NOT NULL, ECR_SENS CHAR(1) NOT NULL) ;

Fiche produit ifinance v4

Once the installation is complete, you can delete the temporary Zip files..

Langage SQL : créer et interroger une base

Le No.1 de l économie d énergie pour patinoires.

RAPID Prenez le contrôle sur vos données

WEB page builder and server for SCADA applications usable from a WEB navigator

SERVEUR DÉDIÉ DOCUMENTATION

FileMaker 13. Guide de référence SQL

lundi 3 août 2009 Choose your language What is Document Connection for Mac? Communautés Numériques L informatique à la portée du Grand Public

SparkInData. Place de Marché des applications Spatiales

Utiliser une WebCam. Micro-ordinateurs, informations, idées, trucs et astuces

Le langage SQL Rappels

calls.paris-neuroscience.fr Tutoriel pour Candidatures en ligne *** Online Applications Tutorial

Practice Direction. Class Proceedings

How to Login to Career Page

Instructions pour mettre à jour un HFFv2 v1.x.yy v2.0.00

Comment Accéder à des Bases de Données MySQL avec Windows lorqu'elles sont sur un Serveur Linux

TD : Requêtes SQL (BDR.TD2-1) INSA 3IF

CALCUL DE LA CONTRIBUTION - FONDS VERT Budget 2008/2009

MELTING POTES, LA SECTION INTERNATIONALE DU BELLASSO (Association étudiante de lʼensaparis-belleville) PRESENTE :

Olivier Mondet

SQL. Oracle. pour. 4 e édition. Christian Soutou Avec la participation d Olivier Teste

RULE 5 - SERVICE OF DOCUMENTS RÈGLE 5 SIGNIFICATION DE DOCUMENTS. Rule 5 / Règle 5

Présentation Windows Azure Hadoop Big Data - BI

POLICY: FREE MILK PROGRAM CODE: CS-4

Archived Content. Contenu archivé

MapReduce. Malo Jaffré, Pablo Rauzy. 16 avril 2010 ENS. Malo Jaffré, Pablo Rauzy (ENS) MapReduce 16 avril / 15

Academic Project. B2- Web Development. Resit Project. Version 1.0 Last update: 24/05/2013 Use: Students Author: Samuel CUELLA

OpenPaaS Le réseau social d'entreprise

Surveillance de Scripts LUA et de réception d EVENT. avec LoriotPro Extended & Broadcast Edition

1 Introduction et installation

I. Programmation I. 1 Ecrire un programme en Scilab traduisant l organigramme montré ci-après (on pourra utiliser les annexes):

Plan Général Prévisionnel (1/2) (non contractuel) Internet et Outils L1/IO S2-IO2 Bases de données: Jointures, Transactions

Comment Créer une Base de Données Ab Initio

Règlement sur le télémarketing et les centres d'appel. Call Centres Telemarketing Sales Regulation

Comprendre l impact de l utilisation des réseaux sociaux en entreprise SYNTHESE DES RESULTATS : EUROPE ET FRANCE

Quick Start Guide This guide is intended to get you started with Rational ClearCase or Rational ClearCase MultiSite.

If the corporation is or intends to become a registered charity as defined in the Income Tax Act, a copy of these documents must be sent to:

Compléter le formulaire «Demande de participation» et l envoyer aux bureaux de SGC* à l adresse suivante :

1. Qu'est-ce que SQL? La maintenance des bases de données Les manipulations des bases de données... 5

DOCUMENTATION - FRANCAIS... 2

Historisation des données

UML : Unified Modeling Language

Langage SQL (1) 4 septembre IUT Orléans. Introduction Le langage SQL : données Le langage SQL : requêtes

TABLE DES MATIERES A OBJET PROCEDURE DE CONNEXION

PHOTO ROYAUME DE BELGIQUE /KINDOM OF BELGIUM /KONINKRIJK BELGIE. Données personnelles / personal data

La rencontre du Big Data et du Cloud

Paxton. ins Net2 desktop reader USB

Monitor LRD. Table des matières

Contents Windows

Encryptions, compression et partitionnement des données

Master Développement Durable et Organisations Master s degree in Sustainable Development and Organizations Dossier de candidature Application Form

France SMS+ MT Premium Description

Gestion des prestations Volontaire

UNIVERSITE DE YAOUNDE II

THE LAW SOCIETY OF UPPER CANADA BY-LAW 19 [HANDLING OF MONEY AND OTHER PROPERTY] MOTION TO BE MOVED AT THE MEETING OF CONVOCATION ON JANUARY 24, 2002

GAME CONTENTS CONTENU DU JEU OBJECT OF THE GAME BUT DU JEU

AIDE FINANCIÈRE POUR ATHLÈTES FINANCIAL ASSISTANCE FOR ATHLETES

Plan. Bases de Données. Sources des transparents. Bases de SQL. L3 Info. Chapitre 4 : SQL LDD Le langage de manipulation de données : LMD

NORME INTERNATIONALE INTERNATIONAL STANDARD. Dispositifs à semiconducteurs Dispositifs discrets. Semiconductor devices Discrete devices

Spécial Catégorie 6 Patch Cords

Cours de didactique du français langue étrangère (*) French as a foreign language (*)

The new consumables catalogue from Medisoft is now updated. Please discover this full overview of all our consumables available to you.

INVESTMENT REGULATIONS R In force October 1, RÈGLEMENT SUR LES INVESTISSEMENTS R En vigueur le 1 er octobre 2001

14/04/2014. un ensemble d'informations sur un sujet : exhaustif, non redondant, structuré, persistant. Gaëlle PERRIN SID2 Grenoble.

VTP. LAN Switching and Wireless Chapitre 4

that the child(ren) was/were in need of protection under Part III of the Child and Family Services Act, and the court made an order on

OLAP : Mondrian + Pentaho. Maguelonne Teisseire Hugo Alatrista Salas hugo.alatrista- salas@teledetec9on.fr Flavien Bouillot

MODE OPERATOIRE OPENOFFICE BASE

Cours Bases de données 2ème année IUT

TD n 10 : Ma première Base de Données

ROYAUME DE BELGIQUE / KINGDOM OF BELGIUM / KONINKRIJK BELGIE

PARIS ROISSY CHARLES DE GAULLE

Comment calculer une moyenne journalière de l irradiance avec excel 2007? How to calculate a daily average amount of irradiance with Excel 2007?

Logitech Tablet Keyboard for Windows 8, Windows RT and Android 3.0+ Setup Guide Guide d installation

BIRT (Business Intelligence and Reporting Tools)

Session S12 Les bases de l optimisation SQL avec DB2 for i

DECLARATION OF PERFORMANCE. No DoP_FAC_003

AMENDMENT TO BILL 32 AMENDEMENT AU PROJET DE LOI 32

Tex: The book of which I'm the author is an historical novel.

Lamia Oukid, Ounas Asfari, Fadila Bentayeb, Nadjia Benblidia, Omar Boussaid. 14 Juin 2013

Cheque Holding Policy Disclosure (Banks) Regulations. Règlement sur la communication de la politique de retenue de chèques (banques) CONSOLIDATION

DOCUMENTATION - FRANCAIS... 2

INSTITUT MARITIME DE PREVENTION. For improvement in health and security at work. Created in 1992 Under the aegis of State and the ENIM

Le Langage SQL version Oracle

English Q&A #1 Braille Services Requirement PPTC Q1. Would you like our proposal to be shipped or do you prefer an electronic submission?

OUVRIR UN COMPTE CLIENT PRIVÉ

Editing and managing Systems engineering processes at Snecma

Transcription:

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 SQL 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 SQL 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 building WHERE buildingcityid = 1 OR buildingcityid = 2; SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; 3

Exercise Write a query to display all buildings in Montreal and Laval Write a query to display all apartments where the number of rooms is bigger than 3 and the price is lower than 1000 SELECT * FROM building WHERE buildingcityid = 1 OR buildingcityid = 2; SELECT * FROM apartment WHERE apartmentnumberrooms > 3 and apartmentrentprice < 1000; 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; 4

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 addresse des Buildings en ordre DESC / Write a query to show all Building's address in order DESC. 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. 5

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; 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; 6

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 city name. 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; 7

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. SELECT name, cityname FROM user INNER JOIN city ON usercityid = cityid ORDER BY name ASC; SELECT buildingid, buildingaddress, apartmentnumber, cityname FROM building LEFT OUTER JOIN apartment ON buildingid = apartmentbuildingidinner JOIN city ON buildingcityid=cityid 8

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 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. 9

SELECT AVG(apartmentNumberRooms) FROM apartment; SELECT apartmentrentprice, buildingaddress From apartment INNER JOIN building on buildingid=apartmentbuildingid WHERE apartmentrentprice = (SELECT MAX(apartmentRentPrice) From apartment); SELECT SUM(apartmentRentPrice) From apartment; SELECT count(*) as BUILDSUM FROM building; 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; 10

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. 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; 11

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; 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) 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(); 12

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(); Exercise 1. Display the name of the user and the name of the city; 2. Display the name of the user and the name of the city Order by city name; 3. Display the name of the user and the name of the city when city name starts with M; 4. Display the apartment Number and address; 5. Display the apartment Number, address and city name order by city name; 6. Display the name of the user, the name of the city and the name of the country; 7. Display A list of apartments with the address, city, country, # rooms and rent price, when the number of rooms is bigger than 3 and the price is lower than 1000. 8. Display A list of apartments with the address, city, country, # rooms and rent price,when the number of rooms is bigger than 3 and the price is lower than 1000 in montreal and quebec. 13

1 ) Display the name of the user and the name of the city; SELECT name, cityname FROM USER INNER JOIN city ON cityid=usercityid; 2) Display the name of the user and the name of the city Order by city name; SELECT name, cityname FROM USER INNER JOIN city ON cityid=usercityid ORDER BY cityname ASC; 3) Display the name of the user and the name of the city when city name starts with M; SELECT name, cityname FROM USER INNER JOIN city ON cityid=usercityid WHERE cityname LIKE 'M%'; 4) Display the apartment Number and address; SELECT apartmentnumber, buildingaddress FROM apartment INNER JOIN building ON buildingid=apartmentbuildingid 5) Display the apartment Number, address and city name order by city name; SELECT apartmentnumber, buildingaddress, cityname FROM apartment INNER JOIN building ON buildingid=apartmentbuildingid INNER JOIN city ON cityid=buildingcityid ORDER BY cityname; 6) Display the name of the user, the name of the city and the name of the country; SELECT name, cityname, countryname FROM user INNER JOIN city ON cityid=usercityid INNER JOIN country ON countryid=citycountryid; 14

7) Display A list of apartments with the address, city, country, # rooms and rent price, when the number of rooms is bigger than 3 and the price is lower than 1000. SELECT buildingaddress, cityname, countryname, apartmentnumberrooms, apartmentrentprice FROM building INNER JOIN apartment ON buildingid=apartmentbuildingid INNER JOIN city ON cityid=buildingcityid INNER JOIN country ON countryid = citycountryid WHERE apartmentnumberrooms > 3 AND apartmentrentprice < 1000; 8) Display A list of apartments with the address, city, country, # rooms and rent price, when the number of rooms is bigger than 3 and the price is lower than 1000 in montreal and quebec. SELECT buildingaddress, cityname, countryname, apartmentnumberrooms, apartmentrentprice FROM building INNER JOIN apartment ON buildingid=apartmentbuildingid INNER JOIN city ON cityid=buildingcityid INNER JOIN country ON countryid = citycountryid WHERE apartmentnumberrooms > 3 AND apartmentrentprice < 1000; AND (cityname="montreal" OR CityName="Quebec"); 15

16