0% found this document useful (0 votes)
110 views

Advance Database Systems

The document provides an introduction to SQL and relational database management systems (RDBMS). It defines SQL as the standard language for storing, manipulating and retrieving data in relational databases. It describes the basic functions of SQL like executing queries, inserting, updating, and deleting data. It also introduces some key concepts like RDBMS, tables, columns, and rows. Finally, it provides a sample table from a database as an example.

Uploaded by

Chito Cadena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

Advance Database Systems

The document provides an introduction to SQL and relational database management systems (RDBMS). It defines SQL as the standard language for storing, manipulating and retrieving data in relational databases. It describes the basic functions of SQL like executing queries, inserting, updating, and deleting data. It also introduces some key concepts like RDBMS, tables, columns, and rows. Finally, it provides a sample table from a database as an example.

Uploaded by

Chito Cadena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 172

Noel P.

Cadena

1
MODULE 1: TABLE OF CONTENTS
SQL Introduction 3
Syntax 8
Select 10
Select Distinct 14
Where 20
And, Or, Not 23
Order By 41
Insert Into 63
Null Values 66
Update 71
Delete 76
Select Top 78
Min and Max 80
Count, Avg, Sum 81
Like 83
Wildcards 97
In 100
Between 101
Aliases 107
Joins 107
Inner Join 110
Left Join 111
Right Join 113
Full Join 115
Self Join 117
Union 118
Group By 121
Having 122
Exists 124
Any, All 125
Select Into 128
Insert Into Select 129
Case 131
Null Functions 132
Stored Procedure 133
Comments 135
Operators 137

2
SQL Introduction

SQL is a standard language for accessing and manipulating databases.

What is SQL?
 SQL stands for Structured Query Language
 SQL lets you access and manipulate databases
 SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987

What Can SQL do?


 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

SQL is a Standard - BUT....


Although SQL is an ANSI/ISO standard, there are different versions of the SQL language.

However, to be compliant with the ANSI standard, they all support at least the major commands (such
as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.

Note: Most of the SQL database programs also have their own proprietary extensions in addition to the
SQL standard!

RDBMS
RDBMS stands for Relational Database Management System.

RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2,
Oracle, MySQL, and Microsoft Access.

The data in RDBMS is stored in database objects called tables. A table is a collection of related data
entries and it consists of columns and rows.

Look at the "Customers" table:

Example

SELECT * FROM Customers;

3
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y Constitución 2222
helados

3 Antonio Moreno Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany


Delikatessen

7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg 67000 France

8 Bólido Comidas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain


preparadas

9 Bon app' Laurence Lebihans 12, rue des Marseille 13008 France
Bouchers

10 Bottom-Dollar Elizabeth Lincoln 23 Tsawassen Tsawassen T2F 8M4 Canada


Marketse Blvd.

11 B's Beverages Victoria Ashworth Fauntleroy Circus London EC2 5NT UK

12 Cactus Comidas Patricio Simpson Cerrito 333 Buenos Aires 1010 Argentina
para llevar

13 Centro comercial Francisco Chang Sierras de México D.F. 05022 Mexico


Moctezuma Granada 9993

14 Chop-suey Chinese Yang Wang Hauptstr. 29 Bern 3012 Switzerland

15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, São Paulo 05432-043 Brazil
23

16 Consolidated Elizabeth Brown Berkeley Gardens London WX1 6LT UK


Holdings 12 Brewery

17 Drachenblut Sven Ottlieb Walserweg 21 Aachen 52066 Germany


Delikatessend

18 Du monde entier Janine Labrune 67, rue des Nantes 44000 France
Cinquante Otages

19 Eastern Connection Ann Devon 35 King George London WX3 6FW UK

20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria

21 Familia Arquibaldo Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil

22 FISSA Fabrica Inter. Diego Roel C/ Moralzarzal, 86 Madrid 28034 Spain


Salchichas S.A.

4
23 Folies gourmandes Martine Rancé 184, chaussée de Lille 59000 France
Tournai

24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden

25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany

26 France restauration Carine Schmitt 54, rue Royale Nantes 44000 France

27 Franchi S.p.A. Paolo Accorti Via Monte Bianco Torino 10100 Italy
34

28 Furia Bacalhau e Lino Rodriguez Jardim das rosas Lisboa 1675 Portugal
Frutos do Mar n. 32

29 Galería del Eduardo Saavedra Rambla de Barcelona 08022 Spain


gastrónomo Cataluña, 23

30 Godos Cocina Típica José Pedro Freyre C/ Romero, 33 Sevilla 41101 Spain

31 Gourmet André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil


Lanchonetes

32 Great Lakes Food Howard Snyder 2732 Baker Blvd. Eugene 97403 USA
Market

33 GROSELLA- Manuel Pereira 5ª Ave. Los Palos Caracas 1081 Venezuela


Restaurante Grandes

34 Hanari Carnes Mario Pontes Rua do Paço, 67 Rio de 05454-876 Brazil


Janeiro

35 HILARIÓN-Abastos Carlos Hernández Carrera 22 con San 5022 Venezuela


Ave. Carlos Cristóbal
Soublette #8-35

36 Hungry Coyote Yoshi Latimer City Center Plaza Elgin 97827 USA
Import Store 516 Main St.

37 Hungry Owl All- Patricia McKenna 8 Johnstown Road Cork Ireland


Night Grocers

38 Island Trading Helen Bennett Garden House Cowes PO31 7PJ UK


Crowther Way

39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany

40 La corne Daniel Tonini 67, avenue de Versailles 78000 France


d'abondance l'Europe

41 La maison d'Asie Annette Roulet 1 rue Alsace- Toulouse 31000 France


Lorraine

42 Laughing Bacchus Yoshi Tannamuri 1900 Oak St. Vancouver V3F 2K1 Canada
Wine Cellars

43 Lazy K Kountry John Steel 12 Orchestra Walla Walla 99362 USA


Store Terrace

5
44 Lehmanns Renate Messner Magazinweg 7 Frankfurt 60528 Germany
Marktstand a.M.

45 Let's Stop N Shop Jaime Yorres 87 Polk St. Suite San 94117 USA
5 Francisco

46 LILA-Supermercado Carlos González Carrera 52 con Barquisimeto 3508 Venezuela


Ave. Bolívar #65-
98 Llano Largo

47 LINO-Delicateses Felipe Izquierdo Ave. 5 de Mayo I. de 4980 Venezuela


Porlamar Margarita

48 Lonesome Pine Fran Wilson 89 Chiaroscuro Portland 97219 USA


Restaurant Rd.

49 Magazzini Giovanni Rovelli Via Ludovico il Bergamo 24100 Italy


Alimentari Riuniti Moro 22

50 Maison Dewey Catherine Dewey Rue Joseph-Bens Bruxelles B-1180 Belgium


532

51 Mère Paillarde Jean Fresnière 43 rue St. Laurent Montréal H1J 1C3 Canada

52 Morgenstern Alexander Feuer Heerstr. 22 Leipzig 04179 Germany


Gesundkost

53 North/South Simon Crowther South House 300 London SW7 1RZ UK


Queensbridge

54 Océano Atlántico Yvonne Moncada Ing. Gustavo Buenos Aires 1010 Argentina
Ltda. Moncada 8585
Piso 20-A

55 Old World Rene Phillips 2743 Bering St. Anchorage 99508 USA
Delicatessen

56 Ottilies Käseladen Henriette Mehrheimerstr. Köln 50739 Germany


Pfalzheim 369

57 Paris spécialités Marie Bertrand 265, boulevard Paris 75012 France


Charonne

58 Pericles Comidas Guillermo Calle Dr. Jorge México D.F. 05033 Mexico
clásicas Fernández Cash 321

59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria

60 Princesa Isabel Isabel de Castro Estrada da saúde Lisboa 1756 Portugal


Vinhoss n. 58

61 Que Delícia Bernardo Batista Rua da Rio de 02389-673 Brazil


Panificadora, 12 Janeiro

62 Queen Cozinha Lúcia Carvalho Alameda dos São Paulo 05487-020 Brazil
Canàrios, 891

63 QUICK-Stop Horst Kloss Taucherstraße 10 Cunewalde 01307 Germany

6
64 Rancho grande Sergio Gutiérrez Av. del Libertador Buenos Aires 1010 Argentina
900

65 Rattlesnake Canyon Paula Wilson 2817 Milton Dr. Albuquerque 87110 USA
Grocery

66 Reggiani Caseifici Maurizio Moroni Strada Provinciale Reggio 42100 Italy


124 Emilia

67 Ricardo Adocicados Janete Limeira Av. Copacabana, Rio de 02389-890 Brazil


267 Janeiro

68 Richter Supermarkt Michael Holz Grenzacherweg Genève 1203 Switzerland


237

69 Romero y tomillo Alejandra Camino Gran Vía, 1 Madrid 28001 Spain

70 Santé Gourmet Jonas Bergulfsen Erling Skakkes Stavern 4110 Norway


gate 78

71 Save-a-lot Markets Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA

72 Seven Seas Imports Hari Kumar 90 Wadhurst Rd. London OX15 4NB UK

73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark

74 Spécialités du Dominique Perrier 25, rue Lauriston Paris 75016 France


monde

75 Split Rail Beer & Ale Art P.O. Box 555 Lander 82520 USA
Braunschweiger

76 Suprêmes délices Pascale Cartrain Boulevard Tirou, Charleroi B-6000 Belgium


255

77 The Big Cheese Liz Nixon 89 Jefferson Way Portland 97201 USA
Suite 2

78 The Cracker Box Liu Wong 55 Grizzly Peak Butte 59801 USA
Rd.

79 Toms Spezialitäten Karin Josephs Luisenstr. 48 Münster 44087 Germany

80 Tortuga Miguel Angel Avda. Azteca 123 México D.F. 05033 Mexico
Restaurante Paolino

81 Tradição Anabela Av. Inês de São Paulo 05634-030 Brazil


Hipermercados Domingues Castro, 414

82 Trail's Head Helvetius Nagy 722 DaVinci Blvd. Kirkland 98034 USA
Gourmet
Provisioners

83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark

84 Victuailles en stock Mary Saveley 2, rue du Lyon 69004 France


Commerce

85 Vins et alcools Paul Henriot 59 rue de Reims 51100 France


Chevalier l'Abbaye

7
86 Die Wandernde Kuh Rita Müller Adenauerallee 900 Stuttgart 70563 Germany

87 Wartian Herkku Pirkko Koskitalo Torikatu 38 Oulu 90110 Finland

88 Wellington Paula Parente Rua do Mercado, Resende 08737-363 Brazil


Importadora 12

89 White Clover Karl Jablonski 305 - 14th Ave. S. Seattle 98128 USA
Markets Suite 3B

90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

Table 1.0

Every table is broken up into smaller entities called fields. The fields in the Customers table consist of
CustomerID, CustomerName, ContactName, Address, City, PostalCode and Country. A field is a column
in a table that is designed to maintain specific information about every record in the table.

A record, also called a row, is each individual entry that exists in a table. For example, there are 91
records in the above Customers table. A record is a horizontal entity in a table.

A column is a vertical entity in a table that contains all information associated with a specific field in a
table.

SQL Syntax
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers"
or "Orders"). Tables contain records (rows) with data.

In this Module we will use the well-known Northwind sample database (included in MS Access and MS
SQL Server).

Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

8
2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico
Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

The table above contains five records (one for each customer) and seven columns (CustomerID,
CustomerName, ContactName, Address, City, PostalCode, and Country).

SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.

The following SQL statement selects all the records in the "Customers" table:

Example

SELECT * FROM Customers;


(see Table 1.0 to see the result)

Keep in Mind That...


 SQL keywords are NOT case sensitive: select is the same as SELECT

In this Module we will write all SQL keywords in upper-case.

Semicolon after SQL Statements?


Some database systems require a semicolon at the end of each SQL statement.

Semicolon is the standard way to separate each SQL statement in database systems that allow more
than one SQL statement to be executed in the same call to the server.

In this Module, we will use semicolon at the end of each SQL statement.

9
Some of The Most Important SQL Commands
 SELECT - extracts data from a database
 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index

SQL SELECT Statement


The SQL SELECT Statement
The SELECT statement is used to select data from a database.

The data returned is stored in a result table, called the result-set.

SELECT Syntax

SELECT column1, column2, ...


FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If you want to
select all the fields available in the table, use the following syntax:

SELECT * FROM table_name;

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222

10
3 Antonio Moreno Antonio Mataderos México 05023 Mexico
Taquería Moreno 2312 D.F.

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

SELECT Column Example


The following SQL statement selects the "CustomerName" and "City" columns from the "Customers"
table:

Example

SELECT CustomerName, City FROM Customers;

CustomerName City

Alfreds Futterkiste Berlin

Ana Trujillo Emparedados y helados México D.F.

Antonio Moreno Taquería México D.F.

Around the Horn London

Berglunds snabbköp Luleå

Blauer See Delikatessen Mannheim

Blondel père et fils Strasbourg

Bólido Comidas preparadas Madrid

Bon app' Marseille

Bottom-Dollar Marketse Tsawassen

B's Beverages London

Cactus Comidas para llevar Buenos Aires

Centro comercial Moctezuma México D.F.

Chop-suey Chinese Bern

11
Comércio Mineiro São Paulo

Consolidated Holdings London

Drachenblut Delikatessend Aachen

Du monde entier Nantes

Eastern Connection London

Ernst Handel Graz

Familia Arquibaldo São Paulo

FISSA Fabrica Inter. Salchichas S.A. Madrid

Folies gourmandes Lille

Folk och fä HB Bräcke

Frankenversand München

France restauration Nantes

Franchi S.p.A. Torino

Furia Bacalhau e Frutos do Mar Lisboa

Galería del gastrónomo Barcelona

Godos Cocina Típica Sevilla

Gourmet Lanchonetes Campinas

Great Lakes Food Market Eugene

GROSELLA-Restaurante Caracas

Hanari Carnes Rio de Janeiro

HILARIÓN-Abastos San Cristóbal

Hungry Coyote Import Store Elgin

Hungry Owl All-Night Grocers Cork

Island Trading Cowes

Königlich Essen Brandenburg

La corne d'abondance Versailles

La maison d'Asie Toulouse

Laughing Bacchus Wine Cellars Vancouver

12
Lazy K Kountry Store Walla Walla

Lehmanns Marktstand Frankfurt a.M.

Let's Stop N Shop San Francisco

LILA-Supermercado Barquisimeto

LINO-Delicateses I. de Margarita

Lonesome Pine Restaurant Portland

Magazzini Alimentari Riuniti Bergamo

Maison Dewey Bruxelles

Mère Paillarde Montréal

Morgenstern Gesundkost Leipzig

North/South London

Océano Atlántico Ltda. Buenos Aires

Old World Delicatessen Anchorage

Ottilies Käseladen Köln

Paris spécialités Paris

Pericles Comidas clásicas México D.F.

Piccolo und mehr Salzburg

Princesa Isabel Vinhoss Lisboa

Que Delícia Rio de Janeiro

Queen Cozinha São Paulo

QUICK-Stop Cunewalde

Rancho grande Buenos Aires

Rattlesnake Canyon Grocery Albuquerque

Reggiani Caseifici Reggio Emilia

Ricardo Adocicados Rio de Janeiro

Richter Supermarkt Genève

Romero y tomillo Madrid

Santé Gourmet Stavern

13
Save-a-lot Markets Boise

Seven Seas Imports London

Simons bistro København

Spécialités du monde Paris

Split Rail Beer & Ale Lander

Suprêmes délices Charleroi

The Big Cheese Portland

The Cracker Box Butte

Toms Spezialitäten Münster

Tortuga Restaurante México D.F.

Tradição Hipermercados São Paulo

Trail's Head Gourmet Provisioners Kirkland

Vaffeljernet Århus

Victuailles en stock Lyon

Vins et alcools Chevalier Reims

Die Wandernde Kuh Stuttgart

Wartian Herkku Oulu

Wellington Importadora Resende

White Clover Markets Seattle

Wilman Kala Helsinki

Wolski Walla

SQL SELECT DISTINCT Statement


The SQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct (different) values.

Inside a table, a column often contains many duplicate values; and sometimes you only want to list the
different (distinct) values.

SELECT DISTINCT Syntax

SELECT DISTINCT column1, column2, ...


FROM table_name;
14
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución 2222 D.F.
helados

3 Antonio Moreno Antonio Moreno Mataderos 2312 México 05023 Mexico


Taquería D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds Christina Berguvsvägen 8 Luleå S-958 22 Sweden


snabbköp Berglund

SELECT Example Without DISTINCT


The following SQL statement selects ALL (including the duplicates) values from the "Country" column in
the "Customers" table:

Example

SELECT Country FROM Customers;

Country

Germany

Mexico

Mexico

UK

15
Sweden

Germany

France

Spain

France

Canada

UK

Argentina

Mexico

Switzerland

Brazil

UK

Germany

France

UK

Austria

Brazil

Spain

France

Sweden

Germany

France

Italy

Portugal

Spain

Spain

Brazil

USA

Venezuela

16
Brazil

Venezuela

USA

Ireland

UK

Germany

France

France

Canada

USA

Germany

USA

Venezuela

Venezuela

USA

Italy

Belgium

Canada

Germany

UK

Argentina

USA

Germany

France

Mexico

Austria

Portugal

Brazil

Brazil

17
Germany

Argentina

USA

Italy

Brazil

Switzerland

Spain

Norway

USA

UK

Denmark

France

USA

Belgium

USA

USA

Germany

Mexico

Brazil

USA

Denmark

France

France

Germany

Finland

Brazil

USA

Finland

Poland

Now, let us use the DISTINCT keyword with the above SELECT statement and see the result.
18
SELECT DISTINCT Examples
The following SQL statement selects only the DISTINCT values from the "Country" column in the
"Customers" table:

Example

SELECT DISTINCT Country FROM Customers;

Country

Germany

Mexico

UK

Sweden

France

Spain

Canada

Argentina

Switzerland

Brazil

Austria

Italy

Portugal

USA

Venezuela

Ireland

Belgium

Norway

Denmark

Finland

Poland

The following SQL statement lists the number of different (distinct) customer countries:

Example

SELECT COUNT(DISTINCT Country) FROM Customers;

19
COUNT(DISTINCT Country)

21

Note: The example above will not work in Firefox! Because COUNT(DISTINCT column_name) is not
supported in Microsoft Access databases. Firefox is using Microsoft Access in our examples.

Here is the workaround for MS Access:

Example

SELECT Count(*) AS DistinctCountries


FROM (SELECT DISTINCT Country FROM Customers);

EXERCISES:

1. Insert the missing statement to get all the columns from the Customers table.

* FROM Customers;

2. Write a statement that will select the City column from the Customers table.

Customers;
3. Select all the different values from the Country column in the Customers table.

Country FROM Customers;

SQL WHERE Clause


The SQL WHERE Clause
The WHERE clause is used to filter records.

The WHERE clause is used to extract only those records that fulfill a specified condition.

WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Note: The WHERE clause is not only used in SELECT statement, it is also used in UPDATE, DELETE
statement, etc.!

20
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

WHERE Clause Example


The following SQL statement selects all the customers from the country "Mexico", in the "Customers"
table:

Example

SELECT * FROM Customers


WHERE Country='Mexico';

CustomerID CustomerName ContactName Address City PostalCode Country

2 Ana Trujillo Emparedados Ana Trujillo Avda. de la México 05021 Mexico


y helados Constitución D.F.
2222

3 Antonio Moreno Taquería Antonio Moreno Mataderos México 05023 Mexico


2312 D.F.

21
13 Centro comercial Francisco Chang Sierras de México 05022 Mexico
Moctezuma Granada D.F.
9993

58 Pericles Comidas clásicas Guillermo Calle Dr. México 05033 Mexico


Fernández Jorge Cash D.F.
321

80 Tortuga Restaurante Miguel Angel Avda. México 05033 Mexico


Paolino Azteca 123 D.F.

Text Fields vs. Numeric Fields


SQL requires single quotes around text values (most database systems will also allow double quotes).
However, numeric fields should not be enclosed in quotes:

Example

SELECT * FROM Customers


WHERE CustomerID=1;
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Berlin 12209 Germany


Futterkiste Str. 57

Operators in The WHERE Clause


The following operators can be used in the WHERE clause:

Operator Description

= Equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

<> Not equal. Note: In some versions of SQL this operator may be written as !=

BETWEEN Between a certain range

LIKE Search for a pattern

IN To specify multiple possible values for a column

22
SQL AND, OR and NOT Operators
The SQL AND, OR and NOT Operators
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND are TRUE.
The OR operator displays a record if any of the conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.

AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;

NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

Demo Database
The table below shows the complete "Customers" table from the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y Constitución 2222
helados

3 Antonio Moreno Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany


Delikatessen

7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg 67000 France

8 Bólido Comidas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain


preparadas

9 Bon app' Laurence Lebihans 12, rue des Marseille 13008 France
Bouchers

23
10 Bottom-Dollar Elizabeth Lincoln 23 Tsawassen Tsawassen T2F 8M4 Canada
Marketse Blvd.

11 B's Beverages Victoria Ashworth Fauntleroy Circus London EC2 5NT UK

12 Cactus Comidas Patricio Simpson Cerrito 333 Buenos Aires 1010 Argentina
para llevar

13 Centro comercial Francisco Chang Sierras de México D.F. 05022 Mexico


Moctezuma Granada 9993

14 Chop-suey Chinese Yang Wang Hauptstr. 29 Bern 3012 Switzerland

15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, São Paulo 05432-043 Brazil
23

16 Consolidated Elizabeth Brown Berkeley Gardens London WX1 6LT UK


Holdings 12 Brewery

17 Drachenblut Sven Ottlieb Walserweg 21 Aachen 52066 Germany


Delikatessend

18 Du monde entier Janine Labrune 67, rue des Nantes 44000 France
Cinquante Otages

19 Eastern Connection Ann Devon 35 King George London WX3 6FW UK

20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria

21 Familia Arquibaldo Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil

22 FISSA Fabrica Inter. Diego Roel C/ Moralzarzal, 86 Madrid 28034 Spain


Salchichas S.A.

23 Folies gourmandes Martine Rancé 184, chaussée de Lille 59000 France


Tournai

24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden

25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany

26 France restauration Carine Schmitt 54, rue Royale Nantes 44000 France

27 Franchi S.p.A. Paolo Accorti Via Monte Bianco Torino 10100 Italy
34

28 Furia Bacalhau e Lino Rodriguez Jardim das rosas Lisboa 1675 Portugal
Frutos do Mar n. 32

29 Galería del Eduardo Saavedra Rambla de Barcelona 08022 Spain


gastrónomo Cataluña, 23

30 Godos Cocina Típica José Pedro Freyre C/ Romero, 33 Sevilla 41101 Spain

31 Gourmet André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil


Lanchonetes

32 Great Lakes Food Howard Snyder 2732 Baker Blvd. Eugene 97403 USA
Market

24
33 GROSELLA- Manuel Pereira 5ª Ave. Los Palos Caracas 1081 Venezuela
Restaurante Grandes

34 Hanari Carnes Mario Pontes Rua do Paço, 67 Rio de 05454-876 Brazil


Janeiro

35 HILARIÓN-Abastos Carlos Hernández Carrera 22 con San 5022 Venezuela


Ave. Carlos Cristóbal
Soublette #8-35

36 Hungry Coyote Yoshi Latimer City Center Plaza Elgin 97827 USA
Import Store 516 Main St.

37 Hungry Owl All- Patricia McKenna 8 Johnstown Road Cork Ireland


Night Grocers

38 Island Trading Helen Bennett Garden House Cowes PO31 7PJ UK


Crowther Way

39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany

40 La corne Daniel Tonini 67, avenue de Versailles 78000 France


d'abondance l'Europe

41 La maison d'Asie Annette Roulet 1 rue Alsace- Toulouse 31000 France


Lorraine

42 Laughing Bacchus Yoshi Tannamuri 1900 Oak St. Vancouver V3F 2K1 Canada
Wine Cellars

43 Lazy K Kountry John Steel 12 Orchestra Walla Walla 99362 USA


Store Terrace

44 Lehmanns Renate Messner Magazinweg 7 Frankfurt 60528 Germany


Marktstand a.M.

45 Let's Stop N Shop Jaime Yorres 87 Polk St. Suite San 94117 USA
5 Francisco

46 LILA-Supermercado Carlos González Carrera 52 con Barquisimeto 3508 Venezuela


Ave. Bolívar #65-
98 Llano Largo

47 LINO-Delicateses Felipe Izquierdo Ave. 5 de Mayo I. de 4980 Venezuela


Porlamar Margarita

48 Lonesome Pine Fran Wilson 89 Chiaroscuro Portland 97219 USA


Restaurant Rd.

49 Magazzini Giovanni Rovelli Via Ludovico il Bergamo 24100 Italy


Alimentari Riuniti Moro 22

50 Maison Dewey Catherine Dewey Rue Joseph-Bens Bruxelles B-1180 Belgium


532

51 Mère Paillarde Jean Fresnière 43 rue St. Laurent Montréal H1J 1C3 Canada

52 Morgenstern Alexander Feuer Heerstr. 22 Leipzig 04179 Germany


Gesundkost

25
53 North/South Simon Crowther South House 300 London SW7 1RZ UK
Queensbridge

54 Océano Atlántico Yvonne Moncada Ing. Gustavo Buenos Aires 1010 Argentina
Ltda. Moncada 8585
Piso 20-A

55 Old World Rene Phillips 2743 Bering St. Anchorage 99508 USA
Delicatessen

56 Ottilies Käseladen Henriette Mehrheimerstr. Köln 50739 Germany


Pfalzheim 369

57 Paris spécialités Marie Bertrand 265, boulevard Paris 75012 France


Charonne

58 Pericles Comidas Guillermo Calle Dr. Jorge México D.F. 05033 Mexico
clásicas Fernández Cash 321

59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria

60 Princesa Isabel Isabel de Castro Estrada da saúde Lisboa 1756 Portugal


Vinhoss n. 58

61 Que Delícia Bernardo Batista Rua da Rio de 02389-673 Brazil


Panificadora, 12 Janeiro

62 Queen Cozinha Lúcia Carvalho Alameda dos São Paulo 05487-020 Brazil
Canàrios, 891

63 QUICK-Stop Horst Kloss Taucherstraße 10 Cunewalde 01307 Germany

64 Rancho grande Sergio Gutiérrez Av. del Libertador Buenos Aires 1010 Argentina
900

65 Rattlesnake Canyon Paula Wilson 2817 Milton Dr. Albuquerque 87110 USA
Grocery

66 Reggiani Caseifici Maurizio Moroni Strada Provinciale Reggio 42100 Italy


124 Emilia

67 Ricardo Adocicados Janete Limeira Av. Copacabana, Rio de 02389-890 Brazil


267 Janeiro

68 Richter Supermarkt Michael Holz Grenzacherweg Genève 1203 Switzerland


237

69 Romero y tomillo Alejandra Camino Gran Vía, 1 Madrid 28001 Spain

70 Santé Gourmet Jonas Bergulfsen Erling Skakkes Stavern 4110 Norway


gate 78

71 Save-a-lot Markets Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA

72 Seven Seas Imports Hari Kumar 90 Wadhurst Rd. London OX15 4NB UK

73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark

74 Spécialités du Dominique Perrier 25, rue Lauriston Paris 75016 France


monde

26
75 Split Rail Beer & Ale Art P.O. Box 555 Lander 82520 USA
Braunschweiger

76 Suprêmes délices Pascale Cartrain Boulevard Tirou, Charleroi B-6000 Belgium


255

77 The Big Cheese Liz Nixon 89 Jefferson Way Portland 97201 USA
Suite 2

78 The Cracker Box Liu Wong 55 Grizzly Peak Butte 59801 USA
Rd.

79 Toms Spezialitäten Karin Josephs Luisenstr. 48 Münster 44087 Germany

80 Tortuga Miguel Angel Avda. Azteca 123 México D.F. 05033 Mexico
Restaurante Paolino

81 Tradição Anabela Av. Inês de São Paulo 05634-030 Brazil


Hipermercados Domingues Castro, 414

82 Trail's Head Helvetius Nagy 722 DaVinci Blvd. Kirkland 98034 USA
Gourmet
Provisioners

83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark

84 Victuailles en stock Mary Saveley 2, rue du Lyon 69004 France


Commerce

85 Vins et alcools Paul Henriot 59 rue de Reims 51100 France


Chevalier l'Abbaye

86 Die Wandernde Kuh Rita Müller Adenauerallee 900 Stuttgart 70563 Germany

87 Wartian Herkku Pirkko Koskitalo Torikatu 38 Oulu 90110 Finland

88 Wellington Paula Parente Rua do Mercado, Resende 08737-363 Brazil


Importadora 12

89 White Clover Karl Jablonski 305 - 14th Ave. S. Seattle 98128 USA
Markets Suite 3B

90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

AND Example
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city is
"Berlin":

Example
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';

CustomerID CustomerName ContactName Address City PostalCode Country

27
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

OR Example
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "München":

Example
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Berlin 12209 Germany


Futterkiste Str. 57

25 Frankenversand Peter Franken Berliner München 80805 Germany


Platz 43

The following SQL statement selects all fields from "Customers" where country is "Germany" OR
"Spain":

Example
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany


Delikatessen

8 Bólido Comidas Martín C/ Araquil, 67 Madrid 28023 Spain


preparadas Sommer

17 Drachenblut Sven Ottlieb Walserweg 21 Aachen 52066 Germany


Delikatessend

22 FISSA Fabrica Diego Roel C/ Moralzarzal, Madrid 28034 Spain


Inter. Salchichas 86
S.A.

25 Frankenversand Peter Franken Berliner Platz München 80805 Germany


43

29 Galería del Eduardo Rambla de Barcelona 08022 Spain


gastrónomo Saavedra Cataluña, 23

30 Godos Cocina José Pedro C/ Romero, 33 Sevilla 41101 Spain


Típica Freyre

28
39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany

44 Lehmanns Renate Magazinweg 7 Frankfurt 60528 Germany


Marktstand Messner a.M.

52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 Germany


Gesundkost Feuer

56 Ottilies Henriette Mehrheimerstr. Köln 50739 Germany


Käseladen Pfalzheim 369

63 QUICK-Stop Horst Kloss Taucherstraße Cunewalde 01307 Germany


10

69 Romero y tomillo Alejandra Gran Vía, 1 Madrid 28001 Spain


Camino

79 Toms Karin Josephs Luisenstr. 48 Münster 44087 Germany


Spezialitäten

86 Die Wandernde Rita Müller Adenauerallee Stuttgart 70563 Germany


Kuh 900

NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT "Germany":

Example
SELECT * FROM Customers
WHERE NOT Country='Germany';

CustomerID CustomerName ContactName Address City PostalCode Country

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y Constitución
helados 2222

3 Antonio Antonio Mataderos México D.F. 05023 Mexico


Moreno Moreno 2312
Taquería

4 Around the Thomas Hardy 120 Hanover London WA1 1DP UK


Horn Sq.

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

29
7 Blondel père et Frédérique 24, place Strasbourg 67000 France
fils Citeaux Kléber

8 Bólido Comidas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain


preparadas

9 Bon app' Laurence 12, rue des Marseille 13008 France


Lebihans Bouchers

10 Bottom-Dollar Elizabeth 23 Tsawassen Tsawassen T2F 8M4 Canada


Marketse Lincoln Blvd.

11 B's Beverages Victoria Fauntleroy London EC2 5NT UK


Ashworth Circus

12 Cactus Comidas Patricio Cerrito 333 Buenos Aires 1010 Argentina


para llevar Simpson

13 Centro Francisco Sierras de México D.F. 05022 Mexico


comercial Chang Granada 9993
Moctezuma

14 Chop-suey Yang Wang Hauptstr. 29 Bern 3012 Switzerland


Chinese

15 Comércio Pedro Afonso Av. dos São Paulo 05432-043 Brazil


Mineiro Lusíadas, 23

16 Consolidated Elizabeth Berkeley London WX1 6LT UK


Holdings Brown Gardens 12
Brewery

18 Du monde Janine Labrune 67, rue des Nantes 44000 France


entier Cinquante
Otages

19 Eastern Ann Devon 35 King George London WX3 6FW UK


Connection

30
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria

21 Familia Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil


Arquibaldo

22 FISSA Fabrica Diego Roel C/ Moralzarzal, Madrid 28034 Spain


Inter. 86
Salchichas S.A.

23 Folies Martine Rancé 184, chaussée Lille 59000 France


gourmandes de Tournai

24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden

26 France Carine Schmitt 54, rue Royale Nantes 44000 France


restauration

27 Franchi S.p.A. Paolo Accorti Via Monte Torino 10100 Italy


Bianco 34

28 Furia Bacalhau Lino Rodriguez Jardim das Lisboa 1675 Portugal


e Frutos do rosas n. 32
Mar

29 Galería del Eduardo Rambla de Barcelona 08022 Spain


gastrónomo Saavedra Cataluña, 23

30 Godos Cocina José Pedro C/ Romero, 33 Sevilla 41101 Spain


Típica Freyre

31 Gourmet André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil


Lanchonetes

32 Great Lakes Howard Snyder 2732 Baker Eugene 97403 USA


Food Market Blvd.

33 GROSELLA- Manuel Pereira 5ª Ave. Los Caracas 1081 Venezuela


Restaurante Palos Grandes

31
34 Hanari Carnes Mario Pontes Rua do Paço, Rio de 05454-876 Brazil
67 Janeiro

35 HILARIÓN- Carlos Carrera 22 con San Cristóbal 5022 Venezuela


Abastos Hernández Ave. Carlos
Soublette #8-
35

36 Hungry Coyote Yoshi Latimer City Center Elgin 97827 USA


Import Store Plaza 516 Main
St.

37 Hungry Owl All- Patricia 8 Johnstown Cork Ireland


Night Grocers McKenna Road

38 Island Trading Helen Bennett Garden House Cowes PO31 7PJ UK


Crowther Way

40 La corne Daniel Tonini 67, avenue de Versailles 78000 France


d'abondance l'Europe

41 La maison Annette Roulet 1 rue Alsace- Toulouse 31000 France


d'Asie Lorraine

42 Laughing Yoshi 1900 Oak St. Vancouver V3F 2K1 Canada


Bacchus Wine Tannamuri
Cellars

43 Lazy K Kountry John Steel 12 Orchestra Walla Walla 99362 USA


Store Terrace

45 Let's Stop N Jaime Yorres 87 Polk St. San 94117 USA


Shop Suite 5 Francisco

46 LILA- Carlos González Carrera 52 con Barquisimeto 3508 Venezuela


Supermercado Ave. Bolívar
#65-98 Llano
Largo

32
47 LINO- Felipe Izquierdo Ave. 5 de Mayo I. de 4980 Venezuela
Delicateses Porlamar Margarita

48 Lonesome Pine Fran Wilson 89 Chiaroscuro Portland 97219 USA


Restaurant Rd.

49 Magazzini Giovanni Via Ludovico il Bergamo 24100 Italy


Alimentari Rovelli Moro 22
Riuniti

50 Maison Dewey Catherine Rue Joseph- Bruxelles B-1180 Belgium


Dewey Bens 532

51 Mère Paillarde Jean Fresnière 43 rue St. Montréal H1J 1C3 Canada
Laurent

53 North/South Simon South House London SW7 1RZ UK


Crowther 300
Queensbridge

54 Océano Yvonne Ing. Gustavo Buenos Aires 1010 Argentina


Atlántico Ltda. Moncada Moncada 8585
Piso 20-A

55 Old World Rene Phillips 2743 Bering St. Anchorage 99508 USA
Delicatessen

57 Paris spécialités Marie Bertrand 265, boulevard Paris 75012 France


Charonne

58 Pericles Guillermo Calle Dr. Jorge México D.F. 05033 Mexico


Comidas Fernández Cash 321
clásicas

59 Piccolo und Georg Pipps Geislweg 14 Salzburg 5020 Austria


mehr

60 Princesa Isabel Isabel de Castro Estrada da Lisboa 1756 Portugal


Vinhoss saúde n. 58

33
61 Que Delícia Bernardo Rua da Rio de 02389-673 Brazil
Batista Panificadora, Janeiro
12

62 Queen Cozinha Lúcia Carvalho Alameda dos São Paulo 05487-020 Brazil
Canàrios, 891

64 Rancho grande Sergio Av. del Buenos Aires 1010 Argentina


Gutiérrez Libertador 900

65 Rattlesnake Paula Wilson 2817 Milton Albuquerque 87110 USA


Canyon Dr.
Grocery

66 Reggiani Maurizio Strada Reggio Emilia 42100 Italy


Caseifici Moroni Provinciale 124

67 Ricardo Janete Limeira Av. Rio de 02389-890 Brazil


Adocicados Copacabana, Janeiro
267

68 Richter Michael Holz Grenzacherweg Genève 1203 Switzerland


Supermarkt 237

69 Romero y Alejandra Gran Vía, 1 Madrid 28001 Spain


tomillo Camino

70 Santé Gourmet Jonas Erling Skakkes Stavern 4110 Norway


Bergulfsen gate 78

71 Save-a-lot Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA


Markets

72 Seven Seas Hari Kumar 90 Wadhurst London OX15 4NB UK


Imports Rd.

73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark

34
74 Spécialités du Dominique 25, rue Paris 75016 France
monde Perrier Lauriston

75 Split Rail Beer Art P.O. Box 555 Lander 82520 USA
& Ale Braunschweiger

76 Suprêmes Pascale Cartrain Boulevard Charleroi B-6000 Belgium


délices Tirou, 255

77 The Big Cheese Liz Nixon 89 Jefferson Portland 97201 USA


Way Suite 2

78 The Cracker Liu Wong 55 Grizzly Peak Butte 59801 USA


Box Rd.

80 Tortuga Miguel Angel Avda. Azteca México D.F. 05033 Mexico


Restaurante Paolino 123

81 Tradição Anabela Av. Inês de São Paulo 05634-030 Brazil


Hipermercados Domingues Castro, 414

82 Trail's Head Helvetius Nagy 722 DaVinci Kirkland 98034 USA


Gourmet Blvd.
Provisioners

83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark

84 Victuailles en Mary Saveley 2, rue du Lyon 69004 France


stock Commerce

85 Vins et alcools Paul Henriot 59 rue de Reims 51100 France


Chevalier l'Abbaye

87 Wartian Herkku Pirkko Koskitalo Torikatu 38 Oulu 90110 Finland

88 Wellington Paula Parente Rua do Resende 08737-363 Brazil


Importadora Mercado, 12

35
89 White Clover Karl Jablonski 305 - 14th Ave. Seattle 98128 USA
Markets S. Suite 3B

90 Wilman Kala Matti Keskuskatu 45 Helsinki 21240 Finland


Karttunen

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

Combining AND, OR and NOT


You can also combine the AND, OR and NOT operators.

The following SQL statement selects all fields from "Customers" where country is "Germany" AND city
must be "Berlin" OR "München" (use parenthesis to form complex expressions):

Example
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Berlin 12209 Germany


Futterkiste Str. 57

25 Frankenversand Peter Franken Berliner München 80805 Germany


Platz 43

The following SQL statement selects all fields from "Customers" where country is NOT "Germany" and
NOT "USA":

Example
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
Customer CustomerNa ContactNa Address City PostalCo Country
ID me me de

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados Constitución D.F.
y helados 2222

3 Antonio Antonio Mataderos México 05023 Mexico


Moreno Moreno 2312 D.F.
Taquería

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

36
5 Berglunds Christina Berguvsväge Luleå S-958 22 Sweden
snabbköp Berglund n8

7 Blondel père Frédérique 24, place Strasbourg 67000 France


et fils Citeaux Kléber

8 Bólido Martín C/ Araquil, Madrid 28023 Spain


Comidas Sommer 67
preparadas

9 Bon app' Laurence 12, rue des Marseille 13008 France


Lebihans Bouchers

10 Bottom-Dollar Elizabeth 23 Tsawassen T2F 8M4 Canada


Marketse Lincoln Tsawassen
Blvd.

11 B's Beverages Victoria Fauntleroy London EC2 5NT UK


Ashworth Circus

12 Cactus Patricio Cerrito 333 Buenos 1010 Argentina


Comidas para Simpson Aires
llevar

13 Centro Francisco Sierras de México 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

14 Chop-suey Yang Wang Hauptstr. 29 Bern 3012 Switzerla


Chinese nd

15 Comércio Pedro Av. dos São Paulo 05432- Brazil


Mineiro Afonso Lusíadas, 23 043

16 Consolidated Elizabeth Berkeley London WX1 6LT UK


Holdings Brown Gardens 12
Brewery

18 Du monde Janine 67, rue des Nantes 44000 France


entier Labrune Cinquante
Otages

19 Eastern Ann Devon 35 King London WX3 6FW UK


Connection George

20 Ernst Handel Roland Kirchgasse 6 Graz 8010 Austria


Mendel

21 Familia Aria Cruz Rua Orós, São Paulo 05442- Brazil


Arquibaldo 92 030

22 FISSA Fabrica Diego Roel C/ Madrid 28034 Spain


Inter. Moralzarzal,
Salchichas 86
S.A.

37
23 Folies Martine 184, Lille 59000 France
gourmandes Rancé chaussée de
Tournai

24 Folk och fä HB Maria Åkergatan Bräcke S-844 67 Sweden


Larsson 24

26 France Carine 54, rue Nantes 44000 France


restauration Schmitt Royale

27 Franchi S.p.A. Paolo Via Monte Torino 10100 Italy


Accorti Bianco 34

28 Furia Lino Jardim das Lisboa 1675 Portugal


Bacalhau e Rodriguez rosas n. 32
Frutos do Mar

29 Galería del Eduardo Rambla de Barcelona 08022 Spain


gastrónomo Saavedra Cataluña, 23

30 Godos Cocina José Pedro C/ Romero, Sevilla 41101 Spain


Típica Freyre 33

31 Gourmet André Av. Brasil, Campinas 04876- Brazil


Lanchonetes Fonseca 442 786

33 GROSELLA- Manuel 5ª Ave. Los Caracas 1081 Venezuel


Restaurante Pereira Palos a
Grandes

34 Hanari Carnes Mario Rua do Paço, Rio de 05454- Brazil


Pontes 67 Janeiro 876

35 HILARIÓN- Carlos Carrera 22 San 5022 Venezuel


Abastos Hernández con Ave. Cristóbal a
Carlos
Soublette
#8-35

37 Hungry Owl Patricia 8 Johnstown Cork Ireland


All-Night McKenna Road
Grocers

38 Island Trading Helen Garden Cowes PO31 7PJ UK


Bennett House
Crowther
Way

40 La corne Daniel 67, avenue Versailles 78000 France


d'abondance Tonini de l'Europe

41 La maison Annette 1 rue Toulouse 31000 France


d'Asie Roulet Alsace-
Lorraine

38
42 Laughing Yoshi 1900 Oak Vancouver V3F 2K1 Canada
Bacchus Wine Tannamuri St.
Cellars

46 LILA- Carlos Carrera 52 Barquisim 3508 Venezuel


Supermercado González con Ave. eto a
Bolívar #65-
98 Llano
Largo

47 LINO- Felipe Ave. 5 de I. de 4980 Venezuel


Delicateses Izquierdo Mayo Margarita a
Porlamar

49 Magazzini Giovanni Via Ludovico Bergamo 24100 Italy


Alimentari Rovelli il Moro 22
Riuniti

50 Maison Dewey Catherine Rue Joseph- Bruxelles B-1180 Belgium


Dewey Bens 532

51 Mère Paillarde Jean 43 rue St. Montréal H1J 1C3 Canada


Fresnière Laurent

53 North/South Simon South House London SW7 1RZ UK


Crowther 300
Queensbridg
e

54 Océano Yvonne Ing. Gustavo Buenos 1010 Argentina


Atlántico Ltda. Moncada Moncada Aires
8585 Piso
20-A

57 Paris Marie 265, Paris 75012 France


spécialités Bertrand boulevard
Charonne

58 Pericles Guillermo Calle Dr. México 05033 Mexico


Comidas Fernández Jorge Cash D.F.
clásicas 321

59 Piccolo und Georg Pipps Geislweg 14 Salzburg 5020 Austria


mehr

60 Princesa Isabel de Estrada da Lisboa 1756 Portugal


Isabel Vinhoss Castro saúde n. 58

61 Que Delícia Bernardo Rua da Rio de 02389- Brazil


Batista Panificadora, Janeiro 673
12

62 Queen Lúcia Alameda dos São Paulo 05487- Brazil


Cozinha Carvalho Canàrios, 020
891

39
64 Rancho Sergio Av. del Buenos 1010 Argentina
grande Gutiérrez Libertador Aires
900

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacabana, Janeiro 890
267

68 Richter Michael Holz Grenzacherw Genève 1203 Switzerla


Supermarkt eg 237 nd

69 Romero y Alejandra Gran Vía, 1 Madrid 28001 Spain


tomillo Camino

70 Santé Jonas Erling Stavern 4110 Norway


Gourmet Bergulfsen Skakkes
gate 78

72 Seven Seas Hari Kumar 90 Wadhurst London OX15 4NB UK


Imports Rd.

73 Simons bistro Jytte Vinbæltet 34 Københav 1734 Denmark


Petersen n

74 Spécialités du Dominique 25, rue Paris 75016 France


monde Perrier Lauriston

76 Suprêmes Pascale Boulevard Charleroi B-6000 Belgium


délices Cartrain Tirou, 255

80 Tortuga Miguel Avda. Azteca México 05033 Mexico


Restaurante Angel 123 D.F.
Paolino

81 Tradição Anabela Av. Inês de São Paulo 05634- Brazil


Hipermercado Domingues Castro, 414 030
s

83 Vaffeljernet Palle Ibsen Smagsløget Århus 8200 Denmark


45

84 Victuailles en Mary 2, rue du Lyon 69004 France


stock Saveley Commerce

85 Vins et alcools Paul Henriot 59 rue de Reims 51100 France


Chevalier l'Abbaye

87 Wartian Pirkko Torikatu 38 Oulu 90110 Finland


Herkku Koskitalo

88 Wellington Paula Rua do Resende 08737- Brazil


Importadora Parente Mercado, 12 363

40
90 Wilman Kala Matti Keskuskatu Helsinki 21240 Finland
Karttunen 45

91 Wolski Zbyszek ul. Filtrowa Walla 01-012 Poland


68

EXERCISES:

1. Select all records where the City column has the value "Berlin".
SELECT * FROM Customers _____ ____ = ________;
2. Use the NOT keyword to select all records where City is NOT "Berlin".
SELECT * FROM Customers _____ ___ ____ = ________;
3. Select all records where the CustomerID column has the value 32.
SELECT * FROM Customers _____ CustomerID _ ____;
4. Select all records where the City column has the value 'Berlin' and the PostalCode column has
the value 12209.
______ * from Customers _____ City = ‘Berlin’ ___ ___________ = 12209;
5. Select all records where the City column has the value 'Berlin' or 'London'.
6. ______ * from Customers _____ City = ‘Berlin’ __ ____ = ‘London’;

SQL ORDER BY Keyword


The SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.

ORDER BY Syntax

SELECT column1, column2, ...


FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

Demo Database

Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

41
2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico
Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country"
column:

Example
SELECT * FROM Customers
ORDER BY Country;
CustomerID CustomerName ContactName Address City PostalCode Country

12 Cactus Comidas Patricio Cerrito 333 Buenos Aires 1010 Argentina


para llevar Simpson

54 Océano Atlántico Yvonne Ing. Gustavo Buenos Aires 1010 Argentina


Ltda. Moncada Moncada 8585
Piso 20-A

64 Rancho grande Sergio Av. del Buenos Aires 1010 Argentina


Gutiérrez Libertador 900

20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria

59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria

50 Maison Dewey Catherine Rue Joseph- Bruxelles B-1180 Belgium


Dewey Bens 532

76 Suprêmes Pascale Boulevard Charleroi B-6000 Belgium


délices Cartrain Tirou, 255

42
15 Comércio Pedro Afonso Av. dos São Paulo 05432-043 Brazil
Mineiro Lusíadas, 23

21 Familia Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil


Arquibaldo

31 Gourmet André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil


Lanchonetes

34 Hanari Carnes Mario Pontes Rua do Paço, Rio de 05454-876 Brazil


67 Janeiro

61 Que Delícia Bernardo Rua da Rio de 02389-673 Brazil


Batista Panificadora, Janeiro
12

62 Queen Cozinha Lúcia Carvalho Alameda dos São Paulo 05487-020 Brazil
Canàrios, 891

67 Ricardo Janete Limeira Av. Rio de 02389-890 Brazil


Adocicados Copacabana, Janeiro
267

81 Tradição Anabela Av. Inês de São Paulo 05634-030 Brazil


Hipermercados Domingues Castro, 414

88 Wellington Paula Parente Rua do Resende 08737-363 Brazil


Importadora Mercado, 12

10 Bottom-Dollar Elizabeth 23 Tsawassen Tsawassen T2F 8M4 Canada


Marketse Lincoln Blvd.

42 Laughing Yoshi 1900 Oak St. Vancouver V3F 2K1 Canada


Bacchus Wine Tannamuri
Cellars

51 Mère Paillarde Jean Fresnière 43 rue St. Montréal H1J 1C3 Canada
Laurent

73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark

83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark

87 Wartian Herkku Pirkko Torikatu 38 Oulu 90110 Finland


Koskitalo

90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland

7 Blondel père et Frédérique 24, place Strasbourg 67000 France


fils Citeaux Kléber

9 Bon app' Laurence 12, rue des Marseille 13008 France


Lebihans Bouchers

43
18 Du monde entier Janine Labrune 67, rue des Nantes 44000 France
Cinquante
Otages

23 Folies Martine Rancé 184, chaussée Lille 59000 France


gourmandes de Tournai

26 France Carine Schmitt 54, rue Royale Nantes 44000 France


restauration

40 La corne Daniel Tonini 67, avenue de Versailles 78000 France


d'abondance l'Europe

41 La maison d'Asie Annette Roulet 1 rue Alsace- Toulouse 31000 France


Lorraine

57 Paris spécialités Marie Bertrand 265, boulevard Paris 75012 France


Charonne

74 Spécialités du Dominique 25, rue Paris 75016 France


monde Perrier Lauriston

84 Victuailles en Mary Saveley 2, rue du Lyon 69004 France


stock Commerce

85 Vins et alcools Paul Henriot 59 rue de Reims 51100 France


Chevalier l'Abbaye

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany


Delikatessen

17 Drachenblut Sven Ottlieb Walserweg 21 Aachen 52066 Germany


Delikatessend

25 Frankenversand Peter Franken Berliner Platz München 80805 Germany


43

39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany

44 Lehmanns Renate Magazinweg 7 Frankfurt 60528 Germany


Marktstand Messner a.M.

52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 Germany


Gesundkost Feuer

56 Ottilies Henriette Mehrheimerstr. Köln 50739 Germany


Käseladen Pfalzheim 369

63 QUICK-Stop Horst Kloss Taucherstraße Cunewalde 01307 Germany


10

79 Toms Karin Josephs Luisenstr. 48 Münster 44087 Germany


Spezialitäten

44
86 Die Wandernde Rita Müller Adenauerallee Stuttgart 70563 Germany
Kuh 900

37 Hungry Owl All- Patricia 8 Johnstown Cork Ireland


Night Grocers McKenna Road

27 Franchi S.p.A. Paolo Accorti Via Monte Torino 10100 Italy


Bianco 34

49 Magazzini Giovanni Via Ludovico il Bergamo 24100 Italy


Alimentari Rovelli Moro 22
Riuniti

66 Reggiani Maurizio Moroni Strada Reggio 42100 Italy


Caseifici Provinciale 124 Emilia

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y Constitución
helados 2222

3 Antonio Moreno Antonio Moreno Mataderos México D.F. 05023 Mexico


Taquería 2312

13 Centro comercial Francisco Sierras de México D.F. 05022 Mexico


Moctezuma Chang Granada 9993

58 Pericles Comidas Guillermo Calle Dr. Jorge México D.F. 05033 Mexico
clásicas Fernández Cash 321

80 Tortuga Miguel Angel Avda. Azteca México D.F. 05033 Mexico


Restaurante Paolino 123

70 Santé Gourmet Jonas Erling Skakkes Stavern 4110 Norway


Bergulfsen gate 78

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

28 Furia Bacalhau e Lino Rodriguez Jardim das Lisboa 1675 Portugal


Frutos do Mar rosas n. 32

60 Princesa Isabel Isabel de Estrada da Lisboa 1756 Portugal


Vinhoss Castro saúde n. 58

8 Bólido Comidas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain


preparadas

22 FISSA Fabrica Diego Roel C/ Moralzarzal, Madrid 28034 Spain


Inter. Salchichas 86
S.A.

29 Galería del Eduardo Rambla de Barcelona 08022 Spain


gastrónomo Saavedra Cataluña, 23

30 Godos Cocina José Pedro C/ Romero, 33 Sevilla 41101 Spain


Típica Freyre

45
69 Romero y tomillo Alejandra Gran Vía, 1 Madrid 28001 Spain
Camino

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden

14 Chop-suey Yang Wang Hauptstr. 29 Bern 3012 Switzerland


Chinese

68 Richter Michael Holz Grenzacherweg Genève 1203 Switzerland


Supermarkt 237

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.

11 B's Beverages Victoria Fauntleroy London EC2 5NT UK


Ashworth Circus

16 Consolidated Elizabeth Berkeley London WX1 6LT UK


Holdings Brown Gardens 12
Brewery

19 Eastern Ann Devon 35 King London WX3 6FW UK


Connection George

38 Island Trading Helen Bennett Garden House Cowes PO31 7PJ UK


Crowther Way

53 North/South Simon South House London SW7 1RZ UK


Crowther 300
Queensbridge

72 Seven Seas Hari Kumar 90 Wadhurst London OX15 4NB UK


Imports Rd.

32 Great Lakes Howard Snyder 2732 Baker Eugene 97403 USA


Food Market Blvd.

36 Hungry Coyote Yoshi Latimer City Center Elgin 97827 USA


Import Store Plaza 516 Main
St.

43 Lazy K Kountry John Steel 12 Orchestra Walla Walla 99362 USA


Store Terrace

45 Let's Stop N Jaime Yorres 87 Polk St. San 94117 USA


Shop Suite 5 Francisco

48 Lonesome Pine Fran Wilson 89 Chiaroscuro Portland 97219 USA


Restaurant Rd.

55 Old World Rene Phillips 2743 Bering Anchorage 99508 USA


Delicatessen St.

46
65 Rattlesnake Paula Wilson 2817 Milton Albuquerque 87110 USA
Canyon Grocery Dr.

71 Save-a-lot Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA


Markets

75 Split Rail Beer & Art P.O. Box 555 Lander 82520 USA
Ale Braunschweiger

77 The Big Cheese Liz Nixon 89 Jefferson Portland 97201 USA


Way Suite 2

78 The Cracker Box Liu Wong 55 Grizzly Peak Butte 59801 USA
Rd.

82 Trail's Head Helvetius Nagy 722 DaVinci Kirkland 98034 USA


Gourmet Blvd.
Provisioners

89 White Clover Karl Jablonski 305 - 14th Seattle 98128 USA


Markets Ave. S. Suite
3B

33 GROSELLA- Manuel Pereira 5ª Ave. Los Caracas 1081 Venezuela


Restaurante Palos Grandes

35 HILARIÓN- Carlos Carrera 22 con San 5022 Venezuela


Abastos Hernández Ave. Carlos Cristóbal
Soublette #8-
35

46 LILA- Carlos Carrera 52 con Barquisimeto 3508 Venezuela


Supermercado González Ave. Bolívar
#65-98 Llano
Largo

47 LINO- Felipe Ave. 5 de I. de 4980 Venezuela


Delicateses Izquierdo Mayo Porlamar Margarita

ORDER BY DESC Example


The following SQL statement selects all customers from the "Customers" table, sorted DESCENDING by
the "Country" column:

Example
SELECT * FROM Customers
ORDER BY Country DESC;
CustomerID CustomerName ContactName Address City PostalCode Country

33 GROSELLA- Manuel Pereira 5ª Ave. Los Caracas 1081 Venezuela


Restaurante Palos Grandes

35 HILARIÓN- Carlos Carrera 22 con San 5022 Venezuela


Abastos Hernández Ave. Carlos Cristóbal

47
Soublette #8-
35

46 LILA- Carlos Carrera 52 con Barquisimeto 3508 Venezuela


Supermercado González Ave. Bolívar
#65-98 Llano
Largo

47 LINO- Felipe Ave. 5 de I. de 4980 Venezuela


Delicateses Izquierdo Mayo Porlamar Margarita

32 Great Lakes Howard Snyder 2732 Baker Eugene 97403 USA


Food Market Blvd.

36 Hungry Coyote Yoshi Latimer City Center Elgin 97827 USA


Import Store Plaza 516 Main
St.

43 Lazy K Kountry John Steel 12 Orchestra Walla Walla 99362 USA


Store Terrace

45 Let's Stop N Jaime Yorres 87 Polk St. San 94117 USA


Shop Suite 5 Francisco

48 Lonesome Pine Fran Wilson 89 Chiaroscuro Portland 97219 USA


Restaurant Rd.

55 Old World Rene Phillips 2743 Bering Anchorage 99508 USA


Delicatessen St.

65 Rattlesnake Paula Wilson 2817 Milton Albuquerque 87110 USA


Canyon Grocery Dr.

71 Save-a-lot Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA


Markets

75 Split Rail Beer & Art P.O. Box 555 Lander 82520 USA
Ale Braunschweiger

77 The Big Cheese Liz Nixon 89 Jefferson Portland 97201 USA


Way Suite 2

78 The Cracker Box Liu Wong 55 Grizzly Peak Butte 59801 USA
Rd.

82 Trail's Head Helvetius Nagy 722 DaVinci Kirkland 98034 USA


Gourmet Blvd.
Provisioners

89 White Clover Karl Jablonski 305 - 14th Seattle 98128 USA


Markets Ave. S. Suite
3B

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.

48
11 B's Beverages Victoria Fauntleroy London EC2 5NT UK
Ashworth Circus

16 Consolidated Elizabeth Berkeley London WX1 6LT UK


Holdings Brown Gardens 12
Brewery

19 Eastern Ann Devon 35 King London WX3 6FW UK


Connection George

38 Island Trading Helen Bennett Garden House Cowes PO31 7PJ UK


Crowther Way

53 North/South Simon South House London SW7 1RZ UK


Crowther 300
Queensbridge

72 Seven Seas Hari Kumar 90 Wadhurst London OX15 4NB UK


Imports Rd.

14 Chop-suey Yang Wang Hauptstr. 29 Bern 3012 Switzerland


Chinese

68 Richter Michael Holz Grenzacherweg Genève 1203 Switzerland


Supermarkt 237

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden

8 Bólido Comidas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain


preparadas

22 FISSA Fabrica Diego Roel C/ Moralzarzal, Madrid 28034 Spain


Inter. Salchichas 86
S.A.

29 Galería del Eduardo Rambla de Barcelona 08022 Spain


gastrónomo Saavedra Cataluña, 23

30 Godos Cocina José Pedro C/ Romero, 33 Sevilla 41101 Spain


Típica Freyre

69 Romero y tomillo Alejandra Gran Vía, 1 Madrid 28001 Spain


Camino

28 Furia Bacalhau e Lino Rodriguez Jardim das Lisboa 1675 Portugal


Frutos do Mar rosas n. 32

60 Princesa Isabel Isabel de Estrada da Lisboa 1756 Portugal


Vinhoss Castro saúde n. 58

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

49
70 Santé Gourmet Jonas Erling Skakkes Stavern 4110 Norway
Bergulfsen gate 78

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y Constitución
helados 2222

3 Antonio Moreno Antonio Moreno Mataderos México D.F. 05023 Mexico


Taquería 2312

13 Centro comercial Francisco Sierras de México D.F. 05022 Mexico


Moctezuma Chang Granada 9993

58 Pericles Comidas Guillermo Calle Dr. Jorge México D.F. 05033 Mexico
clásicas Fernández Cash 321

80 Tortuga Miguel Angel Avda. Azteca México D.F. 05033 Mexico


Restaurante Paolino 123

27 Franchi S.p.A. Paolo Accorti Via Monte Torino 10100 Italy


Bianco 34

49 Magazzini Giovanni Via Ludovico il Bergamo 24100 Italy


Alimentari Rovelli Moro 22
Riuniti

66 Reggiani Maurizio Moroni Strada Reggio 42100 Italy


Caseifici Provinciale 124 Emilia

37 Hungry Owl All- Patricia 8 Johnstown Cork Ireland


Night Grocers McKenna Road

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany


Delikatessen

17 Drachenblut Sven Ottlieb Walserweg 21 Aachen 52066 Germany


Delikatessend

25 Frankenversand Peter Franken Berliner Platz München 80805 Germany


43

39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany

44 Lehmanns Renate Magazinweg 7 Frankfurt 60528 Germany


Marktstand Messner a.M.

52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 Germany


Gesundkost Feuer

56 Ottilies Henriette Mehrheimerstr. Köln 50739 Germany


Käseladen Pfalzheim 369

50
63 QUICK-Stop Horst Kloss Taucherstraße Cunewalde 01307 Germany
10

79 Toms Karin Josephs Luisenstr. 48 Münster 44087 Germany


Spezialitäten

86 Die Wandernde Rita Müller Adenauerallee Stuttgart 70563 Germany


Kuh 900

7 Blondel père et Frédérique 24, place Strasbourg 67000 France


fils Citeaux Kléber

9 Bon app' Laurence 12, rue des Marseille 13008 France


Lebihans Bouchers

18 Du monde entier Janine Labrune 67, rue des Nantes 44000 France
Cinquante
Otages

23 Folies Martine Rancé 184, chaussée Lille 59000 France


gourmandes de Tournai

26 France Carine Schmitt 54, rue Royale Nantes 44000 France


restauration

40 La corne Daniel Tonini 67, avenue de Versailles 78000 France


d'abondance l'Europe

41 La maison d'Asie Annette Roulet 1 rue Alsace- Toulouse 31000 France


Lorraine

57 Paris spécialités Marie Bertrand 265, boulevard Paris 75012 France


Charonne

74 Spécialités du Dominique 25, rue Paris 75016 France


monde Perrier Lauriston

84 Victuailles en Mary Saveley 2, rue du Lyon 69004 France


stock Commerce

85 Vins et alcools Paul Henriot 59 rue de Reims 51100 France


Chevalier l'Abbaye

87 Wartian Herkku Pirkko Torikatu 38 Oulu 90110 Finland


Koskitalo

90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland

73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark

83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark

10 Bottom-Dollar Elizabeth 23 Tsawassen Tsawassen T2F 8M4 Canada


Marketse Lincoln Blvd.

51
42 Laughing Yoshi 1900 Oak St. Vancouver V3F 2K1 Canada
Bacchus Wine Tannamuri
Cellars

51 Mère Paillarde Jean Fresnière 43 rue St. Montréal H1J 1C3 Canada
Laurent

15 Comércio Pedro Afonso Av. dos São Paulo 05432-043 Brazil


Mineiro Lusíadas, 23

21 Familia Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil


Arquibaldo

31 Gourmet André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil


Lanchonetes

34 Hanari Carnes Mario Pontes Rua do Paço, Rio de 05454-876 Brazil


67 Janeiro

61 Que Delícia Bernardo Rua da Rio de 02389-673 Brazil


Batista Panificadora, Janeiro
12

62 Queen Cozinha Lúcia Carvalho Alameda dos São Paulo 05487-020 Brazil
Canàrios, 891

67 Ricardo Janete Limeira Av. Rio de 02389-890 Brazil


Adocicados Copacabana, Janeiro
267

81 Tradição Anabela Av. Inês de São Paulo 05634-030 Brazil


Hipermercados Domingues Castro, 414

88 Wellington Paula Parente Rua do Resende 08737-363 Brazil


Importadora Mercado, 12

50 Maison Dewey Catherine Rue Joseph- Bruxelles B-1180 Belgium


Dewey Bens 532

76 Suprêmes Pascale Boulevard Charleroi B-6000 Belgium


délices Cartrain Tirou, 255

20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria

59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria

12 Cactus Comidas Patricio Cerrito 333 Buenos Aires 1010 Argentina


para llevar Simpson

54 Océano Atlántico Yvonne Ing. Gustavo Buenos Aires 1010 Argentina


Ltda. Moncada Moncada 8585
Piso 20-A

64 Rancho grande Sergio Av. del Buenos Aires 1010 Argentina


Gutiérrez Libertador 900

52
ORDER BY Several Columns Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country"
and the "CustomerName" column. This means that it orders by Country, but if some rows have the same
Country, it orders them by CustomerName:

Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
CustomerID CustomerName ContactName Address City PostalCode Country

12 Cactus Comidas Patricio Cerrito 333 Buenos Aires 1010 Argentina


para llevar Simpson

54 Océano Atlántico Yvonne Ing. Gustavo Buenos Aires 1010 Argentina


Ltda. Moncada Moncada 8585
Piso 20-A

64 Rancho grande Sergio Av. del Buenos Aires 1010 Argentina


Gutiérrez Libertador 900

20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria

59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria

50 Maison Dewey Catherine Rue Joseph- Bruxelles B-1180 Belgium


Dewey Bens 532

76 Suprêmes Pascale Boulevard Charleroi B-6000 Belgium


délices Cartrain Tirou, 255

15 Comércio Pedro Afonso Av. dos São Paulo 05432-043 Brazil


Mineiro Lusíadas, 23

21 Familia Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil


Arquibaldo

31 Gourmet André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil


Lanchonetes

34 Hanari Carnes Mario Pontes Rua do Paço, Rio de 05454-876 Brazil


67 Janeiro

61 Que Delícia Bernardo Rua da Rio de 02389-673 Brazil


Batista Panificadora, Janeiro
12

62 Queen Cozinha Lúcia Carvalho Alameda dos São Paulo 05487-020 Brazil
Canàrios, 891

67 Ricardo Janete Limeira Av. Rio de 02389-890 Brazil


Adocicados Copacabana, Janeiro
267

53
81 Tradição Anabela Av. Inês de São Paulo 05634-030 Brazil
Hipermercados Domingues Castro, 414

88 Wellington Paula Parente Rua do Resende 08737-363 Brazil


Importadora Mercado, 12

10 Bottom-Dollar Elizabeth 23 Tsawassen Tsawassen T2F 8M4 Canada


Marketse Lincoln Blvd.

42 Laughing Yoshi 1900 Oak St. Vancouver V3F 2K1 Canada


Bacchus Wine Tannamuri
Cellars

51 Mère Paillarde Jean Fresnière 43 rue St. Montréal H1J 1C3 Canada
Laurent

73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark

83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark

87 Wartian Herkku Pirkko Torikatu 38 Oulu 90110 Finland


Koskitalo

90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland

7 Blondel père et Frédérique 24, place Strasbourg 67000 France


fils Citeaux Kléber

9 Bon app' Laurence 12, rue des Marseille 13008 France


Lebihans Bouchers

18 Du monde entier Janine Labrune 67, rue des Nantes 44000 France
Cinquante
Otages

23 Folies Martine Rancé 184, chaussée Lille 59000 France


gourmandes de Tournai

26 France Carine Schmitt 54, rue Royale Nantes 44000 France


restauration

40 La corne Daniel Tonini 67, avenue de Versailles 78000 France


d'abondance l'Europe

41 La maison d'Asie Annette Roulet 1 rue Alsace- Toulouse 31000 France


Lorraine

57 Paris spécialités Marie Bertrand 265, boulevard Paris 75012 France


Charonne

74 Spécialités du Dominique 25, rue Paris 75016 France


monde Perrier Lauriston

84 Victuailles en Mary Saveley 2, rue du Lyon 69004 France


stock Commerce

54
85 Vins et alcools Paul Henriot 59 rue de Reims 51100 France
Chevalier l'Abbaye

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany


Delikatessen

86 Die Wandernde Rita Müller Adenauerallee Stuttgart 70563 Germany


Kuh 900

17 Drachenblut Sven Ottlieb Walserweg 21 Aachen 52066 Germany


Delikatessend

25 Frankenversand Peter Franken Berliner Platz München 80805 Germany


43

39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany

44 Lehmanns Renate Magazinweg 7 Frankfurt 60528 Germany


Marktstand Messner a.M.

52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 Germany


Gesundkost Feuer

56 Ottilies Henriette Mehrheimerstr. Köln 50739 Germany


Käseladen Pfalzheim 369

63 QUICK-Stop Horst Kloss Taucherstraße Cunewalde 01307 Germany


10

79 Toms Karin Josephs Luisenstr. 48 Münster 44087 Germany


Spezialitäten

37 Hungry Owl All- Patricia 8 Johnstown Cork Ireland


Night Grocers McKenna Road

27 Franchi S.p.A. Paolo Accorti Via Monte Torino 10100 Italy


Bianco 34

49 Magazzini Giovanni Via Ludovico il Bergamo 24100 Italy


Alimentari Rovelli Moro 22
Riuniti

66 Reggiani Maurizio Moroni Strada Reggio 42100 Italy


Caseifici Provinciale 124 Emilia

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y Constitución
helados 2222

3 Antonio Moreno Antonio Moreno Mataderos México D.F. 05023 Mexico


Taquería 2312

55
13 Centro comercial Francisco Sierras de México D.F. 05022 Mexico
Moctezuma Chang Granada 9993

58 Pericles Comidas Guillermo Calle Dr. Jorge México D.F. 05033 Mexico
clásicas Fernández Cash 321

80 Tortuga Miguel Angel Avda. Azteca México D.F. 05033 Mexico


Restaurante Paolino 123

70 Santé Gourmet Jonas Erling Skakkes Stavern 4110 Norway


Bergulfsen gate 78

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

28 Furia Bacalhau e Lino Rodriguez Jardim das Lisboa 1675 Portugal


Frutos do Mar rosas n. 32

60 Princesa Isabel Isabel de Estrada da Lisboa 1756 Portugal


Vinhoss Castro saúde n. 58

8 Bólido Comidas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain


preparadas

22 FISSA Fabrica Diego Roel C/ Moralzarzal, Madrid 28034 Spain


Inter. Salchichas 86
S.A.

29 Galería del Eduardo Rambla de Barcelona 08022 Spain


gastrónomo Saavedra Cataluña, 23

30 Godos Cocina José Pedro C/ Romero, 33 Sevilla 41101 Spain


Típica Freyre

69 Romero y tomillo Alejandra Gran Vía, 1 Madrid 28001 Spain


Camino

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden

14 Chop-suey Yang Wang Hauptstr. 29 Bern 3012 Switzerland


Chinese

68 Richter Michael Holz Grenzacherweg Genève 1203 Switzerland


Supermarkt 237

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.

11 B's Beverages Victoria Fauntleroy London EC2 5NT UK


Ashworth Circus

16 Consolidated Elizabeth Berkeley London WX1 6LT UK


Holdings Brown Gardens 12
Brewery

56
19 Eastern Ann Devon 35 King London WX3 6FW UK
Connection George

38 Island Trading Helen Bennett Garden House Cowes PO31 7PJ UK


Crowther Way

53 North/South Simon South House London SW7 1RZ UK


Crowther 300
Queensbridge

72 Seven Seas Hari Kumar 90 Wadhurst London OX15 4NB UK


Imports Rd.

32 Great Lakes Howard Snyder 2732 Baker Eugene 97403 USA


Food Market Blvd.

36 Hungry Coyote Yoshi Latimer City Center Elgin 97827 USA


Import Store Plaza 516 Main
St.

43 Lazy K Kountry John Steel 12 Orchestra Walla Walla 99362 USA


Store Terrace

45 Let's Stop N Jaime Yorres 87 Polk St. San 94117 USA


Shop Suite 5 Francisco

48 Lonesome Pine Fran Wilson 89 Chiaroscuro Portland 97219 USA


Restaurant Rd.

55 Old World Rene Phillips 2743 Bering Anchorage 99508 USA


Delicatessen St.

65 Rattlesnake Paula Wilson 2817 Milton Albuquerque 87110 USA


Canyon Grocery Dr.

71 Save-a-lot Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA


Markets

75 Split Rail Beer & Art P.O. Box 555 Lander 82520 USA
Ale Braunschweiger

77 The Big Cheese Liz Nixon 89 Jefferson Portland 97201 USA


Way Suite 2

78 The Cracker Box Liu Wong 55 Grizzly Peak Butte 59801 USA
Rd.

82 Trail's Head Helvetius Nagy 722 DaVinci Kirkland 98034 USA


Gourmet Blvd.
Provisioners

89 White Clover Karl Jablonski 305 - 14th Seattle 98128 USA


Markets Ave. S. Suite
3B

57
33 GROSELLA- Manuel Pereira 5ª Ave. Los Caracas 1081 Venezuela
Restaurante Palos Grandes

35 HILARIÓN- Carlos Carrera 22 con San 5022 Venezuela


Abastos Hernández Ave. Carlos Cristóbal
Soublette #8-
35

46 LILA- Carlos Carrera 52 con Barquisimeto 3508 Venezuela


Supermercado González Ave. Bolívar
#65-98 Llano
Largo

47 LINO- Felipe Ave. 5 de I. de 4980 Venezuela


Delicateses Izquierdo Mayo Porlamar Margarita

ORDER BY Several Columns Example 2


The following SQL statement selects all customers from the "Customers" table, sorted ascending by the
"Country" and descending by the "CustomerName" column:

Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;

CustomerID CustomerName ContactName Address City PostalCode Country

64 Rancho grande Sergio Av. del Buenos Aires 1010 Argentina


Gutiérrez Libertador 900

54 Océano Atlántico Yvonne Ing. Gustavo Buenos Aires 1010 Argentina


Ltda. Moncada Moncada 8585
Piso 20-A

12 Cactus Comidas Patricio Cerrito 333 Buenos Aires 1010 Argentina


para llevar Simpson

59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria

20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria

76 Suprêmes Pascale Boulevard Charleroi B-6000 Belgium


délices Cartrain Tirou, 255

50 Maison Dewey Catherine Rue Joseph- Bruxelles B-1180 Belgium


Dewey Bens 532

88 Wellington Paula Parente Rua do Resende 08737-363 Brazil


Importadora Mercado, 12

81 Tradição Anabela Av. Inês de São Paulo 05634-030 Brazil


Hipermercados Domingues Castro, 414

58
67 Ricardo Janete Limeira Av. Rio de 02389-890 Brazil
Adocicados Copacabana, Janeiro
267

62 Queen Cozinha Lúcia Carvalho Alameda dos São Paulo 05487-020 Brazil
Canàrios, 891

61 Que Delícia Bernardo Rua da Rio de 02389-673 Brazil


Batista Panificadora, Janeiro
12

34 Hanari Carnes Mario Pontes Rua do Paço, Rio de 05454-876 Brazil


67 Janeiro

31 Gourmet André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil


Lanchonetes

21 Familia Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil


Arquibaldo

15 Comércio Pedro Afonso Av. dos São Paulo 05432-043 Brazil


Mineiro Lusíadas, 23

51 Mère Paillarde Jean Fresnière 43 rue St. Montréal H1J 1C3 Canada
Laurent

42 Laughing Yoshi 1900 Oak St. Vancouver V3F 2K1 Canada


Bacchus Wine Tannamuri
Cellars

10 Bottom-Dollar Elizabeth 23 Tsawassen Tsawassen T2F 8M4 Canada


Marketse Lincoln Blvd.

83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark

73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark

90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland

87 Wartian Herkku Pirkko Torikatu 38 Oulu 90110 Finland


Koskitalo

85 Vins et alcools Paul Henriot 59 rue de Reims 51100 France


Chevalier l'Abbaye

84 Victuailles en Mary Saveley 2, rue du Lyon 69004 France


stock Commerce

74 Spécialités du Dominique 25, rue Paris 75016 France


monde Perrier Lauriston

57 Paris spécialités Marie Bertrand 265, boulevard Paris 75012 France


Charonne

41 La maison d'Asie Annette Roulet 1 rue Alsace- Toulouse 31000 France


Lorraine

59
40 La corne Daniel Tonini 67, avenue de Versailles 78000 France
d'abondance l'Europe

26 France Carine Schmitt 54, rue Royale Nantes 44000 France


restauration

23 Folies Martine Rancé 184, chaussée Lille 59000 France


gourmandes de Tournai

18 Du monde entier Janine Labrune 67, rue des Nantes 44000 France
Cinquante
Otages

9 Bon app' Laurence 12, rue des Marseille 13008 France


Lebihans Bouchers

7 Blondel père et Frédérique 24, place Strasbourg 67000 France


fils Citeaux Kléber

79 Toms Karin Josephs Luisenstr. 48 Münster 44087 Germany


Spezialitäten

63 QUICK-Stop Horst Kloss Taucherstraße Cunewalde 01307 Germany


10

56 Ottilies Henriette Mehrheimerstr. Köln 50739 Germany


Käseladen Pfalzheim 369

52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 Germany


Gesundkost Feuer

44 Lehmanns Renate Magazinweg 7 Frankfurt 60528 Germany


Marktstand Messner a.M.

39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany

25 Frankenversand Peter Franken Berliner Platz München 80805 Germany


43

17 Drachenblut Sven Ottlieb Walserweg 21 Aachen 52066 Germany


Delikatessend

86 Die Wandernde Rita Müller Adenauerallee Stuttgart 70563 Germany


Kuh 900

6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany


Delikatessen

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

37 Hungry Owl All- Patricia 8 Johnstown Cork Ireland


Night Grocers McKenna Road

66 Reggiani Maurizio Moroni Strada Reggio 42100 Italy


Caseifici Provinciale 124 Emilia

60
49 Magazzini Giovanni Via Ludovico il Bergamo 24100 Italy
Alimentari Rovelli Moro 22
Riuniti

27 Franchi S.p.A. Paolo Accorti Via Monte Torino 10100 Italy


Bianco 34

80 Tortuga Miguel Angel Avda. Azteca México D.F. 05033 Mexico


Restaurante Paolino 123

58 Pericles Comidas Guillermo Calle Dr. Jorge México D.F. 05033 Mexico
clásicas Fernández Cash 321

13 Centro comercial Francisco Sierras de México D.F. 05022 Mexico


Moctezuma Chang Granada 9993

3 Antonio Moreno Antonio Moreno Mataderos México D.F. 05023 Mexico


Taquería 2312

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y Constitución
helados 2222

70 Santé Gourmet Jonas Erling Skakkes Stavern 4110 Norway


Bergulfsen gate 78

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

60 Princesa Isabel Isabel de Estrada da Lisboa 1756 Portugal


Vinhoss Castro saúde n. 58

28 Furia Bacalhau e Lino Rodriguez Jardim das Lisboa 1675 Portugal


Frutos do Mar rosas n. 32

69 Romero y tomillo Alejandra Gran Vía, 1 Madrid 28001 Spain


Camino

30 Godos Cocina José Pedro C/ Romero, 33 Sevilla 41101 Spain


Típica Freyre

29 Galería del Eduardo Rambla de Barcelona 08022 Spain


gastrónomo Saavedra Cataluña, 23

22 FISSA Fabrica Diego Roel C/ Moralzarzal, Madrid 28034 Spain


Inter. Salchichas 86
S.A.

8 Bólido Comidas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain


preparadas

24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

61
68 Richter Michael Holz Grenzacherweg Genève 1203 Switzerland
Supermarkt 237

14 Chop-suey Yang Wang Hauptstr. 29 Bern 3012 Switzerland


Chinese

72 Seven Seas Hari Kumar 90 Wadhurst London OX15 4NB UK


Imports Rd.

53 North/South Simon South House London SW7 1RZ UK


Crowther 300
Queensbridge

38 Island Trading Helen Bennett Garden House Cowes PO31 7PJ UK


Crowther Way

19 Eastern Ann Devon 35 King London WX3 6FW UK


Connection George

16 Consolidated Elizabeth Berkeley London WX1 6LT UK


Holdings Brown Gardens 12
Brewery

11 B's Beverages Victoria Fauntleroy London EC2 5NT UK


Ashworth Circus

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.

89 White Clover Karl Jablonski 305 - 14th Seattle 98128 USA


Markets Ave. S. Suite
3B

82 Trail's Head Helvetius Nagy 722 DaVinci Kirkland 98034 USA


Gourmet Blvd.
Provisioners

78 The Cracker Box Liu Wong 55 Grizzly Peak Butte 59801 USA
Rd.

77 The Big Cheese Liz Nixon 89 Jefferson Portland 97201 USA


Way Suite 2

75 Split Rail Beer & Art P.O. Box 555 Lander 82520 USA
Ale Braunschweiger

71 Save-a-lot Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA


Markets

65 Rattlesnake Paula Wilson 2817 Milton Albuquerque 87110 USA


Canyon Grocery Dr.

55 Old World Rene Phillips 2743 Bering Anchorage 99508 USA


Delicatessen St.

62
48 Lonesome Pine Fran Wilson 89 Chiaroscuro Portland 97219 USA
Restaurant Rd.

45 Let's Stop N Jaime Yorres 87 Polk St. San 94117 USA


Shop Suite 5 Francisco

43 Lazy K Kountry John Steel 12 Orchestra Walla Walla 99362 USA


Store Terrace

36 Hungry Coyote Yoshi Latimer City Center Elgin 97827 USA


Import Store Plaza 516 Main
St.

32 Great Lakes Howard Snyder 2732 Baker Eugene 97403 USA


Food Market Blvd.

47 LINO- Felipe Ave. 5 de I. de 4980 Venezuela


Delicateses Izquierdo Mayo Porlamar Margarita

46 LILA- Carlos Carrera 52 con Barquisimeto 3508 Venezuela


Supermercado González Ave. Bolívar
#65-98 Llano
Largo

35 HILARIÓN- Carlos Carrera 22 con San 5022 Venezuela


Abastos Hernández Ave. Carlos Cristóbal
Soublette #8-
35

33 GROSELLA- Manuel Pereira 5ª Ave. Los Caracas 1081 Venezuela


Restaurante Palos Grandes

EXERCISES:

1. Select all records from the Customers table, sort the result alphabetically by the column City.
SELECT * FROM Customers _____ __ ____;
2. Select all records from the Customers table, sort the result reversed alphabetically by the
column City.
SELECT * FROM Customers _____ __ ____ ____;
3. Select all records from the Customers table, sort the result alphabetically, first by the column
Country, then, by the column City.
SELECT * FROM Customers _____ __ ________ ____;

SQL INSERT INTO Statement

The SQL INSERT INTO Statement


The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Syntax


It is possible to write the INSERT INTO statement in two ways.

63
The first way specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

If you are adding values for all the columns of the table, you do not need to specify the column names in
the SQL query. However, make sure the order of the values is in the same order as the columns in the
table. The INSERT INTO syntax would be as follows:

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

89 White Clover Karl Jablonski 305 - 14th Seattle 98128 USA


Markets Ave. S.
Suite 3B

90 Wilman Kala Matti Keskuskatu Helsinki 21240 Finland


Karttunen 45

91 Wolski Zbyszek ul. Filtrowa Walla 01-012 Poland


68

INSERT INTO Example


The following SQL statement inserts a new record in the "Customers" table:

Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');

64
CustomerID CustomerName ContactName Address City PostalCode Country

89 White Clover Karl Jablonski 305 - 14th Ave. Seattle 98128 USA
Markets S. Suite 3B

90 Wilman Kala Matti Keskuskatu 45 Helsinki 21240 Finland


Karttunen

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

92 Cardinal Tom B. Skagen 21 Stavanger 4006 Norway


Erichsen

Did you notice that we did not insert any number into the CustomerID field?
The CustomerID column is an auto-increment field and will be generated automatically when a new
record is inserted into the table.

Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');

The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

89 White Clover Karl Jablonski 305 - 14th Seattle 98128 USA


Markets Ave. S.
Suite 3B

65
90 Wilman Kala Matti Keskuskatu Helsinki 21240 Finland
Karttunen 45

91 Wolski Zbyszek ul. Filtrowa Walla 01-012 Poland


68

92 Cardinal null null Stavanger null Norway

EXERCISES:

1. Insert a new record in the Customers table.

______ ____ Customers (CustomerName, Address, City, PostalCode, Country _ ______ _'Hekkan
Burger','Gateveien 15','Sandnes','4306','Norway');

SQL NULL Values


What is a NULL Value?
A field with a NULL value is a field with no value.

If a field in a table is optional, it is possible to insert a new record or update a record without adding a
value to this field. Then, the field will be saved with a NULL value.

Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL
value is one that has been left blank during record creation!

How to Test for NULL Values?


It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

We will have to use the IS NULL and IS NOT NULL operators instead.

IS NULL Syntax

SELECT column_names
FROM table_name
WHERE column_name IS NULL;

IS NOT NULL Syntax

66
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y helados Constitución 2222 D.F.

3 Antonio Moreno Antonio Mataderos 2312 México 05023 Mexico


Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden


Berglund

The IS NULL Operator


The IS NULL operator is used to test for empty values (NULL values).

The following SQL lists all customers with a NULL value in the "Address" field:

Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;

No result.

Tip: Always use IS NULL to look for NULL values.

67
The IS NOT NULL Operator
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).

The following SQL lists all customers with a value in the "Address" field:

Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;

CustomerName ContactName Address

Alfreds Futterkiste Maria Anders Obere Str. 57

Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222

Antonio Moreno Taquería Antonio Moreno Mataderos 2312

Around the Horn Thomas Hardy 120 Hanover Sq.

Berglunds snabbköp Christina Berglund Berguvsvägen 8

Blauer See Delikatessen Hanna Moos Forsterstr. 57

Blondel père et fils Frédérique Citeaux 24, place Kléber

Bólido Comidas preparadas Martín Sommer C/ Araquil, 67

Bon app' Laurence Lebihans 12, rue des Bouchers

Bottom-Dollar Marketse Elizabeth Lincoln 23 Tsawassen Blvd.

B's Beverages Victoria Ashworth Fauntleroy Circus

Cactus Comidas para llevar Patricio Simpson Cerrito 333

Centro comercial Moctezuma Francisco Chang Sierras de Granada 9993

Chop-suey Chinese Yang Wang Hauptstr. 29

Comércio Mineiro Pedro Afonso Av. dos Lusíadas, 23

Consolidated Holdings Elizabeth Brown Berkeley Gardens 12 Brewery

Drachenblut Delikatessend Sven Ottlieb Walserweg 21

Du monde entier Janine Labrune 67, rue des Cinquante Otages

Eastern Connection Ann Devon 35 King George

Ernst Handel Roland Mendel Kirchgasse 6

Familia Arquibaldo Aria Cruz Rua Orós, 92

FISSA Fabrica Inter. Salchichas S.A. Diego Roel C/ Moralzarzal, 86

68
Folies gourmandes Martine Rancé 184, chaussée de Tournai

Folk och fä HB Maria Larsson Åkergatan 24

Frankenversand Peter Franken Berliner Platz 43

France restauration Carine Schmitt 54, rue Royale

Franchi S.p.A. Paolo Accorti Via Monte Bianco 34

Furia Bacalhau e Frutos do Mar Lino Rodriguez Jardim das rosas n. 32

Galería del gastrónomo Eduardo Saavedra Rambla de Cataluña, 23

Godos Cocina Típica José Pedro Freyre C/ Romero, 33

Gourmet Lanchonetes André Fonseca Av. Brasil, 442

Great Lakes Food Market Howard Snyder 2732 Baker Blvd.

GROSELLA-Restaurante Manuel Pereira 5ª Ave. Los Palos Grandes

Hanari Carnes Mario Pontes Rua do Paço, 67

HILARIÓN-Abastos Carlos Hernández Carrera 22 con Ave. Carlos Soublette #8-35

Hungry Coyote Import Store Yoshi Latimer City Center Plaza 516 Main St.

Hungry Owl All-Night Grocers Patricia McKenna 8 Johnstown Road

Island Trading Helen Bennett Garden House Crowther Way

Königlich Essen Philip Cramer Maubelstr. 90

La corne d'abondance Daniel Tonini 67, avenue de l'Europe

La maison d'Asie Annette Roulet 1 rue Alsace-Lorraine

Laughing Bacchus Wine Cellars Yoshi Tannamuri 1900 Oak St.

Lazy K Kountry Store John Steel 12 Orchestra Terrace

Lehmanns Marktstand Renate Messner Magazinweg 7

Let's Stop N Shop Jaime Yorres 87 Polk St. Suite 5

LILA-Supermercado Carlos González Carrera 52 con Ave. Bolívar #65-98 Llano Largo

LINO-Delicateses Felipe Izquierdo Ave. 5 de Mayo Porlamar

Lonesome Pine Restaurant Fran Wilson 89 Chiaroscuro Rd.

Magazzini Alimentari Riuniti Giovanni Rovelli Via Ludovico il Moro 22

Maison Dewey Catherine Dewey Rue Joseph-Bens 532

Mère Paillarde Jean Fresnière 43 rue St. Laurent

69
Morgenstern Gesundkost Alexander Feuer Heerstr. 22

North/South Simon Crowther South House 300 Queensbridge

Océano Atlántico Ltda. Yvonne Moncada Ing. Gustavo Moncada 8585 Piso 20-A

Old World Delicatessen Rene Phillips 2743 Bering St.

Ottilies Käseladen Henriette Pfalzheim Mehrheimerstr. 369

Paris spécialités Marie Bertrand 265, boulevard Charonne

Pericles Comidas clásicas Guillermo Fernández Calle Dr. Jorge Cash 321

Piccolo und mehr Georg Pipps Geislweg 14

Princesa Isabel Vinhoss Isabel de Castro Estrada da saúde n. 58

Que Delícia Bernardo Batista Rua da Panificadora, 12

Queen Cozinha Lúcia Carvalho Alameda dos Canàrios, 891

QUICK-Stop Horst Kloss Taucherstraße 10

Rancho grande Sergio Gutiérrez Av. del Libertador 900

Rattlesnake Canyon Grocery Paula Wilson 2817 Milton Dr.

Reggiani Caseifici Maurizio Moroni Strada Provinciale 124

Ricardo Adocicados Janete Limeira Av. Copacabana, 267

Richter Supermarkt Michael Holz Grenzacherweg 237

Romero y tomillo Alejandra Camino Gran Vía, 1

Santé Gourmet Jonas Bergulfsen Erling Skakkes gate 78

Save-a-lot Markets Jose Pavarotti 187 Suffolk Ln.

Seven Seas Imports Hari Kumar 90 Wadhurst Rd.

Simons bistro Jytte Petersen Vinbæltet 34

Spécialités du monde Dominique Perrier 25, rue Lauriston

Split Rail Beer & Ale Art Braunschweiger P.O. Box 555

Suprêmes délices Pascale Cartrain Boulevard Tirou, 255

The Big Cheese Liz Nixon 89 Jefferson Way Suite 2

The Cracker Box Liu Wong 55 Grizzly Peak Rd.

Toms Spezialitäten Karin Josephs Luisenstr. 48

Tortuga Restaurante Miguel Angel Paolino Avda. Azteca 123

70
Tradição Hipermercados Anabela Domingues Av. Inês de Castro, 414

Trail's Head Gourmet Provisioners Helvetius Nagy 722 DaVinci Blvd.

Vaffeljernet Palle Ibsen Smagsløget 45

Victuailles en stock Mary Saveley 2, rue du Commerce

Vins et alcools Chevalier Paul Henriot 59 rue de l'Abbaye

Die Wandernde Kuh Rita Müller Adenauerallee 900

Wartian Herkku Pirkko Koskitalo Torikatu 38

Wellington Importadora Paula Parente Rua do Mercado, 12

White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B

Wilman Kala Matti Karttunen Keskuskatu 45

Wolski Zbyszek ul. Filtrowa 68

EXERCISES:

1. Select all records from the Customers where the PostalCode column is empty.
SELECT * FROM Customers WHERE __________ __ ____ ;
2. Select all records from the Customers where the PostalCode column is NOT empty.
SELECT * FROM Customers WHERE __________ __ ___ ____;

SQL UPDATE Statement


The SQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.

UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement.
The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all
records in the table will be updated!

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

71
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y helados Constitución 2222 D.F.

3 Antonio Moreno Antonio Mataderos 2312 México 05023 Mexico


Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden


Berglund

UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact person
and a new city.

Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Alfred Schmidt Obere Str. 57 Frankfurt 12209 Germany


Futterkiste

72
2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico
Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

UPDATE Multiple Records


It is the WHERE clause that determines how many records will be updated.

The following SQL statement will update the contactname to "Juan" for all records where country is
"Mexico":

Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';

The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Alfred Schmidt Obere Str. 57 Frankfurt 12209 Germany


Futterkiste

73
2 Ana Trujillo Juan Avda. de la México 05021 Mexico
Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Juan Mataderos México 05023 Mexico


Taquería 2312 D.F.

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!

Example
UPDATE Customers
SET ContactName='Juan';

The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Juan Obere Str. 57 Frankfurt 12209 Germany

2 Ana Trujillo Juan Avda. de la México 05021 Mexico


Emparedados y helados Constitución 2222 D.F.

74
3 Antonio Moreno Juan Mataderos 2312 México 05023 Mexico
Taquería D.F.

4 Around the Horn Juan 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Juan Berguvsvägen 8 Luleå S-958 22 Sweden

EXERCISES:

1. Update the City column of all records in the Customers table.


______ Customers ___ City = 'Oslo';
2. Set the value of the City columns to 'Oslo', but only the ones where the Country column has the
value "Norway".
______ Customers ___ City = 'Oslo' _____ Country = 'Norway';
3. Update the City value and the Country value.
______ Customers ___ City = 'Oslo' _____ Country = 'Norway' WHERE CustomerID = 32;

SQL DELETE Statement


The SQL DELETE Statement
The DELETE statement is used to delete existing records in a table.

DELETE Syntax
DELETE FROM table_name WHERE condition;

Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement.
The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records
in the table will be deleted!

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

75
2 Ana Trujillo Emparedados Ana Trujillo Avda. de la México 05021 Mexico
y helados Constitución 2222 D.F.

3 Antonio Moreno Taquería Antonio Mataderos 2312 México 05023 Mexico


Moreno D.F.

4 Around the Horn Thomas 120 Hanover Sq. London WA1 1DP UK
Hardy

5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden


Berglund

SQL DELETE Example


The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers" table:

Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

The "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos 2312 México 05023 Mexico


Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.

76
5 Berglunds snabbköp Christina Berguvsvägen Luleå S-958 22 Sweden
Berglund 8

Delete All Records


It is possible to delete all rows in a table without deleting the table. This means that the table structure,
attributes, and indexes will be intact:

DELETE FROM table_name;

The following SQL statement deletes all rows in the "Customers" table, without deleting the table:

Example
DELETE FROM Customers;

EXERCISES:

1. Delete all the records from the Customers table where the Country value is 'Norway'.
______ ____ Customers _____ Country = 'Norway';
2. Delete all the records from the Customers table.
______ ____ Customers;

SQL TOP, LIMIT or ROWNUM Clause


The SQL SELECT TOP Clause

The SELECT TOP clause is used to specify the number of records to return.

The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of
records can impact performance.

Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause to
select a limited number of records, while Oracle uses ROWNUM.

SQL Server / MS Access Syntax:


SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;

MySQL Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;

77
Oracle Syntax:
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

SQL TOP, LIMIT and ROWNUM Examples


The following SQL statement selects the first three records from the "Customers" table (for SQL
Server/MS Access):

Example
SELECT TOP 3 * FROM Customers;

The following SQL statement shows the equivalent example using the LIMIT clause (for MySQL):

Example

78
SELECT * FROM Customers
LIMIT 3;

The following SQL statement shows the equivalent example using ROWNUM (for Oracle):

Example
SELECT * FROM Customers
WHERE ROWNUM <= 3;

SQL TOP PERCENT Example


The following SQL statement selects the first 50% of the records from the "Customers" table (for SQL
Server/MS Access):

Example
SELECT TOP 50 PERCENT * FROM Customers;

ADD a WHERE CLAUSE


The following SQL statement selects the first three records from the "Customers" table, where the
country is "Germany" (for SQL Server/MS Access):

Example
SELECT TOP 3 * FROM Customers
WHERE Country='Germany';

The following SQL statement shows the equivalent example using the LIMIT clause (for MySQL):

Example
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;

The following SQL statement shows the equivalent example using ROWNUM (for Oracle):

Example
SELECT * FROM Customers
WHERE Country='Germany' AND ROWNUM <= 3;

SQL MIN() and MAX() Functions


The SQL MIN() and MAX() Functions
The MIN() function returns the smallest value of the selected column.

The MAX() function returns the largest value of the selected column.

MIN() Syntax

79
SELECT MIN(column_name)
FROM table_name
WHERE condition;

MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;

Demo Database
Below is a selection from the "Products" table in the Northwind sample database:

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 18
bags

2 Chang 1 1 24 - 12 oz 19
bottles

3 Aniseed Syrup 1 2 12 - 550 ml 10


bottles

4 Chef Anton's Cajun 2 2 48 - 6 oz jars 22


Seasoning

5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35

MIN() Example
The following SQL statement finds the price of the cheapest product:

Example
SELECT MIN(Price) AS SmallestPrice
FROM Products;

Number of Records: 1

80
SmallestPrice

2.5

MAX() Example
The following SQL statement finds the price of the most expensive product:

Example
SELECT MAX(Price) AS LargestPrice
FROM Products;

Number of Records: 1

LargestPrice

263.5

SQL COUNT(), AVG() and SUM() Functions


The SQL COUNT(), AVG() and SUM() Functions
The COUNT() function returns the number of rows that matches a specified criterion.
The AVG() function returns the average value of a numeric column.
The SUM() function returns the total sum of a numeric column.

COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;

SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;

Demo Database
Below is a selection from the "Products" table in the Northwind sample database:

ProductID ProductName SupplierID CategoryID Unit Price

81
1 Chais 1 1 10 boxes x 20 18
bags

2 Chang 1 1 24 - 12 oz 19
bottles

3 Aniseed Syrup 1 2 12 - 550 ml 10


bottles

4 Chef Anton's Cajun 2 2 48 - 6 oz jars 22


Seasoning

5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35

COUNT() Example
The following SQL statement finds the number of products:

Example
SELECT COUNT(ProductID)
FROM Products;

Note: NULL values are not counted.

AVG() Example
The following SQL statement finds the average price of all products:

Example
SELECT AVG(Price)
FROM Products;

Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample database:

OrderDetailID OrderID ProductID Quantity

82
1 10248 11 12

2 10248 42 10

3 10248 72 5

4 10249 14 9

5 10249 51 40

SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:

Example
SELECT SUM(Quantity)
FROM OrderDetails;

EXERCISES:

1. Use the MIN function to select the record with the smallest value of the Price column.
SELECT __________ FROM Products;
2. Use an SQL function to select the record with the highest value of the Price column.
SELECT __________ FROM Products;
3. Use the correct function to return the number of records that have the Price value set to 18.
SELECT _____ (*) FROM Products _____ Price = 18;
4. Use an SQL function to calculate the average price of all products.
SELECT __________ FROM Products;
5. Use an SQL function to calculate the sum of all the Price column values in the Products table.
SELECT __________ FROM Products;

SQL LIKE Operator


The SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

83
There are two wildcards often used in conjunction with the LIKE operator:

 % - The percent sign represents zero, one, or multiple characters


 _ - The underscore represents a single character

Note: MS Access uses an asterisk (*) instead of the percent sign (%), and a question mark (?) instead of
the underscore (_).

The percent sign and the underscore can also be used in combinations!

LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Tip: You can also combine any number of conditions using AND or OR operators.

Here are some examples showing different LIKE operators with '%' and '_' wildcards:

LIKE Operator Description

WHERE CustomerName LIKE Finds any values that start with "a"
'a%'

WHERE CustomerName LIKE Finds any values that end with "a"
'%a'

WHERE CustomerName LIKE Finds any values that have "or" in any position
'%or%'

WHERE CustomerName LIKE Finds any values that have "r" in the second position
'_r%'

WHERE CustomerName LIKE Finds any values that start with "a" and are at least 2
'a_%' characters in length

84
WHERE CustomerName LIKE Finds any values that start with "a" and are at least 3
'a__%' characters in length

WHERE ContactName LIKE Finds any values that start with "a" and ends with "o"
'a%o'

Demo Database
The table below shows the complete "Customers" table from the Northwind sample database:

Customer CustomerNa ContactNa Address City PostalCo Country


ID me me de

1 Alfreds Maria Anders Obere Str. Berlin 12209 Germany


Futterkiste 57

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados Constitución D.F.
y helados 2222

3 Antonio Antonio Mataderos México 05023 Mexico


Moreno Moreno 2312 D.F.
Taquería

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

5 Berglunds Christina Berguvsväge Luleå S-958 22 Sweden


snabbköp Berglund n8

85
6 Blauer See Hanna Moos Forsterstr. Mannheim 68306 Germany
Delikatessen 57

7 Blondel père Frédérique 24, place Strasbourg 67000 France


et fils Citeaux Kléber

8 Bólido Martín C/ Araquil, Madrid 28023 Spain


Comidas Sommer 67
preparadas

9 Bon app' Laurence 12, rue des Marseille 13008 France


Lebihans Bouchers

10 Bottom-Dollar Elizabeth 23 Tsawassen T2F 8M4 Canada


Marketse Lincoln Tsawassen
Blvd.

11 B's Beverages Victoria Fauntleroy London EC2 5NT UK


Ashworth Circus

12 Cactus Patricio Cerrito 333 Buenos 1010 Argentina


Comidas para Simpson Aires
llevar

13 Centro Francisco Sierras de México 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

14 Chop-suey Yang Wang Hauptstr. 29 Bern 3012 Switzerla


Chinese nd

86
15 Comércio Pedro Afonso Av. dos São Paulo 05432- Brazil
Mineiro Lusíadas, 23 043

16 Consolidated Elizabeth Berkeley London WX1 6LT UK


Holdings Brown Gardens 12
Brewery

17 Drachenblut Sven Ottlieb Walserweg Aachen 52066 Germany


Delikatessend 21

18 Du monde Janine 67, rue des Nantes 44000 France


entier Labrune Cinquante
Otages

19 Eastern Ann Devon 35 King London WX3 6FW UK


Connection George

20 Ernst Handel Roland Kirchgasse 6 Graz 8010 Austria


Mendel

21 Familia Aria Cruz Rua Orós, São Paulo 05442- Brazil


Arquibaldo 92 030

22 FISSA Fabrica Diego Roel C/ Madrid 28034 Spain


Inter. Moralzarzal,
Salchichas 86
S.A.

23 Folies Martine 184, Lille 59000 France


gourmandes Rancé chaussée de
Tournai

87
24 Folk och fä Maria Åkergatan Bräcke S-844 67 Sweden
HB Larsson 24

25 Frankenversa Peter Berliner München 80805 Germany


nd Franken Platz 43

26 France Carine 54, rue Nantes 44000 France


restauration Schmitt Royale

27 Franchi S.p.A. Paolo Accorti Via Monte Torino 10100 Italy


Bianco 34

28 Furia Lino Jardim das Lisboa 1675 Portugal


Bacalhau e Rodriguez rosas n. 32
Frutos do Mar

29 Galería del Eduardo Rambla de Barcelona 08022 Spain


gastrónomo Saavedra Cataluña, 23

30 Godos Cocina José Pedro C/ Romero, Sevilla 41101 Spain


Típica Freyre 33

31 Gourmet André Av. Brasil, Campinas 04876- Brazil


Lanchonetes Fonseca 442 786

32 Great Lakes Howard 2732 Baker Eugene 97403 USA


Food Market Snyder Blvd.

88
33 GROSELLA- Manuel 5ª Ave. Los Caracas 1081 Venezuel
Restaurante Pereira Palos a
Grandes

34 Hanari Carnes Mario Pontes Rua do Rio de 05454- Brazil


Paço, 67 Janeiro 876

35 HILARIÓN- Carlos Carrera 22 San 5022 Venezuel


Abastos Hernández con Ave. Cristóbal a
Carlos
Soublette
#8-35

36 Hungry Yoshi City Center Elgin 97827 USA


Coyote Latimer Plaza 516
Import Store Main St.

37 Hungry Owl Patricia 8 Johnstown Cork Ireland


All-Night McKenna Road
Grocers

38 Island Trading Helen Garden Cowes PO31 7PJ UK


Bennett House
Crowther
Way

39 Königlich Philip Maubelstr. Brandenbu 14776 Germany


Essen Cramer 90 rg

40 La corne Daniel Tonini 67, avenue Versailles 78000 France


d'abondance de l'Europe

89
41 La maison Annette 1 rue Toulouse 31000 France
d'Asie Roulet Alsace-
Lorraine

42 Laughing Yoshi 1900 Oak Vancouver V3F 2K1 Canada


Bacchus Wine Tannamuri St.
Cellars

43 Lazy K John Steel 12 Orchestra Walla 99362 USA


Kountry Store Terrace Walla

44 Lehmanns Renate Magazinweg Frankfurt 60528 Germany


Marktstand Messner 7 a.M.

45 Let's Stop N Jaime Yorres 87 Polk St. San 94117 USA


Shop Suite 5 Francisco

46 LILA- Carlos Carrera 52 Barquisim 3508 Venezuel


Supermercad González con Ave. eto a
o Bolívar #65-
98 Llano
Largo

47 LINO- Felipe Ave. 5 de I. de 4980 Venezuel


Delicateses Izquierdo Mayo Margarita a
Porlamar

48 Lonesome Fran Wilson 89 Portland 97219 USA


Pine Chiaroscuro
Restaurant Rd.

90
49 Magazzini Giovanni Via Ludovico Bergamo 24100 Italy
Alimentari Rovelli il Moro 22
Riuniti

50 Maison Dewey Catherine Rue Joseph- Bruxelles B-1180 Belgium


Dewey Bens 532

51 Mère Paillarde Jean 43 rue St. Montréal H1J 1C3 Canada


Fresnière Laurent

52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 Germany


Gesundkost Feuer

53 North/South Simon South House London SW7 1RZ UK


Crowther 300
Queensbridg
e

54 Océano Yvonne Ing. Gustavo Buenos 1010 Argentina


Atlántico Moncada Moncada Aires
Ltda. 8585 Piso
20-A

55 Old World Rene Phillips 2743 Bering Anchorage 99508 USA


Delicatessen St.

56 Ottilies Henriette Mehrheimers Köln 50739 Germany


Käseladen Pfalzheim tr. 369

57 Paris Marie 265, Paris 75012 France


spécialités Bertrand boulevard
Charonne

91
58 Pericles Guillermo Calle Dr. México 05033 Mexico
Comidas Fernández Jorge Cash D.F.
clásicas 321

59 Piccolo und Georg Pipps Geislweg 14 Salzburg 5020 Austria


mehr

60 Princesa Isabel de Estrada da Lisboa 1756 Portugal


Isabel Castro saúde n. 58
Vinhoss

61 Que Delícia Bernardo Rua da Rio de 02389- Brazil


Batista Panificadora, Janeiro 673
12

62 Queen Lúcia Alameda dos São Paulo 05487- Brazil


Cozinha Carvalho Canàrios, 020
891

63 QUICK-Stop Horst Kloss Taucherstra Cunewalde 01307 Germany


ße 10

64 Rancho Sergio Av. del Buenos 1010 Argentina


grande Gutiérrez Libertador Aires
900

65 Rattlesnake Paula Wilson 2817 Milton Albuquerq 87110 USA


Canyon Dr. ue
Grocery

92
66 Reggiani Maurizio Strada Reggio 42100 Italy
Caseifici Moroni Provinciale Emilia
124

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacabana, Janeiro 890
267

68 Richter Michael Holz Grenzacher Genève 1203 Switzerla


Supermarkt weg 237 nd

69 Romero y Alejandra Gran Vía, 1 Madrid 28001 Spain


tomillo Camino

70 Santé Jonas Erling Stavern 4110 Norway


Gourmet Bergulfsen Skakkes
gate 78

71 Save-a-lot Jose 187 Suffolk Boise 83720 USA


Markets Pavarotti Ln.

72 Seven Seas Hari Kumar 90 Wadhurst London OX15 4NB UK


Imports Rd.

73 Simons bistro Jytte Vinbæltet 34 Københav 1734 Denmark


Petersen n

74 Spécialités du Dominique 25, rue Paris 75016 France


monde Perrier Lauriston

93
75 Split Rail Beer Art P.O. Box Lander 82520 USA
& Ale Braunschwei 555
ger

76 Suprêmes Pascale Boulevard Charleroi B-6000 Belgium


délices Cartrain Tirou, 255

77 The Big Liz Nixon 89 Jefferson Portland 97201 USA


Cheese Way Suite 2

78 The Cracker Liu Wong 55 Grizzly Butte 59801 USA


Box Peak Rd.

79 Toms Karin Luisenstr. Münster 44087 Germany


Spezialitäten Josephs 48

80 Tortuga Miguel Angel Avda. México 05033 Mexico


Restaurante Paolino Azteca 123 D.F.

81 Tradição Anabela Av. Inês de São Paulo 05634- Brazil


Hipermercado Domingues Castro, 414 030
s

82 Trail's Head Helvetius 722 DaVinci Kirkland 98034 USA


Gourmet Nagy Blvd.
Provisioners

83 Vaffeljernet Palle Ibsen Smagsløget Århus 8200 Denmark


45

94
84 Victuailles en Mary 2, rue du Lyon 69004 France
stock Saveley Commerce

85 Vins et alcools Paul Henriot 59 rue de Reims 51100 France


Chevalier l'Abbaye

86 Die Rita Müller Adenauerall Stuttgart 70563 Germany


Wandernde ee 900
Kuh

87 Wartian Pirkko Torikatu 38 Oulu 90110 Finland


Herkku Koskitalo

88 Wellington Paula Rua do Resende 08737- Brazil


Importadora Parente Mercado, 12 363

89 White Clover Karl 305 - 14th Seattle 98128 USA


Markets Jablonski Ave. S.
Suite 3B

90 Wilman Kala Matti Keskuskatu Helsinki 21240 Finland


Karttunen 45

91 Wolski Zbyszek ul. Filtrowa Walla 01-012 Poland


68

SQL LIKE Examples


The following SQL statement selects all customers with a CustomerName starting with "a":

Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';

95
The following SQL statement selects all customers with a CustomerName ending with "a":

Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';

The following SQL statement selects all customers with a CustomerName that have "or" in any position:

Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';

The following SQL statement selects all customers with a CustomerName that have "r" in the second
position:

Example
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';

The following SQL statement selects all customers with a CustomerName that starts with "a" and are at
least 3 characters in length:

Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';

The following SQL statement selects all customers with a ContactName that starts with "a" and ends
with "o":

Example
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';

The following SQL statement selects all customers with a CustomerName that does NOT start with "a":

Example
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';

EXERCISES:
1. Select all records where the value of the City column starts with the letter "a".
SELECT * FROM Customers _____ ____ ____ ____;
2. Select all records where the value of the City column ends with the letter "a".
SELECT * FROM Customers _____ ____ ____ ____;
3. Select all records where the value of the City column contains the letter "a".
SELECT * FROM Customers _____ ____ ____ ______;

96
4. Select all records where the value of the City column starts with letter "a" and ends with the
letter "b".
SELECT * FROM Customers _____ ____ ____ ______;
5. Select all records where the value of the City column does NOT start with the letter "a".
SELECT * FROM Customers _____ ____ ____ ____;

SQL Wildcards
SQL Wildcard Characters
A wildcard character is used to substitute one or more characters in a string.

Wildcard characters are used with the SQL LIKE operator. The LIKE operator is used in a WHERE clause to
search for a specified pattern in a column.

Wildcard Characters in MS Access

Symbol Description Example

* Represents zero or more characters bl* finds bl, black, blue, and blob

? Represents a single character h?t finds hot, hat, and hit

[] Represents any single character h[oa]t finds hot and hat, but not hit
within the brackets

! Represents any character not in the h[!oa]t finds hit, but not hot and hat
brackets

- Represents a range of characters c[a-b]t finds cat and cbt

# Represents any single numeric 2#5 finds 205, 215, 225, 235, 245, 255, 265,
character 275, 285, and 295

97
Wildcard Characters in SQL Server

Symbol Description Example

% Represents zero or more characters bl% finds bl, black, blue, and blob

_ Represents a single character h_t finds hot, hat, and hit

[] Represents any single character within the h[oa]t finds hot and hat, but not
brackets hit

^ Represents any character not in the brackets h[^oa]t finds hit, but not hot and
hat

- Represents a range of characters c[a-b]t finds cat and cbt

All the wildcards can also be used in combinations!

Here are some examples showing different LIKE operators with '%' and '_' wildcards:

LIKE Operator Description

WHERE CustomerName LIKE Finds any values that starts with "a"
'a%'

WHERE CustomerName LIKE Finds any values that ends with "a"
'%a'

98
WHERE CustomerName LIKE Finds any values that have "or" in any position
'%or%'

WHERE CustomerName LIKE Finds any values that have "r" in the second position
'_r%'

WHERE CustomerName LIKE Finds any values that starts with "a" and are at least 3
'a_%_%' characters in length

WHERE ContactName LIKE Finds any values that starts with "a" and ends with "o"
'a%o'

Using the % Wildcard


The following SQL statement selects all customers with a City starting with "ber":

Example
SELECT * FROM Customers
WHERE City LIKE 'ber%';

The following SQL statement selects all customers with a City containing the pattern "es":

Example
SELECT * FROM Customers
WHERE City LIKE '%es%';

Using the _ Wildcard


The following SQL statement selects all customers with a City starting with any character, followed by
"ondon":

Example
SELECT * FROM Customers
WHERE City LIKE '_ondon';

The following SQL statement selects all customers with a City starting with "L", followed by any
character, followed by "n", followed by any character, followed by "on":

Example
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';
99
Using the [charlist] Wildcard
The following SQL statement selects all customers with a City starting with "b", "s", or "p":

Example
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';

The following SQL statement selects all customers with a City starting with "a", "b", or "c":

Example
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';

Using the [!charlist] Wildcard


The two following SQL statements select all customers with a City NOT starting with "b", "s", or "p":

Example
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';

Or:

Example
SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';

EXERCISES:
1. Select all records where the second letter of the City is an "a".
SELECT * FROM Customers WHERE City LIKE ' __%';
2. Select all records where the first letter of the City is an "a" or a "c" or an "s".
SELECT * FROM Customers WHERE City LIKE ' _____%';
3. Select all records where the first letter of the City starts with anything from an "a" to an "f".
SELECT * FROM Customers WHERE City LIKE '_____%';
4. Select all records where the first letter of the City is NOT an "a" or a "c" or an "f".
5. SELECT * FROM Customers WHERE City LIKE '_____%';

SQL IN Operator
The SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

IN Syntax

100
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

or:

SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);

IN Operator Examples
The following SQL statement selects all customers that are located in "Germany", "France" or "UK":

Example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');

The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":

Example
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');

The following SQL statement selects all customers that are from the same countries as the suppliers:

Example
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);

EXERCISES:
1. Use the IN operator to select all the records where Country is either "Norway" or "France".
SELECT * FROM Customers _____ _______ __ __________ ‘France’ _;
2. Use the IN operator to select all the records where Country is NOT "Norway" and NOT "France".
SELECT * FROM Customers _____ _______ ___ __ ('Norway', 'France');

SQL BETWEEN Operator


The SQL BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.

BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

101
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 18
bags

2 Chang 1 1 24 - 12 oz 19
bottles

3 Aniseed Syrup 1 2 12 - 550 ml 10


bottles

4 Chef Anton's Cajun 1 2 48 - 6 oz jars 22


Seasoning

5 Chef Anton's Gumbo Mix 1 2 36 boxes 21.35

BETWEEN Example
The following SQL statement selects all products with a price BETWEEN 10 and 20:

Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

NOT BETWEEN Example


To display the products outside the range of the previous example, use NOT BETWEEN:

Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

102
BETWEEN with IN Example
The following SQL statement selects all products with a price BETWEEN 10 and 20. In addition; do not
show products with a CategoryID of 1,2, or 3:

Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);

BETWEEN Text Values Example


The following SQL statement selects all products with a ProductName BETWEEN Carnarvon Tigers and
Mozzarella di Giovanni:

Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

The following SQL statement selects all products with a ProductName BETWEEN Carnarvon Tigers and
Chef Anton's Cajun Seasoning:

Example
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun
Seasoning"
ORDER BY ProductName;

NOT BETWEEN Text Values Example


The following SQL statement selects all products with a ProductName NOT BETWEEN Carnarvon Tigers
and Mozzarella di Giovanni:

Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni'
ORDER BY ProductName;

Sample Table
Below is a selection from the "Orders" table in the Northwind sample database:

OrderID CustomerID EmployeeID OrderDate ShipperID

103
10248 90 5 7/4/1996 3

10249 81 6 7/5/1996 1

10250 34 4 7/8/1996 2

10251 84 3 7/9/1996 1

10252 76 4 7/10/1996 2

BETWEEN Dates Example


The following SQL statement selects all orders with an OrderDate BETWEEN '01-July-1996' and '31-July-
1996':

Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #01/07/1996# AND #31/07/1996#;

OR

SELECT * FROM Orders


WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';

EXERCISES:
1. Use the BETWEEN operator to select all the records where the value of the Price column is
between 10 and 20.
SELECT * FROM Products WHERE Price _______ __ ___ __;
2. Use the BETWEEN operator to select all the records where the value of the Price column is NOT
between 10 and 20.
SELECT * FROM Products WHERE Price ___ _______ __ ___ __;
3. Use the BETWEEN operator to select all the records where the value of the ProductName
column is alphabetically between 'Geitost' and 'Pavlova'.
SELECT * FROM Products WHERE ProductName BETWEEN 'Geitost' AND 'Pavlova';

104
SQL Aliases
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of the query.

Alias Column Syntax


SELECT column_name AS alias_name
FROM table_name;

Alias Table Syntax


SELECT column_name(s)
FROM table_name AS alias_name;

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode Country

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

4 Around the Horn Thomas Hardy 120 London WA1 1DP UK


Hanover
Sq.

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

105
10354 58 8 1996-11-14 3

10355 4 6 1996-11-15 1

10356 86 6 1996-11-18 2

Alias for Columns Examples


The following SQL statement creates two aliases, one for the CustomerID column and one for the
CustomerName column:

Example
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;

The following SQL statement creates two aliases, one for the CustomerName column and one for the
ContactName column. Note: It requires double quotation marks or square brackets if the alias name
contains spaces:

Example
SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;

The following SQL statement creates an alias named "Address" that combine four columns (Address,
PostalCode, City and Country):

Example
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' +
Country AS Address
FROM Customers;

Note: To get the SQL statement above to work in MySQL use the following:

SELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,',


',Country) AS Address
FROM Customers;

Alias for Tables Example


The following SQL statement selects all the orders from the customer with CustomerID=4 (Around the
Horn). We use the "Customers" and "Orders" tables, and give them the table aliases of "c" and "o"
respectively (Here we use aliases to make the SQL shorter):

106
Example
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;

The following SQL statement is the same as above, but without aliases:

Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the
Horn' AND Customers.CustomerID=Orders.CustomerID;

Aliases can be useful when:

 There are more than one table involved in a query


 Functions are used in the query
 Column names are big or not very readable
 Two or more columns are combined together

EXERCISES:
1. When displaying the Customers table, make an ALIAS of the PostalCode column, the column
should be called Pno instead.
SELECT CustomerName, Address, PostalCode __ ___ FROM Customers;
2. When displaying the Customers table, refer to the table as Consumers instead of Customers.
SELECT * FROM Customers __ __________;

SQL Joins
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.

Let's look at a selection from the "Orders" table:

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

107
10310 77 1996-09-20

Then, look at a selection from the "Customers" table:

CustomerID CustomerName ContactName Country

1 Alfreds Futterkiste Maria Anders Germany

2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico

3 Antonio Moreno Taquería Antonio Moreno Mexico

Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID" column.

Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records
that have matching values in both tables:

Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

and it will produce something like this:

OrderID CustomerName OrderDate

10308 Ana Trujillo Emparedados y helados 9/18/1996

108
10365 Antonio Moreno Taquería 11/27/1996

10383 Around the Horn 12/16/1996

10355 Around the Horn 11/15/1996

10278 Berglunds snabbköp 8/12/1996

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:

 (INNER) JOIN: Returns records that have matching values in both tables
 LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the
right table
 RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from
the left table
 FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table

109
SQL INNER JOIN Keyword
SQL INNER JOIN Keyword
The INNER JOIN keyword selects records that have matching values in both tables.

INNER JOIN Syntax


SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

And a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode Country

110
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y helados Constitución 2222 D.F.

3 Antonio Moreno Antonio Mataderos 2312 México 05023 Mexico


Taquería Moreno D.F.

SQL INNER JOIN Example


The following SQL statement selects all orders with customer information:

Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match between the
columns. If there are records in the "Orders" table that do not have matches in "Customers", these
orders will not be shown!

JOIN Three Tables


The following SQL statement selects all orders with customer and shipper information:

Example
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);

SQL LEFT JOIN Keyword


SQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from
the right table (table2). The result is NULL from the right side, if there is no match.

LEFT JOIN Syntax


SELECT column_name(s)
FROM table1

111
LEFT JOIN table2
ON table1.column_name = table2.column_name;

Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerI CustomerNam ContactNam Address City PostalCod Country


D e e e

1 Alfreds Maria Anders Obere Str. Berlin 12209 German


Futterkiste 57 y

2 Ana Trujillo Ana Trujillo Avda. de la Méxic 05021 Mexico


Emparedados y Constitució o D.F.
helados n 2222

3 Antonio Moreno Antonio Mataderos Méxic 05023 Mexico


Taquería Moreno 2312 o D.F.

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

112
10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

SQL LEFT JOIN Example


The following SQL statement will select all customers, and any orders they might have:

Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

Note: The LEFT JOIN keyword returns all records from the left table (Customers), even if there are no
matches in the right table (Orders).

SQL RIGHT JOIN Keyword


SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records from
the left table (table1). The result is NULL from the left side, when there is no match.

RIGHT JOIN Syntax


SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

113
OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

And a selection from the "Employees" table:

EmployeeID LastName FirstName BirthDate Photo

1 Davolio Nancy 12/8/1968 EmpID1.pic

2 Fuller Andrew 2/19/1952 EmpID2.pic

3 Leverling Janet 8/30/1963 EmpID3.pic

SQL RIGHT JOIN Example


The following SQL statement will return all employees, and any orders they might have placed:

Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;

Note: The RIGHT JOIN keyword returns all records from the right table (Employees), even if there are no
matches in the left table (Orders).

114
SQL FULL OUTER JOIN Keyword
SQL FULL OUTER JOIN Keyword
The FULL OUTER JOIN keyword returns all records when there is a match in left (table1) or right (table2)
table records.

Note: FULL OUTER JOIN can potentially return very large result-sets!

Tip: FULL OUTER JOIN and FULL JOIN are the same.

FULL OUTER JOIN Syntax


SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerI CustomerNam ContactNam Address City PostalCod Country


D e e e

1 Alfreds Maria Anders Obere Str. Berlin 12209 German


Futterkiste 57 y

2 Ana Trujillo Ana Trujillo Avda. de la Méxic 05021 Mexico


Emparedados y Constitució o D.F.
helados n 2222

115
3 Antonio Moreno Antonio Mataderos Méxic 05023 Mexico
Taquería Moreno 2312 o D.F.

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

SQL FULL OUTER JOIN Example


The following SQL statement selects all customers, and all orders:

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

A selection from the result set may look like this:

CustomerName OrderID

Alfreds Futterkiste Null

Ana Trujillo Emparedados y helados 10308

116
Antonio Moreno Taquería 10365

Note: The FULL OUTER JOIN keyword returns all matching records from both tables whether the other
table matches or not. So, if there are rows in "Customers" that do not have matches in "Orders", or if
there are rows in "Orders" that do not have matches in "Customers", those rows will be listed as well.

SQL Self JOIN


SQL Self JOIN
A self JOIN is a regular join, but the table is joined with itself.

Self JOIN Syntax


SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerI CustomerNam ContactNam Address City PostalCod Country


D e e e

1 Alfreds Maria Anders Obere Str. Berlin 12209 German


Futterkiste 57 y

2 Ana Trujillo Ana Trujillo Avda. de la Méxic 05021 Mexico


Emparedados y Constitució o D.F.
helados n 2222

3 Antonio Moreno Antonio Mataderos Méxic 05023 Mexico


Taquería Moreno 2312 o D.F.

SQL Self JOIN Example


The following SQL statement matches customers that are from the same city:

117
Example
SELECT A.CustomerName AS CustomerName1,
B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;

SQL UNION Operator


The SQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.
 Each SELECT statement within UNION must have the same number of columns
 The columns must also have similar data types
 The columns in each SELECT statement must also be in the same order

UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

UNION ALL Syntax


The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL:

SELECT column_name(s) FROM table1


UNION ALL
SELECT column_name(s) FROM table2;

Note: The column names in the result-set are usually equal to the column names in the first SELECT
statement in the UNION.

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:


CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

118
And a selection from the "Suppliers" table:

SupplierID SupplierName ContactName Address City PostalCode Country

1 Exotic Liquid Charlotte 49 Gilbert London EC1 4SD UK


Cooper St.

2 New Orleans Cajun Shelley Burke P.O. Box New 70117 USA
Delights 78934 Orleans

3 Grandma Kelly's Regina 707 Ann 48104 USA


Homestead Murphy Oxford Rd. Arbor

SQL UNION Example


The following SQL statement returns the cities (only distinct values) from both the "Customers" and the
"Suppliers" table:

Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

Note: If some customers or suppliers have the same city, each city will only be listed once, because
UNION selects only distinct values. Use UNION ALL to also select duplicate values!

SQL UNION ALL Example


The following SQL statement returns the cities (duplicate values also) from both the "Customers" and
the "Suppliers" table:

Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;

SQL UNION With WHERE


The following SQL statement returns the German cities (only distinct values) from both the "Customers"
and the "Suppliers" table:

Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers

119
WHERE Country='Germany'
ORDER BY City;

SQL UNION ALL With WHERE


The following SQL statement returns the German cities (duplicate values also) from both the
"Customers" and the "Suppliers" table:

Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

Another UNION Example


The following SQL statement lists all customers and suppliers:

Example
SELECT 'Customer' AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;

Notice the "AS Type" above - it is an alias. SQL Aliases are used to give a table or a column a temporary
name. An alias only exists for the duration of the query. So, here we have created a temporary column
named "Type", that list whether the contact person is a "Customer" or a "Supplier".

EXERCISES:
1. Insert the missing parts in the JOIN clause to join the two tables Orders and Customers, using
the CustomerID field in both tables as the relationship between the two tables.
SELECT * FROM Orders LEFT JOIN Customers __ _______________________________________;
2. Choose the correct JOIN clause to select all records from the two tables where there is a match
in both tables.
SELECT * FROM Orders _____ ____ ________ ON Orders.CustomerID=Customers.CustomerID;
3. Choose the correct JOIN clause to select all the records from the Customers table plus all the
matches in the Orders table.
SELECT * FROM Orders _____ ____ __________ ON
Orders.CustomerID=Customers.CustomerID;

120
SQL GROUP BY Statement
The SQL GROUP BY Statement
The GROUP BY statement groups rows that have the same values into summary rows, like "find the
number of customers in each country".

The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to
group the result-set by one or more columns.

GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la México 05021 Mexico


helados Constitución 2222 D.F.

3 Antonio Moreno Taquería Antonio Mataderos 2312 México 05023 Mexico


Moreno D.F.

4 Around the Horn Thomas 120 Hanover Sq. London WA1 1DP UK
Hardy

5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden


Berglund

SQL GROUP BY Examples


The following SQL statement lists the number of customers in each country:

Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;

The following SQL statement lists the number of customers in each country, sorted high to low:

Example
SELECT COUNT(CustomerID), Country
FROM Customers

121
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
OrderID CustomerID EmployeeID OrderDate ShipperID

10248 90 5 1996-07-04 3

10249 81 6 1996-07-05 1

10250 34 4 1996-07-08 2

And a selection from the "Shippers" table:

ShipperID ShipperName

1 Speedy Express

2 United Package

3 Federal Shipping

GROUP BY With JOIN Example


The following SQL statement lists the number of orders sent by each shipper:

Example
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM
Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;

EXERCISES:
1. List the number of customers in each country.
SELECT _____ (CustomerID), Country FROM Customers _____ __ _____;
2. List the number of customers in each country, ordered by the country with the most customers
first.
SELECT _____ (CustomerID), Country FROM Customers _____ __ _____ ORDER BY
______________________;

SQL HAVING Clause


The SQL HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate
functions.

HAVING Syntax
122
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222

3 Antonio Antonio Mataderos México 05023 Mexico


Moreno Moreno 2312 D.F.
Taquería

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

SQL HAVING Examples


The following SQL statement lists the number of customers in each country. Only include countries with
more than 5 customers:

Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

The following SQL statement lists the number of customers in each country, sorted high to low (Only
include countries with more than 5 customers):

Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;

123
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
OrderID CustomerID EmployeeID OrderDate ShipperID

10248 90 5 1996-07-04 3

10249 81 6 1996-07-05 1

10250 34 4 1996-07-08 2

And a selection from the "Employees" table:

EmployeeID LastName FirstName BirthDate Photo Notes

1 Davolio Nancy 1968-12-08 EmpID1.pic Education includes a BA....

2 Fuller Andrew 1952-02-19 EmpID2.pic Andrew received his BTS....

3 Leverling Janet 1963-08-30 EmpID3.pic Janet has a BS degree....

More HAVING Examples


The following SQL statement lists the employees that have registered more than 10 orders:

Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;

The following SQL statement lists if the employees "Davolio" or "Fuller" have registered more than 25
orders:

Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
WHERE LastName = 'Davolio' OR LastName = 'Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;

SQL EXISTS Operator


The SQL EXISTS Operator
The EXISTS operator is used to test for the existence of any record in a subquery.

124
The EXISTS operator returns true if the subquery returns one or more records.

EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);

Demo Database
Below is a selection from the "Products" table in the Northwind sample database:

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 bags 18

2 Chang 1 1 24 - 12 oz bottles 19

3 Aniseed Syrup 1 2 12 - 550 ml bottles 10

4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22

5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35

And a selection from the "Suppliers" table:

SupplierID SupplierName ContactName Address City PostalCode Country

1 Exotic Liquid Charlotte 49 Gilbert St. London EC1 4SD UK


Cooper

2 New Orleans Cajun Shelley Burke P.O. Box 78934 New 70117 USA
Delights Orleans

3 Grandma Kelly's Regina 707 Oxford Rd. Ann Arbor 48104 USA
Homestead Murphy

4 Tokyo Traders Yoshi Nagase 9-8 Sekimai Tokyo 100 Japan


Musashino-shi

SQL EXISTS Examples


The following SQL statement returns TRUE and lists the suppliers with a product price less than 20:

Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price < 20);

125
The following SQL statement returns TRUE and lists the suppliers with a product price equal to 22:

Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price = 22);

SQL ANY and ALL Operators


The SQL ANY and ALL Operators
The ANY and ALL operators are used with a WHERE or HAVING clause.

The ANY operator returns true if any of the subquery values meet the condition.

The ALL operator returns true if all of the subquery values meet the condition.

ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);

ALL Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);

Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).

Demo Database
Below is a selection from the "Products" table in the Northwind sample database:

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 bags 18

2 Chang 1 1 24 - 12 oz bottles 19

3 Aniseed Syrup 1 2 12 - 550 ml bottles 10

4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22

5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35


And a selection from the "OrderDetails" table:

126
OrderDetailID OrderID ProductID Quantity

1 10248 11 12

2 10248 42 10

3 10248 72 5

4 10249 14 9

5 10249 51 40

SQL ANY Examples


The ANY operator returns TRUE if any of the subquery values meet the condition.

The following SQL statement returns TRUE and lists the product names if it finds ANY records in the
OrderDetails table that quantity = 10:

Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity
= 10);

The following SQL statement returns TRUE and lists the product names if it finds ANY records in the
OrderDetails table that quantity > 99:

Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity
> 99);

SQL ALL Example


The ALL operator returns TRUE if all of the subquery values meet the condition.

The following SQL statement returns TRUE and lists the product names if ALL the records in the
OrderDetails table has quantity = 10 (so, this example will return FALSE, because not ALL records in the
OrderDetails table has quantity = 10):

Example
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity
= 10);

127
SQL SELECT INTO Statement
The SQL SELECT INTO Statement
The SELECT INTO statement copies data from one table into a new table.

SELECT INTO Syntax


Copy all columns into a new table:
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

Copy only some columns into a new table:

SELECT column1, column2, column3, ...


INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

The new table will be created with the column-names and types as defined in the old table. You can
create new column names using the AS clause.

SQL SELECT INTO Examples


The following SQL statement creates a backup copy of Customers:

SELECT * INTO CustomersBackup2017


FROM Customers;

The following SQL statement uses the IN clause to copy the table into a new table in another database:

SELECT * INTO CustomersBackup2017 IN 'Backup.mdb'


FROM Customers;

The following SQL statement copies only a few columns into a new table:

SELECT CustomerName, ContactName INTO CustomersBackup2017


FROM Customers;

The following SQL statement copies only the German customers into a new table:

SELECT * INTO CustomersGermany


FROM Customers
WHERE Country = 'Germany';

The following SQL statement copies data from more than one table into a new table:

128
SELECT Customers.CustomerName, Orders.OrderID
INTO CustomersOrderBackup2017
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Tip: SELECT INTO can also be used to create a new, empty table using the schema of another. Just add a
WHERE clause that causes the query to return no data:

SELECT * INTO newtable


FROM oldtable
WHERE 1 = 0;

SQL INSERT INTO SELECT Statement


The SQL INSERT INTO SELECT Statement
The INSERT INTO SELECT statement copies data from one table and inserts it into another table.

 INSERT INTO SELECT requires that data types in source and target tables match
 The existing records in the target table are unaffected

INSERT INTO SELECT Syntax


Copy all columns from one table to another table:

INSERT INTO table2


SELECT * FROM table1
WHERE condition;

Copy only some columns from one table into another table:

INSERT INTO table2 (column1, column2, column3, ...)


SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:


CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Emparedados Ana Trujillo Avda. de la México 05021 Mexico


y helados Constitución 2222 D.F.

129
3 Antonio Moreno Taquería Antonio Mataderos 2312 México 05023 Mexico
Moreno D.F.

And a selection from the "Suppliers" table:

SupplierID SupplierName ContactName Address City Postal Country


Code

1 Exotic Liquid Charlotte 49 Gilbert St. Londona EC1 4SD UK


Cooper

2 New Orleans Cajun Delights Shelley Burke P.O. Box New 70117 USA
78934 Orleans

3 Grandma Kelly's Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA
Homestead

SQL INSERT INTO SELECT Examples


The following SQL statement copies "Suppliers" into "Customers" (the columns that are not filled with
data, will contain NULL):

Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers;

The following SQL statement copies "Suppliers" into "Customers" (fill all columns):

Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
SELECT SupplierName, ContactName, Address, City,
PostalCode, Country FROM Suppliers;

The following SQL statement copies only the German suppliers into "Customers":

Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';

130
SQL CASE Statement
The SQL CASE Statement
The CASE statement goes through conditions and returns a value when the first condition is met (like an
IF-THEN-ELSE statement). So, once a condition is true, it will stop reading and return the result. If no
conditions are true, it returns the value in the ELSE clause.

If there is no ELSE part and no conditions are true, it returns NULL.

CASE Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;

Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample database:

OrderDetailID OrderID ProductID Quantity

1 10248 11 12

2 10248 42 10

3 10248 72 5

4 10249 14 9

5 10249 51 40

SQL CASE Examples


The following SQL goes through conditions and returns a value when the first condition is met:

Example
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;

The following SQL will order the customers by City. However, if City is NULL, then order by Country:

Example

131
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);

SQL NULL Functions


SQL IFNULL(), ISNULL(), COALESCE(), and NVL() Functions

Look at the following "Products" table:


P_Id ProductName UnitPrice UnitsInStock UnitsOnOrder

1 Jarlsberg 10.45 16 15

2 Mascarpone 32.56 23

3 Gorgonzola 15.67 9 20

Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values.

Look at the following SELECT statement:

SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder)


FROM Products;

In the example above, if any of the "UnitsOnOrder" values are NULL, the result will be NULL.

Solutions
MySQL

The MySQL IFNULL() function lets you return an alternative value if an expression is NULL:

SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0))


FROM Products;

or we can use the COALESCE() function, like this:

SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))


FROM Products;

132
SQL Server

The SQL Server ISNULL() function lets you return an alternative value when an expression is NULL:

SELECT ProductName, UnitPrice * (UnitsInStock + ISNULL(UnitsOnOrder, 0))


FROM Products;

MS Access

The MS Access IsNull() function returns TRUE (-1) if the expression is a null value, otherwise FALSE (0):

SELECT ProductName, UnitPrice * (UnitsInStock +


IIF(IsNull(UnitsOnOrder), 0, UnitsOnOrder))
FROM Products;

Oracle

The Oracle NVL() function achieves the same result:

SELECT ProductName, UnitPrice * (UnitsInStock + NVL(UnitsOnOrder, 0))


FROM Products;

SQL Stored Procedures for SQL Server


What is a Stored Procedure?
A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over
again.

So if you have an SQL query that you write over and over again, save it as a stored procedure, and then
just call it to execute it.

You can also pass parameters to a stored procedure, so that the stored procedure can act based on the
parameter value(s) that is passed.

Stored Procedure Syntax

CREATE PROCEDURE procedure_name


AS
sql_statement
GO;

Execute a Stored Procedure

EXEC procedure_name;

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

133
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222

3 Antonio Antonio Mataderos México 05023 Mexico


Moreno Moreno 2312 D.F.
Taquería

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

Stored Procedure Example


The following SQL statement creates a stored procedure named "SelectAllCustomers" that selects all
records from the "Customers" table:

Example
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;

Execute the stored procedure above as follows:

Example
EXEC SelectAllCustomers;

Stored Procedure With One Parameter


The following SQL statement creates a stored procedure that selects Customers from a particular City
from the "Customers" table:

Example
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)
AS
SELECT * FROM Customers WHERE City = @City
GO;

Execute the stored procedure above as follows:

134
Example
EXEC SelectAllCustomers @City = 'London';

Stored Procedure With Multiple Parameters


Setting up multiple parameters is very easy. Just list each parameter and the data type separated by a
comma as shown below.

The following SQL statement creates a stored procedure that selects Customers from a particular City
with a particular PostalCode from the "Customers" table:

Example
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode
nvarchar(10)
AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;

Execute the stored procedure above as follows:

Example
EXEC SelectAllCustomers @City = 'London', @PostalCode = 'WA1 1DP';

SQL Comments
SQL Comments
Comments are used to explain sections of SQL statements, or to prevent execution of SQL statements.

Note: The examples in this chapter will not work in Firefox and Microsoft Edge!

Comments are not supported in Microsoft Access databases. Firefox and Microsoft Edge are using
Microsoft Access database in our examples.

Single Line Comments


Single line comments start with --.

Any text between -- and the end of the line will be ignored (will not be executed).

The following example uses a single-line comment as an explanation:

Example
--Select all:
SELECT * FROM Customers;

The following example uses a single-line comment to ignore the end of a line:

Example

135
SELECT * FROM Customers -- WHERE City='Berlin';

The following example uses a single-line comment to ignore a statement:

Example
--SELECT * FROM Customers;
SELECT * FROM Products;

Multi-line Comments
Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored.

The following example uses a multi-line comment as an explanation:

Example
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;

The following example uses a multi-line comment to ignore many statements:

Example
/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;

To ignore just a part of a statement, also use the /* */ comment.

The following example uses a comment to ignore part of a line:

Example
SELECT CustomerName, /*City,*/ Country FROM Customers;

The following example uses a comment to ignore part of a statement:

Example
SELECT * FROM Customers WHERE (CustomerName LIKE 'L%'
OR CustomerName LIKE 'R%' /*OR CustomerName LIKE 'S%'
OR CustomerName LIKE 'T%'*/ OR CustomerName LIKE 'W%')
AND Country='USA'
ORDER BY CustomerName;

136
SQL Operators
SQL Arithmetic Operators
Operator Description

+ Add

- Subtract

* Multiply

/ Divide

% Modulo

SQL Bitwise Operators


Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

SQL Comparison Operators


Operator Description

= Equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

<> Not equal to

SQL Compound Operators


Operator Description

+= Add equals

-= Subtract equals

137
*= Multiply equals

/= Divide equals

%= Modulo equals

&= Bitwise AND equals

^-= Bitwise exclusive equals

|*= Bitwise OR equals

SQL Logical Operators


Operator Description

ALL TRUE if all of the subquery values meet the condition

AND TRUE if all the conditions separated by AND is TRUE

ANY TRUE if any of the subquery values meet the condition

BETWEEN TRUE if the operand is within the range of comparisons

EXISTS TRUE if the subquery returns one or more records

IN TRUE if the operand is equal to one of a list of expressions

LIKE TRUE if the operand matches a pattern

NOT Displays a record if the condition(s) is NOT TRUE

OR TRUE if any of the conditions separated by OR is TRUE

SOME TRUE if any of the subquery values meet the condition

138
MODULE 2: TABLE OF CONTENTS
Create DB 140
Drop DB 140
Backup DB 140
Create Table 141
Drop Table 143
Alter Table 143
Constraints 145
Not Null 146
Unique 147
Primary Key 148
Foreign Key 150
Check 152
Default 153
Index 155
Auto Increment 156
Dates 158
Views 160
Injection 162
Hosting 165
Data Types 166
References 172

139
SQL CREATE DATABASE Statement
The SQL CREATE DATABASE Statement
The CREATE DATABASE statement is used to create a new SQL database.

Syntax
CREATE DATABASE databasename;

CREATE DATABASE Example


The following SQL statement creates a database called "testDB":

Example
CREATE DATABASE testDB;

Tip: Make sure you have admin privilege before creating any database. Once a database is created, you
can check it in the list of databases with the following SQL command: SHOW DATABASES;

SQL DROP DATABASE Statement


The SQL DROP DATABASE Statement
The DROP DATABASE statement is used to drop an existing SQL database.

Syntax
DROP DATABASE databasename;

Note: Be careful before dropping a database. Deleting a database will result in loss of complete
information stored in the database!

DROP DATABASE Example


The following SQL statement drops the existing database "testDB":

Example
DROP DATABASE testDB;

Tip: Make sure you have admin privilege before dropping any database. Once a database is dropped,
you can check it in the list of databases with the following SQL command: SHOW DATABASES;

SQL BACKUP DATABASE for SQL Server


The SQL BACKUP DATABASE Statement
The BACKUP DATABASE statement is used in SQL Server to create a full back up of an existing SQL
database.

Syntax

140
BACKUP DATABASE databasename
TO DISK = 'filepath';

The SQL BACKUP WITH DIFFERENTIAL Statement


A differential back up only backs up the parts of the database that have changed since the last full
database backup.

Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath'
WITH DIFFERENTIAL;

BACKUP DATABASE Example


The following SQL statement creates a full back up of the existing database "testDB" to the D disk:

Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak';

Tip: Always back up the database to a different drive than the actual database. Then, if you get a disk
crash, you will not lose your backup file along with the database.

BACKUP WITH DIFFERENTIAL Example


The following SQL statement creates a differential back up of the database "testDB":

Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak'
WITH DIFFERENTIAL;

Tip: A differential back up reduces the back up time (since only the changes are backed up).

The SQL CREATE TABLE Statement


The CREATE TABLE statement is used to create a new table in a database.

Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);

The column parameters specify the names of the columns of the table.

141
The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date, etc.).

Tip: For an overview of the available data types, go to our complete Data Types Reference.

SQL CREATE TABLE Example


The following example creates a table called "Persons" that contains five columns: PersonID, LastName,
FirstName, Address, and City:

Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

The PersonID column is of type int and will hold an integer.

The LastName, FirstName, Address, and City columns are of type varchar and will hold characters, and
the maximum length for these fields is 255 characters.

The empty "Persons" table will now look like this:

PersonID LastName FirstName Address City

Tip: The empty "Persons" table can now be filled with data with the SQL INSERT INTO statement.
A copy of an existing table can also be created using CREATE TABLE.
The new table gets the same column definitions. All columns or specific columns can be selected.
If you create a new table using an existing table, the new table will be filled with the existing values from
the old table.

Syntax
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;

The following SQL creates a new table called "TestTables" (which is a copy of the "Customers" table):

Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;

142
SQL DROP TABLE Statement
The SQL DROP TABLE Statement
The DROP TABLE statement is used to drop an existing table in a database.

Syntax
DROP TABLE table_name;

Note: Be careful before dropping a table. Deleting a table will result in loss of complete information
stored in the table!

SQL DROP TABLE Example


The following SQL statement drops the existing table "Shippers":

Example
DROP TABLE Shippers;

SQL TRUNCATE TABLE


The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table itself.

Syntax
TRUNCATE TABLE table_name;

SQL ALTER TABLE Statement


SQL ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing table.

ALTER TABLE - ADD Column


To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;

The following SQL adds an "Email" column to the "Customers" table:

Example
ALTER TABLE Customers
ADD Email varchar(255);

ALTER TABLE - DROP COLUMN


To delete a column in a table, use the following syntax (notice that some database systems don't allow
deleting a column):

143
ALTER TABLE table_name
DROP COLUMN column_name;

The following SQL deletes the "Email" column from the "Customers" table:

Example
ALTER TABLE Customers
DROP COLUMN Email;

ALTER TABLE - ALTER/MODIFY COLUMN


To change the data type of a column in a table, use the following syntax:

SQL Server / MS Access:


ALTER TABLE table_name
ALTER COLUMN column_name datatype;

My SQL / Oracle (prior version 10G):


ALTER TABLE table_name
MODIFY COLUMN column_name datatype;

Oracle 10G and later:


ALTER TABLE table_name
MODIFY column_name datatype;

SQL ALTER TABLE Example


Look at the "Persons" table:
ID LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to add a column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:


ALTER TABLE Persons
ADD DateOfBirth date;

Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data type
specifies what type of data the column can hold. For a complete reference of all the data types available
in MS Access, MySQL, and SQL Server, go to our complete Data Types reference.

The "Persons" table will now look like this:


ID LastName FirstName Address City DateOfBirth

144
1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Change Data Type Example


Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:


ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;

Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- or four-
digit format.

DROP COLUMN Example


Next, we want to delete the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:


ALTER TABLE Persons
DROP COLUMN DateOfBirth;
The "Persons" table will now look like this:

ID LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

SQL Constraints
SQL constraints are used to specify rules for data in a table.

SQL Create Constraints


Constraints can be specified when the table is created with the CREATE TABLE statement, or after the
table is created with the ALTER TABLE statement.

Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,

145
....
);

SQL Constraints
SQL constraints are used to specify rules for the data in a table.

Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and
reliability of the data in the table. If there is any violation between the constraint and the data action,
the action is aborted.

Constraints can be column level or table level. Column level constraints apply to a column, and table
level constraints apply to the whole table.

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a
table
 FOREIGN KEY - Uniquely identifies a row/record in another table
 CHECK - Ensures that all values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column when no value is specified
 INDEX - Used to create and retrieve data from the database very quickly

SQL NOT NULL Constraint


SQL NOT NULL Constraint
By default, a column can hold NULL values.

The NOT NULL constraint enforces a column to NOT accept NULL values.

This enforces a field to always contain a value, which means that you cannot insert a new record, or
update a record without adding a value to this field.

SQL NOT NULL on CREATE TABLE


The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept NULL
values when the "Persons" table is created:

Example
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

146
SQL NOT NULL on ALTER TABLE
To create a NOT NULL constraint on the "Age" column when the "Persons" table is already created, use
the following SQL:

ALTER TABLE Persons


MODIFY Age int NOT NULL;

SQL UNIQUE Constraint


SQL UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set
of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per
table.

SQL UNIQUE Constraint on CREATE TABLE


The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is created:

SQL Server / Oracle / MS Access:


CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);

To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the
following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:


CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,

147
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);

SQL UNIQUE Constraint on ALTER TABLE


To create a UNIQUE constraint on the "ID" column when the table is already created, use the following
SQL:

MySQL / SQL Server / Oracle / MS Access:


ALTER TABLE Persons
ADD UNIQUE (ID);

To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the
following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:


ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

DROP a UNIQUE Constraint


To drop a UNIQUE constraint, use the following SQL:

MySQL:
ALTER TABLE Persons
DROP INDEX UC_Person;

SQL Server / Oracle / MS Access:


ALTER TABLE Persons
DROP CONSTRAINT UC_Person;

SQL PRIMARY KEY Constraint


SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a table.

Primary keys must contain UNIQUE values, and cannot contain NULL values.

A table can have only ONE primary key; and in the table, this primary key can consist of single or
multiple columns (fields).

SQL PRIMARY KEY on CREATE TABLE


The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is created:

MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
148
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

SQL Server / Oracle / MS Access:


CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple
columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:


CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);

Note: In the example above there is only ONE PRIMARY KEY (PK_Person). However, the VALUE of the
primary key is made up of TWO COLUMNS (ID + LastName).

SQL PRIMARY KEY on ALTER TABLE


To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use the
following SQL:

MySQL / SQL Server / Oracle / MS Access:


ALTER TABLE Persons
ADD PRIMARY KEY (ID);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple
columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:


ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);

Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must
already have been declared to not contain NULL values (when the table was first created).

149
DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the following SQL:

MySQL:
ALTER TABLE Persons
DROP PRIMARY KEY;

SQL Server / Oracle / MS Access:


ALTER TABLE Persons
DROP CONSTRAINT PK_Person;

SQL FOREIGN KEY Constraint


SQL FOREIGN KEY Constraint
A FOREIGN KEY is a key used to link two tables together.
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another
table.
The table containing the foreign key is called the child table, and the table containing the candidate key
is called the referenced or parent table.
Look at the following two tables:

"Persons" table:
PersonID LastName FirstName Age

1 Hansen Ola 30

2 Svendson Tove 23

3 Pettersen Kari 20

"Orders" table:
OrderID OrderNumber PersonID

1 77895 3

2 44678 3

3 22456 2

4 24562 1

Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

150
The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key column,
because it has to be one of the values contained in the table it points to.

SQL FOREIGN KEY on CREATE TABLE


The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is created:

MySQL:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

SQL Server / Oracle / MS Access:


CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple
columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:


CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);

SQL FOREIGN KEY on ALTER TABLE


To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is already
created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:


ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple
columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

151
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

DROP a FOREIGN KEY Constraint


To drop a FOREIGN KEY constraint, use the following SQL:

MySQL:
ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;

SQL Server / Oracle / MS Access:


ALTER TABLE Orders
DROP CONSTRAINT FK_PersonOrder;

SQL CHECK Constraint


SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on values in
other columns in the row.

SQL CHECK on CREATE TABLE


The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is created.
The CHECK constraint ensures that the age of a person must be 18, or older:

MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

SQL Server / Oracle / MS Access:


CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use
the following SQL syntax:

152
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);

SQL CHECK on ALTER TABLE


To create a CHECK constraint on the "Age" column when the table is already created, use the following
SQL:

MySQL / SQL Server / Oracle / MS Access:


ALTER TABLE Persons
ADD CHECK (Age>=18);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use
the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:


ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');

DROP a CHECK Constraint


To drop a CHECK constraint, use the following SQL:

SQL Server / Oracle / MS Access:


ALTER TABLE Persons
DROP CONSTRAINT CHK_PersonAge;

MySQL:
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;

SQL DEFAULT Constraint


SQL DEFAULT Constraint
The DEFAULT constraint is used to provide a default value for a column.

The default value will be added to all new records IF no other value is specified.

153
SQL DEFAULT on CREATE TABLE
The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is created:

My SQL / SQL Server / Oracle / MS Access:


CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);

The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():

CREATE TABLE Orders (


ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE()
);

SQL DEFAULT on ALTER TABLE


To create a DEFAULT constraint on the "City" column when the table is already created, use the
following SQL:

MySQL:
ALTER TABLE Persons
ALTER City SET DEFAULT 'Sandnes';

SQL Server:
ALTER TABLE Persons
ADD CONSTRAINT df_City
DEFAULT 'Sandnes' FOR City;

MS Access:
ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT 'Sandnes';

Oracle:
ALTER TABLE Persons
MODIFY City DEFAULT 'Sandnes';

DROP a DEFAULT Constraint


To drop a DEFAULT constraint, use the following SQL:

MySQL:
ALTER TABLE Persons
ALTER City DROP DEFAULT;
154
SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT;

SQL CREATE INDEX Statement


SQL CREATE INDEX Statement
The CREATE INDEX statement is used to create indexes in tables.

Indexes are used to retrieve data from the database more quickly than otherwise. The users cannot see
the indexes, they are just used to speed up searches/queries.

Note: Updating a table with indexes takes more time than updating a table without (because the
indexes also need an update). So, only create indexes on columns that will be frequently searched
against.

CREATE INDEX Syntax


Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name


ON table_name (column1, column2, ...);

CREATE UNIQUE INDEX Syntax


Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name


ON table_name (column1, column2, ...);

Note: The syntax for creating indexes varies among different databases. Therefore: Check the syntax for
creating indexes in your database.

CREATE INDEX Example


The SQL statement below creates an index named "idx_lastname" on the "LastName" column in the
"Persons" table:

CREATE INDEX idx_lastname


ON Persons (LastName);

If you want to create an index on a combination of columns, you can list the column names within the
parentheses, separated by commas:

CREATE INDEX idx_pname


ON Persons (LastName, FirstName);

DROP INDEX Statement


The DROP INDEX statement is used to delete an index in a table.
155
MS Access:
DROP INDEX index_name ON table_name;

SQL Server:
DROP INDEX table_name.index_name;

DB2/Oracle:
DROP INDEX index_name;

MySQL:
ALTER TABLE table_name
DROP INDEX index_name;

SQL AUTO INCREMENT Field


AUTO INCREMENT Field
Auto-increment allows a unique number to be generated automatically when a new record is inserted
into a table.

Often this is the primary key field that we would like to be created automatically every time a new
record is inserted.

Syntax for MySQL


The following SQL statement defines the "Personid" column to be an auto-increment primary key field in
the "Persons" table:

CREATE TABLE Persons (


Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);

MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature.


By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.
To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:

ALTER TABLE Persons AUTO_INCREMENT=100;

To insert a new record into the "Persons" table, we will NOT have to specify a value for the "Personid"
column (a unique value will be added automatically):

INSERT INTO Persons (FirstName,LastName)


VALUES ('Lars','Monsen');

156
The SQL statement above would insert a new record into the "Persons" table. The "Personid" column
would be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName"
column would be set to "Monsen".

Syntax for SQL Server


The following SQL statement defines the "Personid" column to be an auto-increment primary key field in
the "Persons" table:

CREATE TABLE Persons (


Personid int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.
In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new
record.
Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to
IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "Personid"
column (a unique value will be added automatically):

INSERT INTO Persons (FirstName,LastName)


VALUES ('Lars','Monsen');

The SQL statement above would insert a new record into the "Persons" table. The "Personid" column
would be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName"
column would be set to "Monsen".

Syntax for Access


The following SQL statement defines the "Personid" column to be an auto-increment primary key field in
the "Persons" table:

CREATE TABLE Persons (


Personid AUTOINCREMENT PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

The MS Access uses the AUTOINCREMENT keyword to perform an auto-increment feature.


By default, the starting value for AUTOINCREMENT is 1, and it will increment by 1 for each new record.
Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change the
autoincrement to AUTOINCREMENT(10,5).

157
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "Personid"
column (a unique value will be added automatically):

INSERT INTO Persons (FirstName,LastName)


VALUES ('Lars','Monsen');

The SQL statement above would insert a new record into the "Persons" table. The "Personid" column
would be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName"
column would be set to "Monsen".

Syntax for Oracle


In Oracle the code is a little bit more tricky.

You will have to create an auto-increment field with the sequence object (this object generates a
number sequence).

Use the following CREATE SEQUENCE syntax:


CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;

The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1.
It will also cache up to 10 values for performance. The cache option specifies how many sequence values
will be stored in memory for faster access.

To insert a new record into the "Persons" table, we will have to use the nextval function (this function
retrieves the next value from seq_person sequence):

INSERT INTO Persons (Personid,FirstName,LastName)


VALUES (seq_person.nextval,'Lars','Monsen');

The SQL statement above would insert a new record into the "Persons" table. The "Personid" column
would be assigned the next number from the seq_person sequence. The "FirstName" column would be
set to "Lars" and the "LastName" column would be set to "Monsen".

SQL Working With Dates


SQL Dates
The most difficult part when working with dates is to be sure that the format of the date you are trying
to insert, matches the format of the date column in the database.

As long as your data contains only the date portion, your queries will work as expected. However, if a
time portion is involved, it gets more complicated.

158
SQL Date Data Types
MySQL comes with the following data types for storing a date or a date/time value in the database:

 DATE - format YYYY-MM-DD


 DATETIME - format: YYYY-MM-DD HH:MI:SS
 TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
 YEAR - format YYYY or YY

SQL Server comes with the following data types for storing a date or a date/time value in the database:

 DATE - format YYYY-MM-DD


 DATETIME - format: YYYY-MM-DD HH:MI:SS
 SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
 TIMESTAMP - format: a unique number

Note: The date types are chosen for a column when you create a new table in your database!

SQL Working with Dates


You can compare two dates easily if there is no time component involved!

Assume we have the following "Orders" table:


OrderId ProductName OrderDate

1 Geitost 2008-11-11

2 Camembert Pierrot 2008-11-09

3 Mozzarella di Giovanni 2008-11-11

4 Mascarpone Fabioli 2008-10-29

Now we want to select the records with an OrderDate of "2008-11-11" from the table above.

We use the following SELECT statement:


SELECT * FROM Orders WHERE OrderDate='2008-11-11'

The result-set will look like this:

OrderId ProductName OrderDate

1 Geitost 2008-11-11

3 Mozzarella di Giovanni 2008-11-11

Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate"
column):
159
OrderId ProductName OrderDate

1 Geitost 2008-11-11 13:23:44

2 Camembert Pierrot 2008-11-09 15:45:21

3 Mozzarella di Giovanni 2008-11-11 11:12:01

4 Mascarpone Fabioli 2008-10-29 14:56:59

If we use the same SELECT statement as above:


SELECT * FROM Orders WHERE OrderDate='2008-11-11'

we will get no result! This is because the query is looking only for dates with no time portion.

Tip: To keep your queries simple and easy to maintain, do not allow time components in your dates!

SQL Views
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or more
real tables in the database.

You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data
were coming from one single table.

CREATE VIEW Syntax


CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Note: A view always shows up-to-date data! The database engine recreates the data, using the view's
SQL statement, every time a user queries a view.

SQL CREATE VIEW Examples


The following SQL creates a view that shows all customers from Brazil:

Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';

160
We can query the view above as follows:

Example
SELECT * FROM [Brazil Customers];

The following SQL creates a view that selects every product in the "Products" table with a price higher
than the average price:

Example
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);

We can query the view above as follows:

Example
SELECT * FROM [Products Above Average Price];

SQL Updating a View


A view can be updated with the CREATE OR REPLACE VIEW command.

SQL CREATE OR REPLACE VIEW Syntax


CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

The following SQL adds the "City" column to the "Brazil Customers" view:

Example
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';

SQL Dropping a View


A view is deleted with the DROP VIEW command.

SQL DROP VIEW Syntax


DROP VIEW view_name;

The following SQL drops the "Brazil Customers" view:

Example
DROP VIEW [Brazil Customers];

161
SQL Injection
SQL Injection
SQL injection is a code injection technique that might destroy your database.
SQL injection is one of the most common web hacking techniques.
SQL injection is the placement of malicious code in SQL statements, via web page input.

SQL in Web Pages


SQL injection usually occurs when you ask a user for input, like their username/userid, and instead of a
name/id, the user gives you an SQL statement that you will unknowingly run on your database.

Look at the following example which creates a SELECT statement by adding a variable (txtUserId) to a
select string. The variable is fetched from user input (getRequestString):

Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;

The rest of this chapter describes the potential dangers of using user input in SQL statements.

SQL Injection Based on 1=1 is Always True


Look at the example above again. The original purpose of the code was to create an SQL statement to
select a user, with a given user id.

If there is nothing to prevent a user from entering "wrong" input, the user can enter some "smart" input
like this:

UserId:

Then, the SQL statement will look like this:

SELECT * FROM Users WHERE UserId = 105 OR 1=1;

The SQL above is valid and will return ALL rows from the "Users" table, since OR 1=1 is always TRUE.

Does the example above look dangerous? What if the "Users" table contains names and passwords?

The SQL statement above is much the same as this:

SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1;

A hacker might get access to all the user names and passwords in a database, by simply inserting 105 OR
1=1 into the input field.

SQL Injection Based on ""="" is Always True


Here is an example of a user login on a web site:

162
Username:

Password:

Example
uName = getRequestString("username");
uPass = getRequestString("userpassword");

sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' +
uPass + '"'

Result
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"

A hacker might get access to user names and passwords in a database by simply inserting " OR ""=" into
the user name or password text box:

User Name:

Password:

The code at the server will create a valid SQL statement like this:

Result
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""

The SQL above is valid and will return all rows from the "Users" table, since OR ""="" is always TRUE.

SQL Injection Based on Batched SQL Statements


Most databases support batched SQL statement.
A batch of SQL statements is a group of two or more SQL statements, separated by semicolons.
The SQL statement below will return all rows from the "Users" table, then delete the "Suppliers" table.

Example
SELECT * FROM Users; DROP TABLE Suppliers

Look at the following example:

Example

163
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;

And the following input:

User id: 105; DROP TABLE Suppliers

The valid SQL statement would look like this:

Result
SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers;

Use SQL Parameters for Protection


To protect a web site from SQL injection, you can use SQL parameters.
SQL parameters are values that are added to an SQL query at execution time, in a controlled manner.

ASP.NET Razor Example


txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = @0";
db.Execute(txtSQL,txtUserId);

Note that parameters are represented in the SQL statement by a @ marker.

The SQL engine checks each parameter to ensure that it is correct for its column and are treated
literally, and not as part of the SQL to be executed.

Another Example
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);

Examples
The following examples shows how to build parameterized queries in some common web languages.
SELECT STATEMENT IN ASP.NET:

txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserId);
command.ExecuteReader();

INSERT INTO STATEMENT IN ASP.NET:


txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");

164
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
command = new SqlCommand(txtSQL);
command.Parameters.AddWithValue("@0",txtNam);
command.Parameters.AddWithValue("@1",txtAdd);
command.Parameters.AddWithValue("@2",txtCit);
command.ExecuteNonQuery();

INSERT INTO STATEMENT IN PHP:


$stmt = $dbh->prepare("INSERT INTO Customers (CustomerName,Address,City)
VALUES (:nam, :add, :cit)");
$stmt->bindParam(':nam', $txtNam);
$stmt->bindParam(':add', $txtAdd);
$stmt->bindParam(':cit', $txtCit);
$stmt->execute();

SQL Hosting
SQL Hosting
If you want your web site to be able to store and retrieve data from a database, your web server should
have access to a database-system that uses the SQL language.
If your web server is hosted by an Internet Service Provider (ISP), you will have to look for SQL hosting
plans.
The most common SQL hosting databases are MS SQL Server, Oracle, MySQL, and MS Access.

MS SQL Server
Microsoft's SQL Server is a popular database software for database-driven web sites with high traffic.
SQL Server is a very powerful, robust and full featured SQL database system.

Oracle
Oracle is also a popular database software for database-driven web sites with high traffic.
Oracle is a very powerful, robust and full featured SQL database system.

MySQL
MySQL is also a popular database software for web sites.
MySQL is a very powerful, robust and full featured SQL database system.
MySQL is an inexpensive alternative to the expensive Microsoft and Oracle solutions.

Access
When a web site requires only a simple database, Microsoft Access can be a solution.
Access is not well suited for very high-traffic, and not as powerful as MySQL, SQL Server, or Oracle.

165
SQL Data Types for MySQL, SQL Server, and MS Access
The data type of a column defines what value the column can hold: integer, character, money, date and
time, binary, and so on.

SQL Data Types


Each column in a database table is required to have a name and a data type.

An SQL developer must decide what type of data that will be stored inside each column when creating a
table. The data type is a guideline for SQL to understand what type of data is expected inside of each
column, and it also identifies how SQL will interact with the stored data.

Note: Data types might have different names in different database. And even if the name is the same,
the size and other details may be different! Always check the documentation!

MySQL Data Types (Version 8.0)


In MySQL there are three main data types: string, numeric, and date and time.

String data types:


Data type Description

CHAR(size) A FIXED length string (can contain letters, numbers, and special
characters). The size parameter specifies the column length in
characters - can be from 0 to 255. Default is 1

VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and special
characters). The size parameter specifies the maximum column length
in characters - can be from 0 to 65535

BINARY(size) Equal to CHAR(), but stores binary byte strings. The size parameter
specifies the column length in bytes. Default is 1

VARBINARY(size) Equal to VARCHAR(), but stores binary byte strings.


The size parameter specifies the maximum column length in bytes.

TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255 bytes

TINYTEXT Holds a string with a maximum length of 255 characters

TEXT(size) Holds a string with a maximum length of 65,535 bytes

BLOB(size) For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data

MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters

MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of


data

166
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters

LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of


data

ENUM(val1, val2, val3, ...) A string object that can have only one value, chosen from a list of
possible values. You can list up to 65535 values in an ENUM list. If a
value is inserted that is not in the list, a blank value will be inserted.
The values are sorted in the order you enter them

SET(val1, val2, val3, ...) A string object that can have 0 or more values, chosen from a list of
possible values. You can list up to 64 values in a SET list

Numeric data types:


Data type Description

BIT(size) A bit-value type. The number of bits per value is specified in size.
The size parameter can hold a value from 1 to 64. The default value
for size is 1.

TINYINT(size) A very small integer. Signed range is from -128 to 127. Unsigned range
is from 0 to 255. The size parameter specifies the maximum display
width (which is 255)

BOOL Zero is considered as false, nonzero values are considered as true.

BOOLEAN Equal to BOOL

SMALLINT(size) A small integer. Signed range is from -32768 to 32767. Unsigned range
is from 0 to 65535. The size parameter specifies the maximum display
width (which is 255)

MEDIUMINT(size) A medium integer. Signed range is from -8388608 to 8388607.


Unsigned range is from 0 to 16777215. The size parameter specifies
the maximum display width (which is 255)

INT(size) A medium integer. Signed range is from -2147483648 to 2147483647.


Unsigned range is from 0 to 4294967295. The size parameter specifies
the maximum display width (which is 255)

INTEGER(size) Equal to INT(size)

BIGINT(size) A large integer. Signed range is from -9223372036854775808 to


9223372036854775807. Unsigned range is from 0 to
18446744073709551615. The size parameter specifies the maximum
display width (which is 255)

167
FLOAT(size, d) A floating point number. The total number of digits is specified in size.
The number of digits after the decimal point is specified in
the d parameter. This syntax is deprecated in MySQL 8.0.17, and it will
be removed in future MySQL versions

FLOAT(p) A floating point number. MySQL uses the p value to determine


whether to use FLOAT or DOUBLE for the resulting data type. If p is
from 0 to 24, the data type becomes FLOAT(). If p is from 25 to 53, the
data type becomes DOUBLE()

DOUBLE(size, d) A normal-size floating point number. The total number of digits is


specified in size. The number of digits after the decimal point is
specified in the d parameter

DOUBLE PRECISION(size, d)

DECIMAL(size, d) An exact fixed-point number. The total number of digits is specified


in size. The number of digits after the decimal point is specified in
the d parameter. The maximum number for size is 65. The maximum
number for d is 30. The default value for size is 10. The default value
for d is 0.

DEC(size, d) Equal to DECIMAL(size,d)

Note: All the numeric data types may have an extra option: UNSIGNED or ZEROFILL. If you add the
UNSIGNED option, MySQL disallows negative values for the column. If you add the ZEROFILL option,
MySQL automatically also adds the UNSIGNED attribute to the column.

Date and Time data types:


Data type Description

DATE A date. Format: YYYY-MM-DD. The supported range is from '1000-01-


01' to '9999-12-31'

DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The


supported range is from '1000-01-01 00:00:00' to '9999-12-31
23:59:59'. Adding DEFAULT and ON UPDATE in the column definition
to get automatic initialization and updating to the current date and
time

TIMESTAMP(fsp) A timestamp. TIMESTAMP values are stored as the number of seconds


since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-
DD hh:mm:ss. The supported range is from '1970-01-01 00:00:01' UTC
to '2038-01-09 03:14:07' UTC. Automatic initialization and updating to
the current date and time can be specified using DEFAULT
CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP in the
column definition

168
TIME(fsp) A time. Format: hh:mm:ss. The supported range is from '-838:59:59'
to '838:59:59'

YEAR A year in four-digit format. Values allowed in four-digit format: 1901


to 2155, and 0000.
MySQL 8.0 does not support year in two-digit format.

SQL Server Data Types


String data types:
Data type Description Max size Storage

char(n) Fixed width character 8,000 characters Defined width


string

varchar(n) Variable width 8,000 characters 2 bytes + number of


character string chars

varchar(max) Variable width 1,073,741,824 2 bytes + number of


character string characters chars

text Variable width 2GB of text data 4 bytes + number of


character string chars

nchar Fixed width Unicode 4,000 characters Defined width x 2


string

nvarchar Variable width Unicode 4,000 characters


string

nvarchar(max) Variable width Unicode 536,870,912


string characters

ntext Variable width Unicode 2GB of text data


string

binary(n) Fixed width binary 8,000 bytes


string

varbinary Variable width binary 8,000 bytes


string

varbinary(max) Variable width binary 2GB


string

image Variable width binary 2GB


string

169
Numeric data types:
Data type Description Storage

bit Integer that can be 0, 1, or NULL

tinyint Allows whole numbers from 0 to 255 1 byte

smallint Allows whole numbers between -32,768 and 32,767 2 bytes

int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes

bigint Allows whole numbers between -9,223,372,036,854,775,808 and 8 bytes


9,223,372,036,854,775,807

decimal(p,s) Fixed precision and scale numbers. 5-17


Allows numbers from -10^38 +1 to 10^38 –1. bytes
The p parameter indicates the maximum total number of digits that
can be stored (both to the left and to the right of the decimal point). p
must be a value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored to
the right of the decimal point. s must be a value from 0 to p. Default
value is 0

numeric(p,s) Fixed precision and scale numbers. 5-17


Allows numbers from -10^38 +1 to 10^38 –1. bytes
The p parameter indicates the maximum total number of digits that
can be stored (both to the left and to the right of the decimal point). p
must be a value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored to
the right of the decimal point. s must be a value from 0 to p. Default
value is 0

smallmoney Monetary data from -214,748.3648 to 214,748.3647 4 bytes

money Monetary data from -922,337,203,685,477.5808 to 8 bytes


922,337,203,685,477.5807

float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308. 4 or 8
The n parameter indicates whether the field should hold 4 or 8 bytes. bytes
float(24) holds a 4-byte field and float(53) holds an 8-byte field.
Default value of n is 53.

real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes

Date and Time data types:


Data type Description Storage

170
datetime From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 8 bytes
milliseconds

datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100 6-8
nanoseconds bytes

smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytes

date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes

time Store a time only to an accuracy of 100 nanoseconds 3-5


bytes

datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10
bytes

timestamp Stores a unique number that gets updated every time a row gets
created or modified. The timestamp value is based upon an internal
clock and does not correspond to real time. Each table may have only
one timestamp variable

Other data types:


Data type Description

sql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext, and
timestamp

uniqueidentifier Stores a globally unique identifier (GUID)

xml Stores XML formatted data. Maximum 2GB

cursor Stores a reference to a cursor used for database operations

table Stores a result-set for later processing

Microsoft Access Data Types


Data type Description Storage

Text Use for text or combinations of text and numbers. 255 characters
maximum

Memo Memo is used for larger amounts of text. Stores up to 65,536


characters. Note: You cannot sort a memo field. However, they are
searchable

Byte Allows whole numbers from 0 to 255 1 byte

171
Integer Allows whole numbers between -32,768 and 32,767 2 bytes

Long Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes

Single Single precision floating-point. Will handle most decimals 4 bytes

Double Double precision floating-point. Will handle most decimals 8 bytes

Currency Use for currency. Holds up to 15 digits of whole dollars, plus 4 decimal 8 bytes
places. Tip: You can choose which country's currency to use

AutoNumber AutoNumber fields automatically give each record its own number, 4 bytes
usually starting at 1

Date/Time Use for dates and times 8 bytes

Yes/No A logical field can be displayed as Yes/No, True/False, or On/Off. In 1 bit


code, use the constants True and False (equivalent to -1 and
0). Note: Null values are not allowed in Yes/No fields

Ole Object Can store pictures, audio, video, or other BLOBs (Binary Large OBjects) up to
1GB

Hyperlink Contain links to other files, including web pages

Lookup Wizard Let you type a list of options, which can then be chosen from a drop- 4 bytes
down list

REFERENCES
https://www.w3schools.com/sql/default.asp

172

You might also like