Вы находитесь на странице: 1из 395

SQL Tutorial

SQL HOME 03
SQL Intro 11
SQL Syntax 20
SQL Select 29
SQL Select Distinct 42
SQL Where 51
SQL And, Or, Not 55
SQL Order By 57
SQL Insert Into 94
SQL Null Values 97
SQL Update 100
SQL Delete 104
SQL Select Top 111
SQL Min and Max 114
SQL Count, Avg, Sum 117
SQL Like 120
SQL Wildcards 134
SQL In 150
SQL Between 152
SQL Aliases 161
SQL Joins 164
SQL Inner Join 166
SQL Left Join 177
SQL Right Join 187
SQL Full Join 189
SQL Self Join 192
SQL Union 197
SQL Group By 215
SQL Having 221
SQL Exists 225
SQL Any, All 229
SQL Select Into 233
SQL Insert Into Select 234

1
SQL Comments 237

SQL Database

SQL Create DB 282


SQL Drop DB 283
SQL Create Table 283
SQL Drop Table 285
SQL Alter Table 286
SQL Constraints 289
SQL Not Null 290
SQL Unique 291
SQL Primary Key 293
SQL Foreign Key 295
SQL Check 298
SQL Default 300
SQL Index 302
SQL Auto Increment 303
SQL Views 307
SQL Injection 309
SQL Hosting 314

SQL References

SQL Functions 315


SQL Date Functions 317
SQL Null Functions 322
SQL Operators 324
SQL Data Types 376
SQL DB Data Types 380
SQL Quick Ref 390

SQL Quiz

SQL Quiz 394

2
SQL Tutorial

SQL is a standard language for storing, manipulating and retrieving data


in databases.

Our SQL tutorial will teach you how to use SQL in: MySQL, SQL Server,
MS Access, Oracle, Sybase, Informix, Postgres, and other database
systems.

Examples in Each Chapter

With our online SQL editor, you can edit the SQL statements, and click
on a button to view the result.

Example
SELECT * FROM Customers;
Number of Records: 91

Custom Customer ContactN Address City PostalC Countr


erID Name ame ode y

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Avda. de Mxico 05021 Mexico


Emparedad Trujillo la D.F.
os y Constituci
helados n 2222

3 Antonio Antonio Mataderos Mxico 05023 Mexico


Moreno Moreno 2312 D.F.
Taquera

4 Around the Thomas 120 London WA1 UK


Horn Hardy Hanover 1DP
Sq.

5 Berglunds Christina Berguvsv Lule S-958 Sweden


snabbkp Berglund gen 8 22

6 Blauer See Hanna Forsterstr. Mannhei 68306 German


Delikatesse Moos 57 m y
n

7 Blondel Frdrique 24, place Strasbou 67000 France


pre et fils Citeaux Klber rg

3
8 Blido Martn C/ Araquil, Madrid 28023 Spain
Comidas Sommer 67
preparadas

9 Bon app' Laurence 12, rue Marseille 13008 France


Lebihans des
Bouchers

10 Bottom- Elizabeth 23 Tsawass T2F 8M4 Canada


Dollar Lincoln Tsawassen en
Marketse Blvd.

11 B's Victoria Fauntleroy London EC2 5NT UK


Beverages Ashworth Circus

12 Cactus Patricio Cerrito Buenos 1010 Argenti


Comidas Simpson 333 Aires na
para llevar

13 Centro Francisco Sierras de Mxico 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

14 Chop-suey Yang Hauptstr. Bern 3012 Switzerl


Chinese Wang 29 and

15 Comrcio Pedro Av. dos So 05432- Brazil


Mineiro Afonso Lusadas, Paulo 043
23

16 Consolidate Elizabeth Berkeley London WX1 UK


d Holdings Brown Gardens 6LT
12
Brewery

17 Drachenblu Sven Walserweg Aachen 52066 German


t Ottlieb 21 y
Delikatesse
nd

18 Du monde Janine 67, rue Nantes 44000 France


entier Labrune des
Cinquante
Otages

19 Eastern Ann Devon 35 King London WX3 UK


Connection George 6FW

20 Ernst Roland Kirchgasse Graz 8010 Austria


Handel Mendel 6

4
21 Familia Aria Cruz Rua Ors, So 05442- Brazil
Arquibaldo 92 Paulo 030

22 FISSA Diego Roel C/ Madrid 28034 Spain


Fabrica Moralzarza
Inter. l, 86
Salchichas
S.A.

23 Folies Martine 184, Lille 59000 France


gourmande Ranc chausse
s de Tournai

24 Folk och f Maria kergatan Brcke S-844 Sweden


HB Larsson 24 67

25 Frankenver Peter Berliner Mnchen 80805 German


sand Franken Platz 43 y

26 France Carine 54, rue Nantes 44000 France


restauratio Schmitt Royale
n

27 Franchi Paolo Via Monte Torino 10100 Italy


S.p.A. Accorti Bianco 34

28 Furia Lino Jardim das Lisboa 1675 Portuga


Bacalhau e Rodriguez rosas n. l
Frutos do 32
Mar

29 Galera del Eduardo Rambla de Barcelon 08022 Spain


gastrnomo Saavedra Catalua, a
23

30 Godos Jos Pedro C/ Sevilla 41101 Spain


Cocina Freyre Romero,
Tpica 33

31 Gourmet Andr Av. Brasil, Campina 04876- Brazil


Lanchonete Fonseca 442 s 786
s

32 Great Lakes Howard 2732 Eugene 97403 USA


Food Snyder Baker
Market Blvd.

33 GROSELLA- Manuel 5 Ave. Caracas 1081 Venezu


Restaurante Pereira Los Palos ela
Grandes

5
34 Hanari Mario Rua do Rio de 05454- Brazil
Carnes Pontes Pao, 67 Janeiro 876

35 HILARIN- Carlos Carrera 22 San 5022 Venezu


Abastos Hernndez con Ave. Cristbal ela
Carlos
Soublette
#8-35

36 Hungry Yoshi City Elgin 97827 USA


Coyote Latimer Center
Import Plaza 516
Store Main St.

37 Hungry Owl Patricia 8 Cork Ireland


All-Night McKenna Johnstown
Grocers Road

38 Island Helen Garden Cowes PO31 UK


Trading Bennett House 7PJ
Crowther
Way

39 Kniglich Philip Maubelstr. Branden 14776 German


Essen Cramer 90 burg y

40 La corne Daniel 67, Versaille 78000 France


d'abondanc Tonini avenue de s
e l'Europe

41 La maison Annette 1 rue Toulouse 31000 France


d'Asie Roulet Alsace-
Lorraine

42 Laughing Yoshi 1900 Oak Vancouv V3F 2K1 Canada


Bacchus Tannamuri St. er
Wine
Cellars

43 Lazy K John Steel 12 Walla 99362 USA


Kountry Orchestra Walla
Store Terrace

44 Lehmanns Renate Magazinw Frankfurt 60528 German


Marktstand Messner eg 7 a.M. y

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


Shop Yorres St. Suite 5 Francisc
o

6
46 LILA- Carlos Carrera 52 Barquisi 3508 Venezu
Supermerca Gonzlez con Ave. meto ela
do Bolvar
#65-98
Llano
Largo

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


Delicateses Izquierdo Mayo Margarit ela
Porlamar a

48 Lonesome Fran 89 Portland 97219 USA


Pine Wilson Chiaroscur
Restaurant o Rd.

49 Magazzini Giovanni Via Bergamo 24100 Italy


Alimentari Rovelli Ludovico il
Riuniti Moro 22

50 Maison Catherine Rue Bruxelles B-1180 Belgium


Dewey Dewey Joseph-
Bens 532

51 Mre Jean 43 rue St. Montral H1J 1C3 Canada


Paillarde Fresnire Laurent

52 Morgenster Alexander Heerstr. Leipzig 04179 German


n Feuer 22 y
Gesundkost

53 North/Sout Simon South London SW7 UK


h Crowther House 300 1RZ
Queensbri
dge

54 Ocano Yvonne Ing. Buenos 1010 Argenti


Atlntico Moncada Gustavo Aires na
Ltda. Moncada
8585 Piso
20-A

55 Old World Rene 2743 Anchora 99508 USA


Delicatesse Phillips Bering St. ge
n

56 Ottilies Henriette Mehrheim Kln 50739 German


Kseladen Pfalzheim erstr. 369 y

57 Paris Marie 265, Paris 75012 France


spcialits Bertrand boulevard

7
Charonne

58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico


Comidas Fernndez Jorge D.F.
clsicas Cash 321

59 Piccolo und Georg Geislweg Salzburg 5020 Austria


mehr Pipps 14

60 Princesa Isabel de Estrada da Lisboa 1756 Portuga


Isabel Castro sade n. l
Vinhoss 58

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificado Janeiro 673
ra, 12

62 Queen Lcia Alameda So 05487- Brazil


Cozinha Carvalho dos Paulo 020
Canrios,
891

63 QUICK-Stop Horst Taucherstr Cunewal 01307 German


Kloss ae 10 de y

64 Rancho Sergio Av. del Buenos 1010 Argenti


grande Gutirrez Libertador Aires na
900

65 Rattlesnake Paula 2817 Albuquer 87110 USA


Canyon Wilson Milton Dr. que
Grocery

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacaba Janeiro 890
na, 267

68 Richter Michael Grenzache Genve 1203 Switzerl


Supermarkt Holz rweg 237 and

69 Romero y Alejandra Gran Va, Madrid 28001 Spain


tomillo Camino 1

70 Sant Jonas Erling Stavern 4110 Norway


Gourmet Bergulfsen Skakkes
gate 78

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

72 Seven Seas Hari 90 London OX15 UK


Imports Kumar Wadhurst 4NB
Rd.

73 Simons Jytte Vinbltet Kbenha 1734 Denmar


bistro Petersen 34 vn k

74 Spcialits Dominique 25, rue Paris 75016 France


du monde Perrier Lauriston

75 Split Rail Art P.O. Box Lander 82520 USA


Beer & Ale Braunschw 555
eiger

76 Suprmes Pascale Boulevard Charleroi B-6000 Belgium


dlices Cartrain Tirou, 255

77 The Big Liz Nixon 89 Portland 97201 USA


Cheese Jefferson
Way Suite
2

78 The Cracker Liu Wong 55 Grizzly Butte 59801 USA


Box Peak Rd.

79 Toms Karin Luisenstr. Mnster 44087 German


Spezialitte Josephs 48 y
n

80 Tortuga Miguel Avda. Mxico 05033 Mexico


Restaurante Angel Azteca D.F.
Paolino 123

81 Tradio Anabela Av. Ins So 05634- Brazil


Hipermerca Domingues de Castro, Paulo 030
dos 414

82 Trail's Head Helvetius 722 Kirkland 98034 USA


Gourmet Nagy DaVinci
Provisioners Blvd.

83 Vaffeljernet Palle Ibsen Smagslg rhus 8200 Denmar


et 45 k

84 Victuailles Mary 2, rue du Lyon 69004 France


en stock Saveley Commerce

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

86 Die Rita Mller Adenauera Stuttgart 70563 German


Wandernde llee 900 y
Kuh

87 Wartian Pirkko Torikatu Oulu 90110 Finland


Herkku Koskitalo 38

88 Wellington Paula Rua do Resende 08737- Brazil


Importador Parente Mercado, 363
a 12

89 White Karl 305 - 14th Seattle 98128 USA


Clover Jablonski Ave. S.
Markets Suite 3B

90 Wilman Matti Keskuskat Helsinki 21240 Finland


Kala Karttunen u 45

91 Wolski Zbyszek ul. Walla 01-012 Poland


Filtrowa
68

Click on the "Try it Yourself" button to see how it works.

Start learning SQL now!

SQL Quiz Test

Test your SQL skills at W3Schools!

Start SQL Quiz!

SQL Quick Reference

An SQL Quick Reference. Print it and put it in your pocket.

SQL Quick Reference

SQL Data Types

Data types and ranges for Microsoft Access, MySQL and SQL Server.

10
SQL Data Types

The HTML Certificate documents your knowledge of HTML.

The CSS Certificate documents your knowledge of advanced CSS.

The JavaScript Certificate documents your knowledge of JavaScript and


HTML DOM.

The jQuery Certificate documents your knowledge of jQuery.

The PHP Certificate documents your knowledge of PHP and SQL


(MySQL).

The XML Certificate documents your knowledge of XML, XML DOM and
XSLT.

The Bootstrap Certificate documents your knowledge of the Bootstrap


framework.

Introduction to SQL

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 is an ANSI (American National Standards Institute) standard

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

11
SQL is a Standard - BUT....

Although SQL is an ANSI (American National Standards Institute)


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!

Using SQL in Your Web Site

To build a web site that shows data from a database, you will need:

An RDBMS database program (i.e. MS Access, SQL Server,


MySQL)
To use a server-side scripting language, like PHP or ASP
To use SQL to get the data you want
To use HTML / CSS to style the page

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;
Number of Records: 91

Custom Customer ContactN Address City PostalC Countr


erID Name ame ode y

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

12
2 Ana Trujillo Ana Avda. de Mxico 05021 Mexico
Emparedad Trujillo la D.F.
os y Constituci
helados n 2222

3 Antonio Antonio Mataderos Mxico 05023 Mexico


Moreno Moreno 2312 D.F.
Taquera

4 Around the Thomas 120 London WA1 UK


Horn Hardy Hanover 1DP
Sq.

5 Berglunds Christina Berguvsv Lule S-958 Sweden


snabbkp Berglund gen 8 22

6 Blauer See Hanna Forsterstr. Mannhei 68306 German


Delikatesse Moos 57 m y
n

7 Blondel Frdrique 24, place Strasbou 67000 France


pre et fils Citeaux Klber rg

8 Blido Martn C/ Araquil, Madrid 28023 Spain


Comidas Sommer 67
preparadas

9 Bon app' Laurence 12, rue Marseille 13008 France


Lebihans des
Bouchers

10 Bottom- Elizabeth 23 Tsawass T2F 8M4 Canada


Dollar Lincoln Tsawassen en
Marketse Blvd.

11 B's Victoria Fauntleroy London EC2 5NT UK


Beverages Ashworth Circus

12 Cactus Patricio Cerrito Buenos 1010 Argenti


Comidas Simpson 333 Aires na
para llevar

13 Centro Francisco Sierras de Mxico 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

14 Chop-suey Yang Hauptstr. Bern 3012 Switzerl


Chinese Wang 29 and

15 Comrcio Pedro Av. dos So 05432- Brazil

13
Mineiro Afonso Lusadas, Paulo 043
23

16 Consolidate Elizabeth Berkeley London WX1 UK


d Holdings Brown Gardens 6LT
12
Brewery

17 Drachenblu Sven Walserweg Aachen 52066 German


t Ottlieb 21 y
Delikatesse
nd

18 Du monde Janine 67, rue Nantes 44000 France


entier Labrune des
Cinquante
Otages

19 Eastern Ann Devon 35 King London WX3 UK


Connection George 6FW

20 Ernst Roland Kirchgasse Graz 8010 Austria


Handel Mendel 6

21 Familia Aria Cruz Rua Ors, So 05442- Brazil


Arquibaldo 92 Paulo 030

22 FISSA Diego Roel C/ Madrid 28034 Spain


Fabrica Moralzarza
Inter. l, 86
Salchichas
S.A.

23 Folies Martine 184, Lille 59000 France


gourmande Ranc chausse
s de Tournai

24 Folk och f Maria kergatan Brcke S-844 Sweden


HB Larsson 24 67

25 Frankenver Peter Berliner Mnchen 80805 German


sand Franken Platz 43 y

26 France Carine 54, rue Nantes 44000 France


restauratio Schmitt Royale
n

27 Franchi Paolo Via Monte Torino 10100 Italy


S.p.A. Accorti Bianco 34

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

29 Galera del Eduardo Rambla de Barcelon 08022 Spain


gastrnomo Saavedra Catalua, a
23

30 Godos Jos Pedro C/ Sevilla 41101 Spain


Cocina Freyre Romero,
Tpica 33

31 Gourmet Andr Av. Brasil, Campina 04876- Brazil


Lanchonete Fonseca 442 s 786
s

32 Great Lakes Howard 2732 Eugene 97403 USA


Food Snyder Baker
Market Blvd.

33 GROSELLA- Manuel 5 Ave. Caracas 1081 Venezu


Restaurante Pereira Los Palos ela
Grandes

34 Hanari Mario Rua do Rio de 05454- Brazil


Carnes Pontes Pao, 67 Janeiro 876

35 HILARIN- Carlos Carrera 22 San 5022 Venezu


Abastos Hernndez con Ave. Cristbal ela
Carlos
Soublette
#8-35

36 Hungry Yoshi City Elgin 97827 USA


Coyote Latimer Center
Import Plaza 516
Store Main St.

37 Hungry Owl Patricia 8 Cork Ireland


All-Night McKenna Johnstown
Grocers Road

38 Island Helen Garden Cowes PO31 UK


Trading Bennett House 7PJ
Crowther
Way

39 Kniglich Philip Maubelstr. Branden 14776 German


Essen Cramer 90 burg y

15
40 La corne Daniel 67, Versaille 78000 France
d'abondanc Tonini avenue de s
e l'Europe

41 La maison Annette 1 rue Toulouse 31000 France


d'Asie Roulet Alsace-
Lorraine

42 Laughing Yoshi 1900 Oak Vancouv V3F 2K1 Canada


Bacchus Tannamuri St. er
Wine
Cellars

43 Lazy K John Steel 12 Walla 99362 USA


Kountry Orchestra Walla
Store Terrace

44 Lehmanns Renate Magazinw Frankfurt 60528 German


Marktstand Messner eg 7 a.M. y

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


Shop Yorres St. Suite 5 Francisc
o

46 LILA- Carlos Carrera 52 Barquisi 3508 Venezu


Supermerca Gonzlez con Ave. meto ela
do Bolvar
#65-98
Llano
Largo

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


Delicateses Izquierdo Mayo Margarit ela
Porlamar a

48 Lonesome Fran 89 Portland 97219 USA


Pine Wilson Chiaroscur
Restaurant o Rd.

49 Magazzini Giovanni Via Bergamo 24100 Italy


Alimentari Rovelli Ludovico il
Riuniti Moro 22

50 Maison Catherine Rue Bruxelles B-1180 Belgium


Dewey Dewey Joseph-
Bens 532

51 Mre Jean 43 rue St. Montral H1J 1C3 Canada


Paillarde Fresnire Laurent

16
52 Morgenster Alexander Heerstr. Leipzig 04179 German
n Feuer 22 y
Gesundkost

53 North/Sout Simon South London SW7 UK


h Crowther House 300 1RZ
Queensbri
dge

54 Ocano Yvonne Ing. Buenos 1010 Argenti


Atlntico Moncada Gustavo Aires na
Ltda. Moncada
8585 Piso
20-A

55 Old World Rene 2743 Anchora 99508 USA


Delicatesse Phillips Bering St. ge
n

56 Ottilies Henriette Mehrheim Kln 50739 German


Kseladen Pfalzheim erstr. 369 y

57 Paris Marie 265, Paris 75012 France


spcialits Bertrand boulevard
Charonne

58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico


Comidas Fernndez Jorge D.F.
clsicas Cash 321

59 Piccolo und Georg Geislweg Salzburg 5020 Austria


mehr Pipps 14

60 Princesa Isabel de Estrada da Lisboa 1756 Portuga


Isabel Castro sade n. l
Vinhoss 58

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificado Janeiro 673
ra, 12

62 Queen Lcia Alameda So 05487- Brazil


Cozinha Carvalho dos Paulo 020
Canrios,
891

63 QUICK-Stop Horst Taucherstr Cunewal 01307 German


Kloss ae 10 de y

64 Rancho Sergio Av. del Buenos 1010 Argenti

17
grande Gutirrez Libertador Aires na
900

65 Rattlesnake Paula 2817 Albuquer 87110 USA


Canyon Wilson Milton Dr. que
Grocery

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacaba Janeiro 890
na, 267

68 Richter Michael Grenzache Genve 1203 Switzerl


Supermarkt Holz rweg 237 and

69 Romero y Alejandra Gran Va, Madrid 28001 Spain


tomillo Camino 1

70 Sant Jonas Erling Stavern 4110 Norway


Gourmet Bergulfsen Skakkes
gate 78

71 Save-a-lot Jose 187 Boise 83720 USA


Markets Pavarotti Suffolk Ln.

72 Seven Seas Hari 90 London OX15 UK


Imports Kumar Wadhurst 4NB
Rd.

73 Simons Jytte Vinbltet Kbenha 1734 Denmar


bistro Petersen 34 vn k

74 Spcialits Dominique 25, rue Paris 75016 France


du monde Perrier Lauriston

75 Split Rail Art P.O. Box Lander 82520 USA


Beer & Ale Braunschw 555
eiger

76 Suprmes Pascale Boulevard Charleroi B-6000 Belgium


dlices Cartrain Tirou, 255

77 The Big Liz Nixon 89 Portland 97201 USA


Cheese Jefferson
Way Suite
2

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

79 Toms Karin Luisenstr. Mnster 44087 German


Spezialitte Josephs 48 y
n

80 Tortuga Miguel Avda. Mxico 05033 Mexico


Restaurante Angel Azteca D.F.
Paolino 123

81 Tradio Anabela Av. Ins So 05634- Brazil


Hipermerca Domingues de Castro, Paulo 030
dos 414

82 Trail's Head Helvetius 722 Kirkland 98034 USA


Gourmet Nagy DaVinci
Provisioners Blvd.

83 Vaffeljernet Palle Ibsen Smagslg rhus 8200 Denmar


et 45 k

84 Victuailles Mary 2, rue du Lyon 69004 France


en stock Saveley Commerce

85 Vins et Paul 59 rue de Reims 51100 France


alcools Henriot l'Abbaye
Chevalier

86 Die Rita Mller Adenauera Stuttgart 70563 German


Wandernde llee 900 y
Kuh

87 Wartian Pirkko Torikatu Oulu 90110 Finland


Herkku Koskitalo 38

88 Wellington Paula Rua do Resende 08737- Brazil


Importador Parente Mercado, 363
a 12

89 White Karl 305 - 14th Seattle 98128 USA


Clover Jablonski Ave. S.
Markets Suite 3B

90 Wilman Matti Keskuskat Helsinki 21240 Finland


Kala Karttunen u 45

91 Wolski Zbyszek ul. Walla 01-012 Poland


Filtrowa
68

19
Every table is broken up into smaller entities called fields. The fields in
the Customers table consist of CustomerID, CustomerName,
ContactName, Address, City and PostalCode. 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 tutorial 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:

CustomerI CustomerNa ContactNa Address City PostalCo Countr


D me me de y

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de la Mxic 05021 Mexico


Emparedados Constituci o D.F.

20
y helados n 2222

3 Antonio Antonio Mataderos Mxic 05023 Mexico


Moreno Moreno 2312 o D.F.
Taquera

4 Around the Thomas 120 Londo WA1 1DP UK


Horn Hardy Hanover n
Sq.

5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden


snabbkp Berglund en 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;
Number of Records: 91

Custom Customer ContactN Address City PostalC Countr


erID Name ame ode y

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Avda. de Mxico 05021 Mexico

21
Emparedad Trujillo la D.F.
os y Constituci
helados n 2222

3 Antonio Antonio Mataderos Mxico 05023 Mexico


Moreno Moreno 2312 D.F.
Taquera

4 Around the Thomas 120 London WA1 UK


Horn Hardy Hanover 1DP
Sq.

5 Berglunds Christina Berguvsv Lule S-958 Sweden


snabbkp Berglund gen 8 22

6 Blauer See Hanna Forsterstr. Mannhei 68306 German


Delikatesse Moos 57 m y
n

7 Blondel Frdrique 24, place Strasbou 67000 France


pre et fils Citeaux Klber rg

8 Blido Martn C/ Araquil, Madrid 28023 Spain


Comidas Sommer 67
preparadas

9 Bon app' Laurence 12, rue Marseille 13008 France


Lebihans des
Bouchers

10 Bottom- Elizabeth 23 Tsawass T2F 8M4 Canada


Dollar Lincoln Tsawassen en
Marketse Blvd.

11 B's Victoria Fauntleroy London EC2 5NT UK


Beverages Ashworth Circus

12 Cactus Patricio Cerrito Buenos 1010 Argenti


Comidas Simpson 333 Aires na
para llevar

13 Centro Francisco Sierras de Mxico 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

14 Chop-suey Yang Hauptstr. Bern 3012 Switzerl


Chinese Wang 29 and

15 Comrcio Pedro Av. dos So 05432- Brazil


Mineiro Afonso Lusadas, Paulo 043

22
23

16 Consolidate Elizabeth Berkeley London WX1 UK


d Holdings Brown Gardens 6LT
12
Brewery

17 Drachenblu Sven Walserweg Aachen 52066 German


t Ottlieb 21 y
Delikatesse
nd

18 Du monde Janine 67, rue Nantes 44000 France


entier Labrune des
Cinquante
Otages

19 Eastern Ann Devon 35 King London WX3 UK


Connection George 6FW

20 Ernst Roland Kirchgasse Graz 8010 Austria


Handel Mendel 6

21 Familia Aria Cruz Rua Ors, So 05442- Brazil


Arquibaldo 92 Paulo 030

22 FISSA Diego Roel C/ Madrid 28034 Spain


Fabrica Moralzarza
Inter. l, 86
Salchichas
S.A.

23 Folies Martine 184, Lille 59000 France


gourmande Ranc chausse
s de Tournai

24 Folk och f Maria kergatan Brcke S-844 Sweden


HB Larsson 24 67

25 Frankenver Peter Berliner Mnchen 80805 German


sand Franken Platz 43 y

26 France Carine 54, rue Nantes 44000 France


restauratio Schmitt Royale
n

27 Franchi Paolo Via Monte Torino 10100 Italy


S.p.A. Accorti Bianco 34

28 Furia Lino Jardim das Lisboa 1675 Portuga

23
Bacalhau e Rodriguez rosas n. l
Frutos do 32
Mar

29 Galera del Eduardo Rambla de Barcelon 08022 Spain


gastrnomo Saavedra Catalua, a
23

30 Godos Jos Pedro C/ Sevilla 41101 Spain


Cocina Freyre Romero,
Tpica 33

31 Gourmet Andr Av. Brasil, Campina 04876- Brazil


Lanchonete Fonseca 442 s 786
s

32 Great Lakes Howard 2732 Eugene 97403 USA


Food Snyder Baker
Market Blvd.

33 GROSELLA- Manuel 5 Ave. Caracas 1081 Venezu


Restaurante Pereira Los Palos ela
Grandes

34 Hanari Mario Rua do Rio de 05454- Brazil


Carnes Pontes Pao, 67 Janeiro 876

35 HILARIN- Carlos Carrera 22 San 5022 Venezu


Abastos Hernndez con Ave. Cristbal ela
Carlos
Soublette
#8-35

36 Hungry Yoshi City Elgin 97827 USA


Coyote Latimer Center
Import Plaza 516
Store Main St.

37 Hungry Owl Patricia 8 Cork Ireland


All-Night McKenna Johnstown
Grocers Road

38 Island Helen Garden Cowes PO31 UK


Trading Bennett House 7PJ
Crowther
Way

39 Kniglich Philip Maubelstr. Branden 14776 German


Essen Cramer 90 burg y

24
40 La corne Daniel 67, Versaille 78000 France
d'abondanc Tonini avenue de s
e l'Europe

41 La maison Annette 1 rue Toulouse 31000 France


d'Asie Roulet Alsace-
Lorraine

42 Laughing Yoshi 1900 Oak Vancouv V3F 2K1 Canada


Bacchus Tannamuri St. er
Wine
Cellars

43 Lazy K John Steel 12 Walla 99362 USA


Kountry Orchestra Walla
Store Terrace

44 Lehmanns Renate Magazinw Frankfurt 60528 German


Marktstand Messner eg 7 a.M. y

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


Shop Yorres St. Suite 5 Francisc
o

46 LILA- Carlos Carrera 52 Barquisi 3508 Venezu


Supermerca Gonzlez con Ave. meto ela
do Bolvar
#65-98
Llano
Largo

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


Delicateses Izquierdo Mayo Margarit ela
Porlamar a

48 Lonesome Fran 89 Portland 97219 USA


Pine Wilson Chiaroscur
Restaurant o Rd.

49 Magazzini Giovanni Via Bergamo 24100 Italy


Alimentari Rovelli Ludovico il
Riuniti Moro 22

50 Maison Catherine Rue Bruxelles B-1180 Belgium


Dewey Dewey Joseph-
Bens 532

51 Mre Jean 43 rue St. Montral H1J 1C3 Canada


Paillarde Fresnire Laurent

25
52 Morgenster Alexander Heerstr. Leipzig 04179 German
n Feuer 22 y
Gesundkost

53 North/Sout Simon South London SW7 UK


h Crowther House 300 1RZ
Queensbri
dge

54 Ocano Yvonne Ing. Buenos 1010 Argenti


Atlntico Moncada Gustavo Aires na
Ltda. Moncada
8585 Piso
20-A

55 Old World Rene 2743 Anchora 99508 USA


Delicatesse Phillips Bering St. ge
n

56 Ottilies Henriette Mehrheim Kln 50739 German


Kseladen Pfalzheim erstr. 369 y

57 Paris Marie 265, Paris 75012 France


spcialits Bertrand boulevard
Charonne

58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico


Comidas Fernndez Jorge D.F.
clsicas Cash 321

59 Piccolo und Georg Geislweg Salzburg 5020 Austria


mehr Pipps 14

60 Princesa Isabel de Estrada da Lisboa 1756 Portuga


Isabel Castro sade n. l
Vinhoss 58

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificado Janeiro 673
ra, 12

62 Queen Lcia Alameda So 05487- Brazil


Cozinha Carvalho dos Paulo 020
Canrios,
891

63 QUICK-Stop Horst Taucherstr Cunewal 01307 German


Kloss ae 10 de y

64 Rancho Sergio Av. del Buenos 1010 Argenti

26
grande Gutirrez Libertador Aires na
900

65 Rattlesnake Paula 2817 Albuquer 87110 USA


Canyon Wilson Milton Dr. que
Grocery

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacaba Janeiro 890
na, 267

68 Richter Michael Grenzache Genve 1203 Switzerl


Supermarkt Holz rweg 237 and

69 Romero y Alejandra Gran Va, Madrid 28001 Spain


tomillo Camino 1

70 Sant Jonas Erling Stavern 4110 Norway


Gourmet Bergulfsen Skakkes
gate 78

71 Save-a-lot Jose 187 Boise 83720 USA


Markets Pavarotti Suffolk Ln.

72 Seven Seas Hari 90 London OX15 UK


Imports Kumar Wadhurst 4NB
Rd.

73 Simons Jytte Vinbltet Kbenha 1734 Denmar


bistro Petersen 34 vn k

74 Spcialits Dominique 25, rue Paris 75016 France


du monde Perrier Lauriston

75 Split Rail Art P.O. Box Lander 82520 USA


Beer & Ale Braunschw 555
eiger

76 Suprmes Pascale Boulevard Charleroi B-6000 Belgium


dlices Cartrain Tirou, 255

77 The Big Liz Nixon 89 Portland 97201 USA


Cheese Jefferson
Way Suite
2

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

79 Toms Karin Luisenstr. Mnster 44087 German


Spezialitte Josephs 48 y
n

80 Tortuga Miguel Avda. Mxico 05033 Mexico


Restaurante Angel Azteca D.F.
Paolino 123

81 Tradio Anabela Av. Ins So 05634- Brazil


Hipermerca Domingues de Castro, Paulo 030
dos 414

82 Trail's Head Helvetius 722 Kirkland 98034 USA


Gourmet Nagy DaVinci
Provisioners Blvd.

83 Vaffeljernet Palle Ibsen Smagslg rhus 8200 Denmar


et 45 k

84 Victuailles Mary 2, rue du Lyon 69004 France


en stock Saveley Commerce

85 Vins et Paul 59 rue de Reims 51100 France


alcools Henriot l'Abbaye
Chevalier

86 Die Rita Mller Adenauera Stuttgart 70563 German


Wandernde llee 900 y
Kuh

87 Wartian Pirkko Torikatu Oulu 90110 Finland


Herkku Koskitalo 38

88 Wellington Paula Rua do Resende 08737- Brazil


Importador Parente Mercado, 363
a 12

89 White Karl 305 - 14th Seattle 98128 USA


Clover Jablonski Ave. S.
Markets Suite 3B

90 Wilman Matti Keskuskat Helsinki 21240 Finland


Kala Karttunen u 45

91 Wolski Zbyszek ul. Walla 01-012 Poland


Filtrowa
68

28
In this tutorial we will teach you all about the different SQL statements.

Keep in Mind That...

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


SELECT

In this tutorial 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 tutorial, we will use semicolon at the end of each SQL statement.

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.

29
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:

CustomerI CustomerNa ContactNa Address City PostalCo Countr


D me me de y

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de la Mxic 05021 Mexico


Emparedados Constituci o D.F.
y helados n 2222

3 Antonio Antonio Mataderos Mxic 05023 Mexico


Moreno Moreno 2312 o D.F.
Taquera

4 Around the Thomas 120 Londo WA1 1DP UK


Horn Hardy Hanover n
Sq.

30
5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden
snabbkp Berglund en 8

SELECT Column Example

The following SQL statement selects the "CustomerName" and "City"


columns from the "Customers" table:

SQL Statement:
Example

SELECT CustomerName, City FROM Customers;

CustomerName City

Alfreds Futterkiste Berlin

Ana Trujillo Emparedados y helados Mxico D.F.

Antonio Moreno Taquera Mxico D.F.

Around the Horn London

Berglunds snabbkp Lule

Blauer See Delikatessen Mannheim

Blondel pre et fils Strasbourg

Blido Comidas preparadas Madrid

Bon app' Marseille

Bottom-Dollar Marketse Tsawassen

B's Beverages London

Cactus Comidas para llevar Buenos Aires

Centro comercial Moctezuma Mxico D.F.

Chop-suey Chinese Bern

31
Comrcio Mineiro So Paulo

Consolidated Holdings London

Drachenblut Delikatessend Aachen

Du monde entier Nantes

Eastern Connection London

Ernst Handel Graz

Familia Arquibaldo So Paulo

FISSA Fabrica Inter. Salchichas S.A. Madrid

Folies gourmandes Lille

Folk och f HB Brcke

Frankenversand Mnchen

France restauration Nantes

Franchi S.p.A. Torino

Furia Bacalhau e Frutos do Mar Lisboa

Galera del gastrnomo Barcelona

Godos Cocina Tpica Sevilla

Gourmet Lanchonetes Campinas

Great Lakes Food Market Eugene

GROSELLA-Restaurante Caracas

Hanari Carnes Rio de Janeiro

HILARIN-Abastos San Cristbal

Hungry Coyote Import Store Elgin

Hungry Owl All-Night Grocers Cork

Island Trading Cowes

Kniglich Essen Brandenburg

La corne d'abondance Versailles

32
La maison d'Asie Toulouse

Laughing Bacchus Wine Cellars Vancouver

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

Mre Paillarde Montral

Morgenstern Gesundkost Leipzig

North/South London

Ocano Atlntico Ltda. Buenos Aires

Old World Delicatessen Anchorage

Ottilies Kseladen Kln

Paris spcialits Paris

Pericles Comidas clsicas Mxico D.F.

Piccolo und mehr Salzburg

Princesa Isabel Vinhoss Lisboa

Que Delcia Rio de Janeiro

Queen Cozinha So Paulo

QUICK-Stop Cunewalde

Rancho grande Buenos Aires

Rattlesnake Canyon Grocery Albuquerque

Reggiani Caseifici Reggio Emilia

33
Ricardo Adocicados Rio de Janeiro

Richter Supermarkt Genve

Romero y tomillo Madrid

Sant Gourmet Stavern

Save-a-lot Markets Boise

Seven Seas Imports London

Simons bistro Kbenhavn

Spcialits du monde Paris

Split Rail Beer & Ale Lander

Suprmes dlices Charleroi

The Big Cheese Portland

The Cracker Box Butte

Toms Spezialitten Mnster

Tortuga Restaurante Mxico D.F.

Tradio Hipermercados So 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

34
SELECT * Example

The following SQL statement selects all the columns from the
"Customers" table:

Example

SELECT * FROM Customers;

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
Number of Records: 91

Custome CustomerN ContactNa Address City PostalC Country


rID ame me ode

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico


Emparedado Constituci D.F.
s y helados n 2222

3 Antonio Antonio Mataderos Mxico 05023 Mexico


Moreno Moreno 2312 D.F.
Taquera

4 Around the Thomas 120 London WA1 UK


Horn Hardy Hanover 1DP
Sq.

5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden


snabbkp Berglund en 8

6 Blauer See Hanna Forsterstr. Mannhei 68306 German


Delikatessen Moos 57 m y

7 Blondel pre Frdrique 24, place Strasbour 67000 France


et fils Citeaux Klber g

8 Blido Martn C/ Araquil, Madrid 28023 Spain


Comidas Sommer 67
preparadas

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

35
Lebihans Bouchers

10 Bottom- Elizabeth 23 Tsawasse T2F Canada


Dollar Lincoln Tsawassen n 8M4
Marketse Blvd.

11 B's Victoria Fauntleroy London EC2 UK


Beverages Ashworth Circus 5NT

12 Cactus Patricio Cerrito 333 Buenos 1010 Argentin


Comidas Simpson Aires a
para llevar

13 Centro Francisco Sierras de Mxico 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

14 Chop-suey Yang Wang Hauptstr. Bern 3012 Switzerl


Chinese 29 and

15 Comrcio Pedro Av. dos So Paulo 05432- Brazil


Mineiro Afonso Lusadas, 043
23

16 Consolidate Elizabeth Berkeley London WX1 UK


d Holdings Brown Gardens 12 6LT
Brewery

17 Drachenblut Sven Ottlieb Walserweg Aachen 52066 German


Delikatessen 21 y
d

18 Du monde Janine 67, rue des Nantes 44000 France


entier Labrune Cinquante
Otages

19 Eastern Ann Devon 35 King London WX3 UK


Connection George 6FW

20 Ernst Roland Kirchgasse Graz 8010 Austria


Handel Mendel 6

21 Familia Aria Cruz Rua Ors, So Paulo 05442- Brazil


Arquibaldo 92 030

22 FISSA Diego Roel C/ Madrid 28034 Spain


Fabrica Moralzarzal

36
Inter. , 86
Salchichas
S.A.

23 Folies Martine 184, Lille 59000 France


gourmandes Ranc chausse de
Tournai

24 Folk och f Maria kergatan Brcke S-844 67 Sweden


HB Larsson 24

25 Frankenvers Peter Berliner Mnchen 80805 German


and Franken Platz 43 y

26 France Carine 54, rue Nantes 44000 France


restauration Schmitt Royale

27 Franchi Paolo Via Monte Torino 10100 Italy


S.p.A. Accorti Bianco 34

28 Furia Lino Jardim das Lisboa 1675 Portugal


Bacalhau e Rodriguez rosas n. 32
Frutos do
Mar

29 Galera del Eduardo Rambla de Barcelona 08022 Spain


gastrnomo Saavedra Catalua,
23

30 Godos Jos Pedro C/ Romero, Sevilla 41101 Spain


Cocina Freyre 33
Tpica

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.

33 GROSELL Manuel 5 Ave. Los Caracas 1081 Venezue


A- Pereira Palos la
Restaurante Grandes

34 Hanari Mario Rua do Rio de 05454- Brazil


Carnes Pontes Pao, 67 Janeiro 876

35 HILARIN- Carlos Carrera 22 San 5022 Venezue

37
Abastos Hernndez con Ave. Cristbal la
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 Cork Ireland


All-Night McKenna Johnstown
Grocers Road

38 Island Helen Garden Cowes PO31 UK


Trading Bennett House 7PJ
Crowther
Way

39 Kniglich Philip Maubelstr. Brandenb 14776 German


Essen Cramer 90 urg y

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

42 Laughing Yoshi 1900 Oak Vancouve V3F Canada


Bacchus Tannamuri St. r 2K1
Wine
Cellars

43 Lazy K John Steel 12 Walla 99362 USA


Kountry Orchestra Walla
Store Terrace

44 Lehmanns Renate Magazinwe Frankfurt 60528 German


Marktstand Messner g7 a.M. y

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


Shop Yorres Suite 5 Francisco

46 LILA- Carlos Carrera 52 Barquisim 3508 Venezue


Supermerca Gonzlez con Ave. eto la
do Bolvar
#65-98

38
Llano
Largo

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


Delicateses Izquierdo Mayo Margarita la
Porlamar

48 Lonesome Fran Wilson 89 Portland 97219 USA


Pine Chiaroscur
Restaurant o Rd.

49 Magazzini Giovanni Via Bergamo 24100 Italy


Alimentari Rovelli Ludovico il
Riuniti Moro 22

50 Maison Catherine Rue Bruxelles B-1180 Belgium


Dewey Dewey Joseph-
Bens 532

51 Mre Jean 43 rue St. Montral H1J 1C3 Canada


Paillarde Fresnire Laurent

52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 German


Gesundkost Feuer y

53 North/South Simon South London SW7 UK


Crowther House 300 1RZ
Queensbrid
ge

54 Ocano Yvonne Ing. Buenos 1010 Argentin


Atlntico Moncada Gustavo Aires a
Ltda. Moncada
8585 Piso
20-A

55 Old World Rene 2743 Anchorag 99508 USA


Delicatessen Phillips Bering St. e

56 Ottilies Henriette Mehrheime Kln 50739 German


Kseladen Pfalzheim rstr. 369 y

57 Paris Marie 265, Paris 75012 France


spcialits Bertrand boulevard
Charonne

58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico

39
Comidas Fernndez Jorge Cash D.F.
clsicas 321

59 Piccolo und Georg Pipps Geislweg Salzburg 5020 Austria


mehr 14

60 Princesa Isabel de Estrada da Lisboa 1756 Portugal


Isabel Castro sade n. 58
Vinhoss

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificador Janeiro 673
a, 12

62 Queen Lcia Alameda So Paulo 05487- Brazil


Cozinha Carvalho dos 020
Canrios,
891

63 QUICK- Horst Kloss Taucherstra Cunewald 01307 German


Stop e 10 e y

64 Rancho Sergio Av. del Buenos 1010 Argentin


grande Gutirrez Libertador Aires a
900

65 Rattlesnake Paula 2817 Albuquer 87110 USA


Canyon Wilson Milton Dr. que
Grocery

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacaban Janeiro 890
a, 267

68 Richter Michael Grenzacher Genve 1203 Switzerl


Supermarkt Holz weg 237 and

69 Romero y Alejandra Gran Va, 1 Madrid 28001 Spain


tomillo Camino

70 Sant Jonas Erling Stavern 4110 Norway


Gourmet Bergulfsen Skakkes
gate 78

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

72 Seven Seas Hari Kumar 90 London OX15 UK


Imports Wadhurst 4NB
Rd.

73 Simons Jytte Vinbltet Kbenhav 1734 Denmar


bistro Petersen 34 n k

74 Spcialits Dominique 25, rue Paris 75016 France


du monde Perrier Lauriston

75 Split Rail Art P.O. Box Lander 82520 USA


Beer & Ale Braunschwe 555
iger

76 Suprmes Pascale Boulevard Charleroi B-6000 Belgium


dlices Cartrain Tirou, 255

77 The Big Liz Nixon 89 Portland 97201 USA


Cheese Jefferson
Way Suite
2

78 The Cracker Liu Wong 55 Grizzly Butte 59801 USA


Box Peak Rd.

79 Toms Karin Luisenstr. Mnster 44087 German


Spezialitten Josephs 48 y

80 Tortuga Miguel Avda. Mxico 05033 Mexico


Restaurante Angel Azteca 123 D.F.
Paolino

81 Tradio Anabela Av. Ins de So Paulo 05634- Brazil


Hipermerca Domingues Castro, 414 030
dos

82 Trail's Head Helvetius 722 Kirkland 98034 USA


Gourmet Nagy DaVinci
Provisioners Blvd.

83 Vaffeljernet Palle Ibsen Smagslget rhus 8200 Denmar


45 k

84 Victuailles Mary 2, rue du Lyon 69004 France

41
en stock Saveley Commerce

85 Vins et Paul 59 rue de Reims 51100 France


alcools Henriot l'Abbaye
Chevalier

86 Die Rita Mller Adenaueral Stuttgart 70563 German


Wandernde lee 900 y
Kuh

87 Wartian Pirkko Torikatu 38 Oulu 90110 Finland


Herkku Koskitalo

88 Wellington Paula Rua do Resende 08737- Brazil


Importadora Parente Mercado, 363
12

89 White Karl 305 - 14th Seattle 98128 USA


Clover Jablonski Ave. S.
Markets Suite 3B

90 Wilman Matti Keskuskatu Helsinki 21240 Finland


Kala Karttunen 45

91 Wolski Zbyszek ul. Filtrowa Walla 01-012


68

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.

The SELECT DISTINCT statement is used to return only distinct


(different) values.

SELECT DISTINCT Syntax


SELECT DISTINCT column1, column2, ...
FROM table_name;

42
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 Mxico 05021 Mexico


Emparedados y Constitucin D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico


Taquera Moreno 2312 D.F.

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

5 Berglunds Christina Berguvsvgen Lule S-958 22 Sweden


snabbkp Berglund 8

SELECT Example

The following SQL statement selects all (and duplicate) values from the
"City" columns in the "Customers" table:

SQL Statement:
SELECT City FROM Customers;

Edit the SQL Statement, and click "Run SQL" to see the result.

43
Run SQL
Result:
Number of Records: 91

City

Berlin

Mxico D.F.

Mxico D.F.

London

Lule

Mannheim

Strasbourg

Madrid

Marseille

Tsawassen

London

Buenos Aires

Mxico D.F.

Bern

So Paulo

London

Aachen

Nantes

London

Graz

So Paulo

44
Madrid

Lille

Brcke

Mnchen

Nantes

Torino

Lisboa

Barcelona

Sevilla

Campinas

Eugene

Caracas

Rio de Janeiro

San Cristbal

Elgin

Cork

Cowes

Brandenburg

Versailles

Toulouse

Vancouver

Walla Walla

Frankfurt a.M.

San Francisco

Barquisimeto

45
I. de Margarita

Portland

Bergamo

Bruxelles

Montral

Leipzig

London

Buenos Aires

Anchorage

Kln

Paris

Mxico D.F.

Salzburg

Lisboa

Rio de Janeiro

So Paulo

Cunewalde

Buenos Aires

Albuquerque

Reggio Emilia

Rio de Janeiro

Genve

Madrid

Stavern

Boise

46
London

Kbenhavn

Paris

Lander

Charleroi

Portland

Butte

Mnster

Mxico D.F.

So Paulo

Kirkland

rhus

Lyon

Reims

Stuttgart

Oulu

Resende

Seattle

Helsinki

Walla

Now, let us use the DISTINCT keyword with the above SELECT
statement and see the result.

SELECT DISTINCT Example

47
The following SQL statement selects only the DISTINCT values from the
"City" columns in the "Customers" table:

Example
SQL Statement:
SELECT DISTINCT City FROM Customers;

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
Number of Records: 69

City

Berlin

Mxico D.F.

London

Lule

Mannheim

Strasbourg

Madrid

Marseille

Tsawassen

Buenos Aires

Bern

So Paulo

Aachen

Nantes

Graz

Lille

48
Brcke

Mnchen

Torino

Lisboa

Barcelona

Sevilla

Campinas

Eugene

Caracas

Rio de Janeiro

San Cristbal

Elgin

Cork

Cowes

Brandenburg

Versailles

Toulouse

Vancouver

Walla Walla

Frankfurt a.M.

San Francisco

Barquisimeto

I. de Margarita

Portland

Bergamo

49
Bruxelles

Montral

Leipzig

Anchorage

Kln

Paris

Salzburg

Cunewalde

Albuquerque

Reggio Emilia

Genve

Stavern

Boise

Kbenhavn

Lander

Charleroi

Butte

Mnster

Kirkland

rhus

Lyon

Reims

Stuttgart

Oulu

Resende

50
Seattle

Helsinki

Walla

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

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 Mxico 05021 Mexico


Emparedados y Constitucin

51
helados 2222 D.F.

3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico


Taquera Moreno 2312 D.F.

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

5 Berglunds Christina Berguvsvgen Lule S-958 22 Sweden


snabbkp Berglund 8

WHERE Clause Example

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

Example

SQL Statement:
SELECT * FROM Customers
WHERE Country='Mexico';

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
Number of Records: 5

CustomerID CustomerName ContactName Address City PostalCode Country

2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico


Emparedados y Constitucin D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico


Taquera Moreno 2312 D.F.

13 Centro Francisco Sierras de Mxico 05022 Mexico

52
comercial Chang Granada D.F.
Moctezuma 9993

58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico


Comidas Fernndez Jorge Cash D.F.
clsicas 321

80 Tortuga Miguel Angel Avda. Mxico 05033 Mexico


Restaurante 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

SQL Statement:
SELECT * FROM Customers
WHERE CustomerID=1;

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
Number of Records: 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

53
= Equal

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

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

BETWEEN Between an inclusive range

LIKE Search for a pattern

IN To specify multiple possible values for a column

The SQL AND and OR 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 is TRUE.

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

The OR operator displays a record if any of the conditions separated by


OR is TRUE.

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

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 Mxico 05021 Mexico


Emparedados y Constitucin D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico


Taquera Moreno 2312 D.F.

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

55
5 Berglunds Christina Berguvsvgen Lule S-958 22 Sweden
snabbkp Berglund 8

AND Operator Example

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

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

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
Number of Records: 1

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Berlin 12209 Germany


Futterkiste Str. 57

OR Operator Example

The following SQL statement selects all fields from the "Customers"
table where city is "Berlin" OR "Mnchen":

SQL Statement:
SELECT * FROM Customers
WHERE City='Berlin' OR City='Mnchen';

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
Number of Records: 2

CustomerID CustomerName ContactName Address City PostalCode Country

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

25 Frankenversand Peter Franken Berliner Mnchen 80805 Germany


Platz 43

Combining AND and OR

You can also combine the AND and OR operators.

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

SQL Statement:
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='Mnchen');

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
Number of Records: 2

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Berlin 12209 Germany


Futterkiste Str. 57

25 Frankenversand Peter Franken Berliner Mnchen 80805 Germany


Platz 43

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

57
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

2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico


Emparedados y Constitucin D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico


Taquera Moreno 2312 D.F.

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

5 Berglunds Christina Berguvsvgen Lule S-958 22 Sweden


snabbkp Berglund 8

ORDER BY Example

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

58
Example
SQL Statement:
SELECT * FROM Customers
ORDER BY Country;

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
Number of Records: 91

Custome CustomerN ContactNa Address City PostalC Country


rID ame me ode

12 Cactus Patricio Cerrito 333 Buenos 1010 Argentin


Comidas Simpson Aires a
para llevar

54 Ocano Yvonne Ing. Buenos 1010 Argentin


Atlntico Moncada Gustavo Aires a
Ltda. Moncada
8585 Piso
20-A

64 Rancho Sergio Av. del Buenos 1010 Argentin


grande Gutirrez Libertador Aires a
900

20 Ernst Roland Kirchgasse Graz 8010 Austria


Handel Mendel 6

59 Piccolo und Georg Pipps Geislweg Salzburg 5020 Austria


mehr 14

50 Maison Catherine Rue Bruxelles B-1180 Belgium


Dewey Dewey Joseph-
Bens 532

76 Suprmes Pascale Boulevard Charleroi B-6000 Belgium


dlices Cartrain Tirou, 255

15 Comrcio Pedro Av. dos So Paulo 05432- Brazil


Mineiro Afonso Lusadas, 043
23

21 Familia Aria Cruz Rua Ors, So Paulo 05442- Brazil

59
Arquibaldo 92 030

31 Gourmet Andr Av. Brasil, Campinas 04876- Brazil


Lanchonetes Fonseca 442 786

34 Hanari Mario Rua do Rio de 05454- Brazil


Carnes Pontes Pao, 67 Janeiro 876

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificador Janeiro 673
a, 12

62 Queen Lcia Alameda So Paulo 05487- Brazil


Cozinha Carvalho dos 020
Canrios,
891

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacaban Janeiro 890
a, 267

81 Tradio Anabela Av. Ins de So Paulo 05634- Brazil


Hipermerca Domingues Castro, 414 030
dos

88 Wellington Paula Rua do Resende 08737- Brazil


Importadora Parente Mercado, 363
12

10 Bottom- Elizabeth 23 Tsawasse T2F Canada


Dollar Lincoln Tsawassen n 8M4
Marketse Blvd.

42 Laughing Yoshi 1900 Oak Vancouve V3F Canada


Bacchus Tannamuri St. r 2K1
Wine
Cellars

51 Mre Jean 43 rue St. Montral H1J 1C3 Canada


Paillarde Fresnire Laurent

73 Simons Jytte Vinbltet Kbenhav 1734 Denmar


bistro Petersen 34 n k

83 Vaffeljernet Palle Ibsen Smagslget rhus 8200 Denmar


45 k

60
87 Wartian Pirkko Torikatu 38 Oulu 90110 Finland
Herkku Koskitalo

90 Wilman Matti Keskuskatu Helsinki 21240 Finland


Kala Karttunen 45

7 Blondel pre Frdrique 24, place Strasbour 67000 France


et fils Citeaux Klber g

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


Lebihans Bouchers

18 Du monde Janine 67, rue des Nantes 44000 France


entier Labrune Cinquante
Otages

23 Folies Martine 184, Lille 59000 France


gourmandes Ranc chausse de
Tournai

26 France Carine 54, rue Nantes 44000 France


restauration Schmitt Royale

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

57 Paris Marie 265, Paris 75012 France


spcialits Bertrand boulevard
Charonne

74 Spcialits Dominique 25, rue Paris 75016 France


du monde Perrier Lauriston

84 Victuailles Mary 2, rue du Lyon 69004 France


en stock Saveley Commerce

85 Vins et Paul 59 rue de Reims 51100 France


alcools Henriot l'Abbaye
Chevalier

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

61
6 Blauer See Hanna Forsterstr. Mannhei 68306 German
Delikatessen Moos 57 m y

17 Drachenblut Sven Ottlieb Walserweg Aachen 52066 German


Delikatessen 21 y
d

25 Frankenvers Peter Berliner Mnchen 80805 German


and Franken Platz 43 y

39 Kniglich Philip Maubelstr. Brandenb 14776 German


Essen Cramer 90 urg y

44 Lehmanns Renate Magazinwe Frankfurt 60528 German


Marktstand Messner g7 a.M. y

52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 German


Gesundkost Feuer y

56 Ottilies Henriette Mehrheime Kln 50739 German


Kseladen Pfalzheim rstr. 369 y

63 QUICK- Horst Kloss Taucherstra Cunewald 01307 German


Stop e 10 e y

79 Toms Karin Luisenstr. Mnster 44087 German


Spezialitten Josephs 48 y

86 Die Rita Mller Adenaueral Stuttgart 70563 German


Wandernde lee 900 y
Kuh

37 Hungry Owl Patricia 8 Cork Ireland


All-Night McKenna Johnstown
Grocers Road

27 Franchi Paolo Via Monte Torino 10100 Italy


S.p.A. Accorti Bianco 34

49 Magazzini Giovanni Via Bergamo 24100 Italy


Alimentari Rovelli Ludovico il
Riuniti Moro 22

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

62
2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico
Emparedado Constituci D.F.
s y helados n 2222

3 Antonio Antonio Mataderos Mxico 05023 Mexico


Moreno Moreno 2312 D.F.
Taquera

13 Centro Francisco Sierras de Mxico 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico


Comidas Fernndez Jorge Cash D.F.
clsicas 321

80 Tortuga Miguel Avda. Mxico 05033 Mexico


Restaurante Angel Azteca 123 D.F.
Paolino

70 Sant Jonas Erling Stavern 4110 Norway


Gourmet Bergulfsen Skakkes
gate 78

91 Wolski Zbyszek ul. Filtrowa Walla 01-012 Poland


68

28 Furia Lino Jardim das Lisboa 1675 Portugal


Bacalhau e Rodriguez rosas n. 32
Frutos do
Mar

60 Princesa Isabel de Estrada da Lisboa 1756 Portugal


Isabel Castro sade n. 58
Vinhoss

8 Blido Martn C/ Araquil, Madrid 28023 Spain


Comidas Sommer 67
preparadas

22 FISSA Diego Roel C/ Madrid 28034 Spain


Fabrica Moralzarzal
Inter. , 86
Salchichas
S.A.

29 Galera del Eduardo Rambla de Barcelona 08022 Spain

63
gastrnomo Saavedra Catalua,
23

30 Godos Jos Pedro C/ Romero, Sevilla 41101 Spain


Cocina Freyre 33
Tpica

69 Romero y Alejandra Gran Va, 1 Madrid 28001 Spain


tomillo Camino

5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden


snabbkp Berglund en 8

24 Folk och f Maria kergatan Brcke S-844 67 Sweden


HB Larsson 24

14 Chop-suey Yang Wang Hauptstr. Bern 3012 Switzerl


Chinese 29 and

68 Richter Michael Grenzacher Genve 1203 Switzerl


Supermarkt Holz weg 237 and

4 Around the Thomas 120 London WA1 UK


Horn Hardy Hanover 1DP
Sq.

11 B's Victoria Fauntleroy London EC2 UK


Beverages Ashworth Circus 5NT

16 Consolidate Elizabeth Berkeley London WX1 UK


d Holdings Brown Gardens 12 6LT
Brewery

19 Eastern Ann Devon 35 King London WX3 UK


Connection George 6FW

38 Island Helen Garden Cowes PO31 UK


Trading Bennett House 7PJ
Crowther
Way

53 North/South Simon South London SW7 UK


Crowther House 300 1RZ
Queensbrid
ge

72 Seven Seas Hari Kumar 90 London OX15 UK

64
Imports Wadhurst 4NB
Rd.

32 Great Lakes Howard 2732 Baker Eugene 97403 USA


Food Market Snyder Blvd.

36 Hungry Yoshi City Center Elgin 97827 USA


Coyote Latimer Plaza 516
Import Store Main St.

43 Lazy K John Steel 12 Walla 99362 USA


Kountry Orchestra Walla
Store Terrace

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


Shop Yorres Suite 5 Francisco

48 Lonesome Fran Wilson 89 Portland 97219 USA


Pine Chiaroscur
Restaurant o Rd.

55 Old World Rene 2743 Anchorag 99508 USA


Delicatessen Phillips Bering St. e

65 Rattlesnake Paula 2817 Albuquer 87110 USA


Canyon Wilson Milton Dr. que
Grocery

71 Save-a-lot Jose 187 Suffolk Boise 83720 USA


Markets Pavarotti Ln.

75 Split Rail Art P.O. Box Lander 82520 USA


Beer & Ale Braunschwe 555
iger

77 The Big Liz Nixon 89 Portland 97201 USA


Cheese Jefferson
Way Suite
2

78 The Cracker Liu Wong 55 Grizzly Butte 59801 USA


Box Peak Rd.

82 Trail's Head Helvetius 722 Kirkland 98034 USA


Gourmet Nagy DaVinci
Provisioners Blvd.

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

33 GROSELL Manuel 5 Ave. Los Caracas 1081 Venezue


A- Pereira Palos la
Restaurante Grandes

35 HILARIN- Carlos Carrera 22 San 5022 Venezue


Abastos Hernndez con Ave. Cristbal la
Carlos
Soublette
#8-35

46 LILA- Carlos Carrera 52 Barquisim 3508 Venezue


Supermerca Gonzlez con Ave. eto la
do Bolvar
#65-98
Llano
Largo

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


Delicatese Izquierdo Mayo Margari
s Porlamar ta

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;

Number of Records: 91

Custome CustomerN ContactNa Address City PostalCo Country


rID ame me de

33 GROSELLA- Manuel 5 Ave. Los Caracas 1081 Venezue


Restaurante Pereira Palos la
Grandes

66
35 HILARIN- Carlos Carrera 22 San 5022 Venezue
Abastos Hernndez con Ave. Cristbal la
Carlos
Soublette
#8-35

46 LILA- Carlos Carrera 52 Barquisim 3508 Venezue


Supermerca Gonzlez con Ave. eto la
do Bolvar #65-
98 Llano
Largo

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


Delicateses Izquierdo Mayo Margarita la
Porlamar

32 Great Lakes Howard 2732 Baker Eugene 97403 USA


Food Snyder Blvd.
Market

36 Hungry Yoshi City Center Elgin 97827 USA


Coyote Latimer Plaza 516
Import Main St.
Store

43 Lazy K John Steel 12 Walla 99362 USA


Kountry Orchestra Walla
Store Terrace

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


Shop Yorres Suite 5 Francisco

48 Lonesome Fran Wilson 89 Portland 97219 USA


Pine Chiaroscuro
Restaurant Rd.

67
55 Old World Rene 2743 Bering Anchorag 99508 USA
Delicatessen Phillips St. e

65 Rattlesnake Paula 2817 Milton Albuquer 87110 USA


Canyon Wilson Dr. que
Grocery

71 Save-a-lot Jose 187 Suffolk Boise 83720 USA


Markets Pavarotti Ln.

75 Split Rail Art P.O. Box Lander 82520 USA


Beer & Ale Braunschwe 555
iger

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.

82 Trail's Head Helvetius 722 DaVinci Kirkland 98034 USA


Gourmet Nagy Blvd.
Provisioners

89 White Karl 305 - 14th Seattle 98128 USA


Clover Jablonski Ave. S. Suite
Markets 3B

4 Around the Thomas 120 London WA1 UK


Horn Hardy Hanover Sq. 1DP

11 B's Victoria Fauntleroy London EC2 5NT UK


Beverages Ashworth Circus

68
16 Consolidate Elizabeth Berkeley London WX1 6LT UK
d Holdings Brown Gardens 12
Brewery

19 Eastern Ann Devon 35 King London WX3 UK


Connection George 6FW

38 Island Helen Garden Cowes PO31 UK


Trading Bennett House 7PJ
Crowther
Way

53 North/Sout Simon South London SW7 1RZ UK


h Crowther House 300
Queensbrid
ge

72 Seven Seas Hari Kumar 90 London OX15 UK


Imports Wadhurst 4NB
Rd.

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


Chinese nd

68 Richter Michael Grenzacher Genve 1203 Switzerla


Supermarkt Holz weg 237 nd

5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden


snabbkp Berglund en 8

24 Folk och f Maria kergatan Brcke S-844 67 Sweden


HB Larsson 24

8 Blido Martn C/ Araquil, Madrid 28023 Spain


Comidas

69
preparadas Sommer 67

22 FISSA Diego Roel C/ Madrid 28034 Spain


Fabrica Moralzarzal,
Inter. 86
Salchichas
S.A.

29 Galera del Eduardo Rambla de Barcelona 08022 Spain


gastrnomo Saavedra Catalua,
23

30 Godos Jos Pedro C/ Romero, Sevilla 41101 Spain


Cocina Freyre 33
Tpica

69 Romero y Alejandra Gran Va, 1 Madrid 28001 Spain


tomillo Camino

28 Furia Lino Jardim das Lisboa 1675 Portugal


Bacalhau e Rodriguez rosas n. 32
Frutos do
Mar

60 Princesa Isabel de Estrada da Lisboa 1756 Portugal


Isabel Castro sade n. 58
Vinhoss

91 Wolski Zbyszek ul. Filtrowa Walla 01-012 Poland


68

70 Sant Jonas Erling Stavern 4110 Norway


Gourmet Bergulfsen Skakkes
gate 78

70
2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico
Emparedad Constituci D.F.
os y helados n 2222

3 Antonio Antonio Mataderos Mxico 05023 Mexico


Moreno Moreno 2312 D.F.
Taquera

13 Centro Francisco Sierras de Mxico 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico


Comidas Fernndez Jorge Cash D.F.
clsicas 321

80 Tortuga Miguel Avda. Mxico 05033 Mexico


Restaurante Angel Azteca 123 D.F.
Paolino

27 Franchi Paolo Via Monte Torino 10100 Italy


S.p.A. Accorti Bianco 34

49 Magazzini Giovanni Via Bergamo 24100 Italy


Alimentari Rovelli Ludovico il
Riuniti Moro 22

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

37 Hungry Owl Patricia 8 Cork Ireland


All-Night McKenna Johnstown
Grocers Road

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

6 Blauer See Hanna Forsterstr. Mannhei 68306 German


Delikatesse Moos 57 m y
n

17 Drachenblut Sven Ottlieb Walserweg Aachen 52066 German


Delikatesse 21 y
nd

25 Frankenvers Peter Berliner Mnchen 80805 German


and Franken Platz 43 y

39 Kniglich Philip Maubelstr. Brandenb 14776 German


Essen Cramer 90 urg y

44 Lehmanns Renate Magazinwe Frankfurt 60528 German


Marktstand Messner g7 a.M. y

52 Morgenster Alexander Heerstr. 22 Leipzig 04179 German


n Feuer y
Gesundkost

56 Ottilies Henriette Mehrheime Kln 50739 German


Kseladen Pfalzheim rstr. 369 y

63 QUICK-Stop Horst Kloss Taucherstra Cunewald 01307 German


e 10 e y

79 Toms Karin Luisenstr. Mnster 44087 German


Spezialitte Josephs 48 y
n

72
86 Die Rita Mller Adenauerall Stuttgart 70563 German
Wandernde ee 900 y
Kuh

7 Blondel Frdrique 24, place Strasbour 67000 France


pre et fils Citeaux Klber g

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


Lebihans Bouchers

18 Du monde Janine 67, rue des Nantes 44000 France


entier Labrune Cinquante
Otages

23 Folies Martine 184, Lille 59000 France


gourmandes Ranc chausse de
Tournai

26 France Carine 54, rue Nantes 44000 France


restauration Schmitt Royale

40 La corne Daniel 67, avenue Versailles 78000 France


d'abondanc Tonini de l'Europe
e

41 La maison Annette 1 rue Toulouse 31000 France


d'Asie Roulet Alsace-
Lorraine

57 Paris Marie 265, Paris 75012 France


spcialits Bertrand boulevard
Charonne

74 Spcialits Dominique 25, rue Paris 75016 France

73
du monde Perrier Lauriston

84 Victuailles Mary 2, rue du Lyon 69004 France


en stock Saveley Commerce

85 Vins et Paul Henriot 59 rue de Reims 51100 France


alcools l'Abbaye
Chevalier

87 Wartian Pirkko Torikatu 38 Oulu 90110 Finland


Herkku Koskitalo

90 Wilman Kala Matti Keskuskatu Helsinki 21240 Finland


Karttunen 45

73 Simons Jytte Vinbltet Kbenhav 1734 Denmark


bistro Petersen 34 n

83 Vaffeljernet Palle Ibsen Smagslget rhus 8200 Denmark


45

10 Bottom- Elizabeth 23 Tsawasse T2F 8M4 Canada


Dollar Lincoln Tsawassen n
Marketse Blvd.

42 Laughing Yoshi 1900 Oak Vancouve V3F 2K1 Canada


Bacchus Tannamuri St. r
Wine Cellars

51 Mre Jean 43 rue St. Montral H1J 1C3 Canada


Paillarde Fresnire Laurent

15 Comrcio Pedro Av. dos So Paulo 05432- Brazil


Mineiro Afonso Lusadas, 23 043

74
21 Familia Aria Cruz Rua Ors, So Paulo 05442- Brazil
Arquibaldo 92 030

31 Gourmet Andr Av. Brasil, Campinas 04876- Brazil


Lanchonete Fonseca 442 786
s

34 Hanari Mario Rua do Rio de 05454- Brazil


Carnes Pontes Pao, 67 Janeiro 876

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificadora Janeiro 673
, 12

62 Queen Lcia Alameda So Paulo 05487- Brazil


Cozinha Carvalho dos 020
Canrios,
891

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacabana Janeiro 890
, 267

81 Tradio Anabela Av. Ins de So Paulo 05634- Brazil


Hipermerca Domingues Castro, 414 030
dos

88 Wellington Paula Rua do Resende 08737- Brazil


Importador Parente Mercado, 363
a 12

50 Maison Catherine Rue Joseph- Bruxelles B-1180 Belgium


Dewey Dewey Bens 532

75
76 Suprmes Pascale Boulevard Charleroi B-6000 Belgium
dlices Cartrain Tirou, 255

20 Ernst Roland Kirchgasse 6 Graz 8010 Austria


Handel Mendel

59 Piccolo und Georg Pipps Geislweg 14 Salzburg 5020 Austria


mehr

12 Cactus Patricio Cerrito 333 Buenos 1010 Argentin


Comidas Simpson Aires a
para llevar

54 Ocano Yvonne Ing. Gustavo Buenos 1010 Argentin


Atlntico Moncada Moncada Aires a
Ltda. 8585 Piso
20-A

64 Rancho Sergio Av. del Buenos 1010


grande Gutirrez Libertador Aires
900

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;

Custome CustomerN ContactNa Address City PostalCo Country


rID ame me de

12 Cactus Patricio Cerrito 333 Buenos 1010 Argentin

76
Comidas Simpson Aires a
para llevar

54 Ocano Yvonne Ing. Gustavo Buenos 1010 Argentin


Atlntico Moncada Moncada Aires a
Ltda. 8585 Piso
20-A

64 Rancho Sergio Av. del Buenos 1010 Argentin


grande Gutirrez Libertador Aires a
900

20 Ernst Roland Kirchgasse 6 Graz 8010 Austria


Handel Mendel

59 Piccolo und Georg Pipps Geislweg 14 Salzburg 5020 Austria


mehr

50 Maison Catherine Rue Joseph- Bruxelles B-1180 Belgium


Dewey Dewey Bens 532

76 Suprmes Pascale Boulevard Charleroi B-6000 Belgium


dlices Cartrain Tirou, 255

15 Comrcio Pedro Av. dos So Paulo 05432- Brazil


Mineiro Afonso Lusadas, 23 043

21 Familia Aria Cruz Rua Ors, So Paulo 05442- Brazil


Arquibaldo 92 030

31 Gourmet Andr Av. Brasil, Campinas 04876- Brazil


Lanchonete Fonseca 442 786
s

77
34 Hanari Mario Rua do Rio de 05454- Brazil
Carnes Pontes Pao, 67 Janeiro 876

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificadora Janeiro 673
, 12

62 Queen Lcia Alameda So Paulo 05487- Brazil


Cozinha Carvalho dos 020
Canrios,
891

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacabana Janeiro 890
, 267

81 Tradio Anabela Av. Ins de So Paulo 05634- Brazil


Hipermerca Domingues Castro, 414 030
dos

88 Wellington Paula Rua do Resende 08737- Brazil


Importador Parente Mercado, 363
a 12

10 Bottom- Elizabeth 23 Tsawasse T2F 8M4 Canada


Dollar Lincoln Tsawassen n
Marketse Blvd.

42 Laughing Yoshi 1900 Oak Vancouve V3F 2K1 Canada


Bacchus Tannamuri St. r
Wine Cellars

51 Mre Jean 43 rue St. Montral H1J 1C3 Canada


Paillarde Fresnire Laurent

78
73 Simons Jytte Vinbltet Kbenhav 1734 Denmark
bistro Petersen 34 n

83 Vaffeljernet Palle Ibsen Smagslget rhus 8200 Denmark


45

87 Wartian Pirkko Torikatu 38 Oulu 90110 Finland


Herkku Koskitalo

90 Wilman Kala Matti Keskuskatu Helsinki 21240 Finland


Karttunen 45

7 Blondel Frdrique 24, place Strasbour 67000 France


pre et fils Citeaux Klber g

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


Lebihans Bouchers

18 Du monde Janine 67, rue des Nantes 44000 France


entier Labrune Cinquante
Otages

23 Folies Martine 184, Lille 59000 France


gourmandes Ranc chausse de
Tournai

26 France Carine 54, rue Nantes 44000 France


restauration Schmitt Royale

40 La corne Daniel 67, avenue Versailles 78000 France


d'abondanc Tonini de l'Europe
e

41 La maison Annette 1 rue Toulouse 31000 France

79
d'Asie Roulet Alsace-
Lorraine

57 Paris Marie 265, Paris 75012 France


spcialits Bertrand boulevard
Charonne

74 Spcialits Dominique 25, rue Paris 75016 France


du monde Perrier Lauriston

84 Victuailles Mary 2, rue du Lyon 69004 France


en stock Saveley Commerce

85 Vins et Paul Henriot 59 rue de Reims 51100 France


alcools l'Abbaye
Chevalier

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

6 Blauer See Hanna Forsterstr. Mannhei 68306 German


Delikatesse Moos 57 m y
n

86 Die Rita Mller Adenauerall Stuttgart 70563 German


Wandernde ee 900 y
Kuh

17 Drachenblut Sven Ottlieb Walserweg Aachen 52066 German


Delikatesse 21 y
nd

25 Frankenvers Peter Berliner Mnchen 80805 German


and Franken Platz 43 y

80
39 Kniglich Philip Maubelstr. Brandenb 14776 German
Essen Cramer 90 urg y

44 Lehmanns Renate Magazinwe Frankfurt 60528 German


Marktstand Messner g7 a.M. y

52 Morgenster Alexander Heerstr. 22 Leipzig 04179 German


n Feuer y
Gesundkost

56 Ottilies Henriette Mehrheime Kln 50739 German


Kseladen Pfalzheim rstr. 369 y

63 QUICK-Stop Horst Kloss Taucherstra Cunewald 01307 German


e 10 e y

79 Toms Karin Luisenstr. Mnster 44087 German


Spezialitte Josephs 48 y
n

37 Hungry Owl Patricia 8 Cork Ireland


All-Night McKenna Johnstown
Grocers Road

27 Franchi Paolo Via Monte Torino 10100 Italy


S.p.A. Accorti Bianco 34

49 Magazzini Giovanni Via Bergamo 24100 Italy


Alimentari Rovelli Ludovico il
Riuniti Moro 22

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

81
2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico
Emparedad Constituci D.F.
os y helados n 2222

3 Antonio Antonio Mataderos Mxico 05023 Mexico


Moreno Moreno 2312 D.F.
Taquera

13 Centro Francisco Sierras de Mxico 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico


Comidas Fernndez Jorge Cash D.F.
clsicas 321

80 Tortuga Miguel Avda. Mxico 05033 Mexico


Restaurante Angel Azteca 123 D.F.
Paolino

70 Sant Jonas Erling Stavern 4110 Norway


Gourmet Bergulfsen Skakkes
gate 78

91 Wolski Zbyszek ul. Filtrowa Walla 01-012 Poland


68

28 Furia Lino Jardim das Lisboa 1675 Portugal


Bacalhau e Rodriguez rosas n. 32
Frutos do
Mar

60 Princesa Isabel de Estrada da Lisboa 1756 Portugal


Isabel Castro sade n. 58

82
Vinhoss

8 Blido Martn C/ Araquil, Madrid 28023 Spain


Comidas Sommer 67
preparadas

22 FISSA Diego Roel C/ Madrid 28034 Spain


Fabrica Moralzarzal,
Inter. 86
Salchichas
S.A.

29 Galera del Eduardo Rambla de Barcelona 08022 Spain


gastrnomo Saavedra Catalua,
23

30 Godos Jos Pedro C/ Romero, Sevilla 41101 Spain


Cocina Freyre 33
Tpica

69 Romero y Alejandra Gran Va, 1 Madrid 28001 Spain


tomillo Camino

5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden


snabbkp Berglund en 8

24 Folk och f Maria kergatan Brcke S-844 67 Sweden


HB Larsson 24

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


Chinese nd

68 Richter Michael Grenzacher Genve 1203 Switzerla


Supermarkt Holz weg 237 nd

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

11 B's Victoria Fauntleroy London EC2 5NT UK


Beverages Ashworth Circus

16 Consolidate Elizabeth Berkeley London WX1 6LT UK


d Holdings Brown Gardens 12
Brewery

19 Eastern Ann Devon 35 King London WX3 UK


Connection George 6FW

38 Island Helen Garden Cowes PO31 UK


Trading Bennett House 7PJ
Crowther
Way

53 North/Sout Simon South London SW7 1RZ UK


h Crowther House 300
Queensbrid
ge

72 Seven Seas Hari Kumar 90 London OX15 UK


Imports Wadhurst 4NB
Rd.

32 Great Lakes Howard 2732 Baker Eugene 97403 USA


Food Snyder Blvd.
Market

36 Hungry Yoshi City Center Elgin 97827 USA


Coyote Latimer Plaza 516
Import Main St.

84
Store

43 Lazy K John Steel 12 Walla 99362 USA


Kountry Orchestra Walla
Store Terrace

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


Shop Yorres Suite 5 Francisco

48 Lonesome Fran Wilson 89 Portland 97219 USA


Pine Chiaroscuro
Restaurant Rd.

55 Old World Rene 2743 Bering Anchorag 99508 USA


Delicatessen Phillips St. e

65 Rattlesnake Paula 2817 Milton Albuquer 87110 USA


Canyon Wilson Dr. que
Grocery

71 Save-a-lot Jose 187 Suffolk Boise 83720 USA


Markets Pavarotti Ln.

75 Split Rail Art P.O. Box Lander 82520 USA


Beer & Ale Braunschwe 555
iger

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.

82 Trail's Head Helvetius 722 DaVinci Kirkland 98034 USA

85
Gourmet Nagy Blvd.
Provisioners

89 White Karl 305 - 14th Seattle 98128 USA


Clover Jablonski Ave. S. Suite
Markets 3B

33 GROSELLA- Manuel 5 Ave. Los Caracas 1081 Venezue


Restaurante Pereira Palos la
Grandes

35 HILARIN- Carlos Carrera 22 San 5022 Venezue


Abastos Hernndez con Ave. Cristbal la
Carlos
Soublette
#8-35

46 LILA- Carlos Carrera 52 Barquisim 3508 Venezue


Supermerca Gonzlez con Ave. eto la
do Bolvar #65-
98 Llano
Largo

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


Delicateses Izquierdo Mayo Margarita
Porlamar

ORDER BY Several Columns Example

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

86
Example

SELECT * FROM Customers


ORDER BY Country, CustomerName;

Custome CustomerN ContactNa Address City PostalC Country


rID ame me ode

64 Rancho Sergio Av. del Buenos 1010 Argentin


grande Gutirrez Libertador Aires a
900

54 Ocano Yvonne Ing. Buenos 1010 Argentin


Atlntico Moncada Gustavo Aires a
Ltda. Moncada
8585 Piso
20-A

12 Cactus Patricio Cerrito 333 Buenos 1010 Argentin


Comidas Simpson Aires a
para llevar

59 Piccolo und Georg Pipps Geislweg Salzburg 5020 Austria


mehr 14

20 Ernst Roland Kirchgasse Graz 8010 Austria


Handel Mendel 6

76 Suprmes Pascale Boulevard Charleroi B-6000 Belgium


dlices Cartrain Tirou, 255

50 Maison Catherine Rue Bruxelles B-1180 Belgium


Dewey Dewey Joseph-
Bens 532

88 Wellington Paula Rua do Resende 08737- Brazil


Importadora Parente Mercado, 363
12

81 Tradio Anabela Av. Ins de So Paulo 05634- Brazil


Hipermerca Domingues Castro, 414 030
dos

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacaban Janeiro 890
a, 267

87
62 Queen Lcia Alameda So Paulo 05487- Brazil
Cozinha Carvalho dos 020
Canrios,
891

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificador Janeiro 673
a, 12

34 Hanari Mario Rua do Rio de 05454- Brazil


Carnes Pontes Pao, 67 Janeiro 876

31 Gourmet Andr Av. Brasil, Campinas 04876- Brazil


Lanchonetes Fonseca 442 786

21 Familia Aria Cruz Rua Ors, So Paulo 05442- Brazil


Arquibaldo 92 030

15 Comrcio Pedro Av. dos So Paulo 05432- Brazil


Mineiro Afonso Lusadas, 043
23

51 Mre Jean 43 rue St. Montral H1J 1C3 Canada


Paillarde Fresnire Laurent

42 Laughing Yoshi 1900 Oak Vancouve V3F Canada


Bacchus Tannamuri St. r 2K1
Wine
Cellars

10 Bottom- Elizabeth 23 Tsawasse T2F Canada


Dollar Lincoln Tsawassen n 8M4
Marketse Blvd.

83 Vaffeljernet Palle Ibsen Smagslget rhus 8200 Denmar


45 k

73 Simons Jytte Vinbltet Kbenhav 1734 Denmar


bistro Petersen 34 n k

90 Wilman Matti Keskuskatu Helsinki 21240 Finland


Kala Karttunen 45

87 Wartian Pirkko Torikatu 38 Oulu 90110 Finland


Herkku Koskitalo

85 Vins et Paul 59 rue de Reims 51100 France

88
alcools Henriot l'Abbaye
Chevalier

84 Victuailles Mary 2, rue du Lyon 69004 France


en stock Saveley Commerce

74 Spcialits Dominique 25, rue Paris 75016 France


du monde Perrier Lauriston

57 Paris Marie 265, Paris 75012 France


spcialits Bertrand boulevard
Charonne

41 La maison Annette 1 rue Toulouse 31000 France


d'Asie Roulet Alsace-
Lorraine

40 La corne Daniel 67, avenue Versailles 78000 France


d'abondance Tonini de l'Europe

26 France Carine 54, rue Nantes 44000 France


restauration Schmitt Royale

23 Folies Martine 184, Lille 59000 France


gourmandes Ranc chausse de
Tournai

18 Du monde Janine 67, rue des Nantes 44000 France


entier Labrune Cinquante
Otages

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


Lebihans Bouchers

7 Blondel pre Frdrique 24, place Strasbour 67000 France


et fils Citeaux Klber g

79 Toms Karin Luisenstr. Mnster 44087 German


Spezialitten Josephs 48 y

63 QUICK- Horst Kloss Taucherstra Cunewald 01307 German


Stop e 10 e y

56 Ottilies Henriette Mehrheime Kln 50739 German


Kseladen Pfalzheim rstr. 369 y

52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 German

89
Gesundkost Feuer y

44 Lehmanns Renate Magazinwe Frankfurt 60528 German


Marktstand Messner g7 a.M. y

39 Kniglich Philip Maubelstr. Brandenb 14776 German


Essen Cramer 90 urg y

25 Frankenvers Peter Berliner Mnchen 80805 German


and Franken Platz 43 y

17 Drachenblut Sven Ottlieb Walserweg Aachen 52066 German


Delikatessen 21 y
d

86 Die Rita Mller Adenaueral Stuttgart 70563 German


Wandernde lee 900 y
Kuh

6 Blauer See Hanna Forsterstr. Mannhei 68306 German


Delikatessen Moos 57 m y

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

37 Hungry Owl Patricia 8 Cork Ireland


All-Night McKenna Johnstown
Grocers Road

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

49 Magazzini Giovanni Via Bergamo 24100 Italy


Alimentari Rovelli Ludovico il
Riuniti Moro 22

27 Franchi Paolo Via Monte Torino 10100 Italy


S.p.A. Accorti Bianco 34

80 Tortuga Miguel Avda. Mxico 05033 Mexico


Restaurante Angel Azteca 123 D.F.
Paolino

58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico


Comidas Fernndez Jorge Cash D.F.
clsicas 321

90
13 Centro Francisco Sierras de Mxico 05022 Mexico
comercial Chang Granada D.F.
Moctezuma 9993

3 Antonio Antonio Mataderos Mxico 05023 Mexico


Moreno Moreno 2312 D.F.
Taquera

2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico


Emparedado Constituci D.F.
s y helados n 2222

70 Sant Jonas Erling Stavern 4110 Norway


Gourmet Bergulfsen Skakkes
gate 78

91 Wolski Zbyszek ul. Filtrowa Walla 01-012 Poland


68

60 Princesa Isabel de Estrada da Lisboa 1756 Portugal


Isabel Castro sade n. 58
Vinhoss

28 Furia Lino Jardim das Lisboa 1675 Portugal


Bacalhau e Rodriguez rosas n. 32
Frutos do
Mar

69 Romero y Alejandra Gran Va, 1 Madrid 28001 Spain


tomillo Camino

30 Godos Jos Pedro C/ Romero, Sevilla 41101 Spain


Cocina Freyre 33
Tpica

29 Galera del Eduardo Rambla de Barcelona 08022 Spain


gastrnomo Saavedra Catalua,
23

22 FISSA Diego Roel C/ Madrid 28034 Spain


Fabrica Moralzarzal
Inter. , 86
Salchichas
S.A.

8 Blido Martn C/ Araquil, Madrid 28023 Spain


Comidas Sommer 67

91
preparadas

24 Folk och f Maria kergatan Brcke S-844 67 Sweden


HB Larsson 24

5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden


snabbkp Berglund en 8

68 Richter Michael Grenzacher Genve 1203 Switzerl


Supermarkt Holz weg 237 and

14 Chop-suey Yang Wang Hauptstr. Bern 3012 Switzerl


Chinese 29 and

72 Seven Seas Hari Kumar 90 London OX15 UK


Imports Wadhurst 4NB
Rd.

53 North/South Simon South London SW7 UK


Crowther House 300 1RZ
Queensbrid
ge

38 Island Helen Garden Cowes PO31 UK


Trading Bennett House 7PJ
Crowther
Way

19 Eastern Ann Devon 35 King London WX3 UK


Connection George 6FW

16 Consolidate Elizabeth Berkeley London WX1 UK


d Holdings Brown Gardens 12 6LT
Brewery

11 B's Victoria Fauntleroy London EC2 UK


Beverages Ashworth Circus 5NT

4 Around the Thomas 120 London WA1 UK


Horn Hardy Hanover 1DP
Sq.

89 White Karl 305 - 14th Seattle 98128 USA


Clover Jablonski Ave. S.
Markets Suite 3B

82 Trail's Head Helvetius 722 Kirkland 98034 USA

92
Gourmet Nagy DaVinci
Provisioners Blvd.

78 The Cracker Liu Wong 55 Grizzly Butte 59801 USA


Box Peak Rd.

77 The Big Liz Nixon 89 Portland 97201 USA


Cheese Jefferson
Way Suite
2

75 Split Rail Art P.O. Box Lander 82520 USA


Beer & Ale Braunschwe 555
iger

71 Save-a-lot Jose 187 Suffolk Boise 83720 USA


Markets Pavarotti Ln.

65 Rattlesnake Paula 2817 Albuquer 87110 USA


Canyon Wilson Milton Dr. que
Grocery

55 Old World Rene 2743 Anchorag 99508 USA


Delicatessen Phillips Bering St. e

48 Lonesome Fran Wilson 89 Portland 97219 USA


Pine Chiaroscur
Restaurant o Rd.

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


Shop Yorres Suite 5 Francisco

43 Lazy K John Steel 12 Walla 99362 USA


Kountry Orchestra Walla
Store Terrace

36 Hungry Yoshi City Center Elgin 97827 USA


Coyote Latimer Plaza 516
Import Store Main St.

32 Great Lakes Howard 2732 Baker Eugene 97403 USA


Food Market Snyder Blvd.

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


Delicateses Izquierdo Mayo Margarita la
Porlamar

93
46 LILA- Carlos Carrera 52 Barquisim 3508 Venezue
Supermerca Gonzlez con Ave. eto la
do Bolvar
#65-98
Llano
Largo

35 HILARIN- Carlos Carrera 22 San 5022 Venezue


Abastos Hernndez con Ave. Cristbal la
Carlos
Soublette
#8-35

33 GROSELL Manuel 5 Ave. Los Caracas 1081 Venezue


A- Pereira Palos la
Restaurante Grandes

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.

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

94
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');

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

95
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

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.

Insert Data Only in Specified Columns

It is also possible to only insert data in specific columns.

The following SQL statement will insert a new record, but only insert
data in the "CustomerName", "City", and "Country" columns
(CustomerID will be updated automatically):

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

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

CustomerI CustomerNa ContactNa Address City PostalCo Countr


D me me de y

89 White Clover Karl 305 - Seattle 98128 USA


Markets Jablonski 14th Ave.
S. Suite
3B

90 Wilman Kala Matti Keskuska Helsinki 21240 Finland


Karttunen tu 45

91 Wolski Zbyszek ul. Walla 01-012 Poland


Filtrowa
68

92 Cardinal null null Stavang null Norwa


er y

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.

97
Note: It is very important to understand that 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

SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

Demo Database

Assume we have the following "Persons" table:

ID LastName FirstName Address City

1 Doe John 542 W. 27th Street New York

2 Bloggs Joe London

3 Roe Jane New York

98
4 Smith John 110 Bishopsgate London

Suppose that the "Address" column in the "Persons" table is optional. If


a record is inserted with no value for "Address", the "Address" column
will be saved with a NULL value.

The IS NULL Operator

The following SQL statement uses the IS NULL operator to list all
persons that have no address:

SELECT LastName, FirstName, Address FROM Persons


WHERE Address IS NULL;

The result-set will look like this:

LastName FirstName Address

Bloggs Joe

Roe Jane

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

The IS NOT NULL Operator

The following SQL statement uses the IS NOT NULL operator to list all
persons that do have an address:

SELECT LastName, FirstName, Address FROM Persons


WHERE Address IS NOT NULL;

The result-set will look like this:

99
LastName FirstName Address

Doe John 542 W. 27th Street

Smith John 110 Bishopsgate

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

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

100
2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico
Emparedados y Constitucin D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico


Taquera Moreno 2312 D.F.

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

5 Berglunds Christina Berguvsvgen Lule S-958 22 Sweden


snabbkp Berglund 8

UPDATE Table

The following SQL statement updates the first customer (CustomerID =


1) with a new contact person and a new city.

Example

SQL Statement:
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Frankfurt'
WHERE CustomerID=;

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
You have made changes to the database. Rows affected: 1

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

101
Customer CustomerNa ContactNa Address City PostalCo Countr
ID me me de y

1 Alfreds Alfred Obere Str. Frankfu 12209 Germa


Futterkiste Schmidt 57 rt ny

2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico


Emparedados Constituci D.F.
y helados n 2222

3 Antonio Antonio Mataderos Mxico 05023 Mexico


Moreno Moreno 2312 D.F.
Taquera

4 Around the Thomas 120 London WA1 UK


Horn Hardy Hanover 1DP
Sq.

5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden


snabbkp Berglund en 8

UPDATE Multiple Records

It is the WHERE clause that determines how many records that 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';
102
The selection from the "Customers" table will now look like this:

Customer CustomerNa ContactNa Address City PostalCo Countr


ID me me de y

1 Alfreds Alfred Obere Str. Frankfu 12209 Germa


Futterkiste Schmidt 57 rt ny

2 Ana Trujillo Juan Avda. de la Mxico 05021 Mexico


Emparedados Constituci D.F.
y helados n 2222

3 Antonio Juan Mataderos Mxico 05023 Mexico


Moreno 2312 D.F.
Taquera

4 Around the Thomas 120 London WA1 UK


Horn Hardy Hanover 1DP
Sq.

5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden


snabbkp Berglund en 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:
103
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Juan Obere Str. 57 Frankfurt 12209 Germany


Futterkiste

2 Ana Trujillo Juan Avda. de la Mxico 05021 Mexico


Emparedados y Constitucin D.F.
helados 2222

3 Antonio Moreno Juan Mataderos Mxico 05023 Mexico


Taquera 2312 D.F.

4 Around the Juan 120 Hanover London WA1 1DP UK


Horn Sq.

5 Berglunds Juan Berguvsvgen Lule S-958 22 Sweden


snabbkp 8

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

104
record(s) that 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:

CustomerI CustomerNa ContactNa Address City PostalCo Countr


D me me de y

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de la Mxic 05021 Mexico


Emparedados Constituci o D.F.
y helados n 2222

3 Antonio Antonio Mataderos Mxic 05023 Mexico


Moreno Moreno 2312 o D.F.
Taquera

4 Around the Thomas 120 Londo WA1 1DP UK


Horn Hardy Hanover n
Sq.

5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden


snabbkp Berglund en 8

SQL DELETE Example

The following SQL statement deletes the customer "Alfreds Futterkiste"


from the "Customers" table:

105
Example

SQL Statement:
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste';

Edit the SQL Statement, and click "Run SQL" to see the result.

Run SQL
Result:
You have made changes to the database.
SQL DELETE Example

The following SQL statement deletes the customer "Alfreds Futterkiste"


from the "Customers" table:

Example

SQL Statement:
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste';

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
You have made changes to the database

The "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico


Emparedados y Constitucin D.F.
helados 2222

106
3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico
Taquera Moreno 2312 D.F.

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

5 Berglunds Christina Berguvsvgen Lule S-958 22 Sweden


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

or:

DELETE * FROM table_name;

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 can be very useful on large tables with
thousands of records. Returning a large number of records can impact
on performance.

Note: Not all database systems support the SELECT TOP clause.

SQL Server / MS Access Syntax


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

107
SQL SELECT TOP Equivalent in MySQL and Oracle
MySQL Syntax
SELECT column_name(s)
FROM table_name
LIMIT number;

Example
SELECT *
FROM Persons
LIMIT 5;

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

Example
SELECT *
FROM Persons
WHERE ROWNUM <=5;

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 Mxico 05021 Mexico


Emparedados y Constitucin D.F.

108
helados 2222

3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico


Taquera Moreno 2312 D.F.

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

5 Berglunds Christina Berguvsvgen Lule S-958 22 Sweden


snabbkp Berglund 8

SQL SELECT TOP Example

The following SQL statement selects the two first records from the
"Customers" table:

Example

Alfreds Maria Obere Str. Berlin 12209 Germany


Futterkiste Anders 57

2 Ana Trujillo Ana Avda. de la Mxico 05021 M


Emparedados y Trujillo Constitucin D.F.
helados 2222

SQL SELECT TOP PERCENT Example

The following SQL statement selects the first 50% of the records from
the "Customers" table:

Example

Number of Records: 46

Custo Custome Contact Addres City Postal Countr


merID rName Name s Code y

109
1 Alfreds Maria Obere Berlin 12209 Germa
Futterkist Anders Str. 57 ny
e

2 Ana Ana Avda. de Mxico 05021 Mexico


Trujillo Trujillo la D.F.
Empareda Constitu
dos y cin
helados 2222

3 Antonio Antonio Matader Mxico 05023 Mexico


Moreno Moreno os 2312 D.F.
Taquera

4 Around Thomas 120 London WA1 UK


the Horn Hardy Hanover 1DP
Sq.

5 Berglunds Christina Berguvs Lule S-958 Swede


snabbkp Berglund vgen 8 22 n

6 Blauer Hanna Forsters Mannhei 68306 Germa


See Moos tr. 57 m ny
Delikatess
en

7 Blondel Frdriq 24, Strasbo 67000 France


pre et ue place urg
fils Citeaux Klber

8 Blido Martn C/ Madrid 28023 Spain


Comidas Sommer Araquil,
preparada 67
s

9 Bon app' Laurence 12, rue Marseill 13008 France


Lebihans des e
Boucher
s

10 Bottom- Elizabeth 23 Tsawass T2F Canada


Dollar Lincoln Tsawass en 8M4
Marketse en
Blvd.

110
11 B's Victoria Fauntler London EC2 UK
Beverages Ashwort oy 5NT
h Circus

12 Cactus Patricio Cerrito Buenos 1010 Argenti


Comidas Simpson 333 Aires na
para
llevar

13 Centro Francisco Sierras Mxico 05022 Mexico


comercial Chang de D.F.
Moctezum Granada
a 9993

14 Chop-suey Yang Hauptstr Bern 3012 Switzer


Chinese Wang . 29 land

15 Comrcio Pedro Av. dos So 05432- Brazil


Mineiro Afonso Lusadas Paulo 043
, 23

16 Consolidat Elizabeth Berkeley London WX1 UK


ed Brown Gardens 6LT
Holdings 12
Brewery

17 Drachenbl Sven Walserw Aachen 52066 Germa


ut Ottlieb eg 21 ny
Delikatess
end

18 Du monde Janine 67, rue Nantes 44000 France


entier Labrune des
Cinquan
te
Otages

19 Eastern Ann 35 King London WX3 UK


Connectio Devon George 6FW
n

20 Ernst Roland Kirchgas Graz 8010 Austria


Handel Mendel se 6

111
21 Familia Aria Rua So 05442- Brazil
Arquibaldo Cruz Ors, Paulo 030
92

22 FISSA Diego C/ Madrid 28034 Spain


Fabrica Roel Moralzar
Inter. zal, 86
Salchichas
S.A.

23 Folies Martine 184, Lille 59000 France


gourmand Ranc chauss
es e de
Tournai

24 Folk och Maria kergat Brcke S-844 Swede


f HB Larsson an 24 67 n

25 Frankenve Peter Berliner Mnche 80805 Germa


rsand Franken Platz 43 n ny

26 France Carine 54, rue Nantes 44000 France


restaurati Schmitt Royale
on

27 Franchi Paolo Via Torino 10100 Italy


S.p.A. Accorti Monte
Bianco
34

28 Furia Lino Jardim Lisboa 1675 Portug


Bacalhau Rodrigue das al
e Frutos z rosas n.
do Mar 32

29 Galera Eduardo Rambla Barcelo 08022 Spain


del Saavedr de na
gastrno a Catalua
mo , 23

30 Godos Jos C/ Sevilla 41101 Spain


Cocina Pedro Romero,
Tpica Freyre 33

31 Gourmet Andr Av. Campin 04876- Brazil

112
Lanchonet Fonseca Brasil, as 786
es 442

32 Great Howard 2732 Eugene 97403 USA


Lakes Snyder Baker
Food Blvd.
Market

33 GROSELLA Manuel 5 Ave. Caracas 1081 Venezu


- Pereira Los ela
Restauran Palos
te Grandes

34 Hanari Mario Rua do Rio de 05454- Brazil


Carnes Pontes Pao, Janeiro 876
67

35 HILARIN Carlos Carrera San 5022 Venezu


-Abastos Hernnd 22 con Cristba ela
ez Ave. l
Carlos
Soublett
e #8-
35

36 Hungry Yoshi City Elgin 97827 USA


Coyote Latimer Center
Import Plaza
Store 516
Main
St.

37 Hungry Patricia 8 Cork Ireland


Owl All- McKenna Johnsto
Night wn
Grocers Road

38 Island Helen Garden Cowes PO31 UK


Trading Bennett House 7PJ
Crowthe
r Way

39 Kniglich Philip Maubels Branden 14776 Germa


Essen Cramer tr. 90 burg ny

113
40 La corne Daniel 67, Versaille 78000 France
d'abondan Tonini avenue s
ce de
l'Europe

41 La maison Annette 1 rue Toulous 31000 France


d'Asie Roulet Alsace- e
Lorraine

42 Laughing Yoshi 1900 Vancouv V3F Canada


Bacchus Tannamu Oak St. er 2K1
Wine ri
Cellars

43 Lazy K John 12 Walla 99362 USA


Kountry Steel Orchestr Walla
Store a
Terrace

44 Lehmanns Renate Magazin Frankfur 60528 Germa


Marktstan Messner weg 7 t a.M. ny
d

45 Let's Stop Jaime 87 Polk San 94117 USA


N Shop Yorres St. Suite Francisc
5 o

46 LILA- Carlos Carrera Barquisi 3508


Supermer Gonzlez 52 con meto
cado Ave.
Bolvar
#65-98
Llano
Largo

SQL MIN() and MAX() Functions

The SQL MIN() and MAX() Functions

The MIN() function returns the smallest value of the selected column.

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

MIN() Syntax

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

115
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

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

116
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 criteria.

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

1 Chais 1 1 10 boxes x 20 18
bags

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

Number of Records: 1

COUNT(ProductID)

77

AVG() Example

The following SQL statement finds the average price of all products:

Example

SELECT AVG(Price)
FROM Products;

118
Number of Records: 1

AVG(Price)

28.866363636363637

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

SUM() Example

The following SQL statement finds the sum of the "Quantity" fields in the
"OrderDetails" table:

119
Example

SELECT SUM(Quantity)
FROM OrderDetails;

Number of Records: 1

SUM(Quantity)

12743

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.

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

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


_ - The underscore represents a single number or character

The percent sign and the underscore can 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 Finds any values that starts with "a"

120
LIKE 'a%'

WHERE CustomerName Finds any values that ends with "a"


LIKE '%a'

WHERE CustomerName Finds any values that have "or" in any


LIKE '%or%' position

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

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

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

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

121
2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico
Emparedados y Constitucin D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico


Taquera Moreno 2312 D.F.

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

5 Berglunds Christina Berguvsvgen Lule S-958 22 Sweden


snabbkp Berglund 8

SQL LIKE Examples

The following SQL statement selects all customers with a


CustomerName starting with "a":

Example

SELECT * FROM Customers


WHERE CustomerName LIKE 'a%';

Number of Records: 4

Customer CustomerNa ContactNa Address City PostalCo Count


ID me me de ry

1 Alfreds Maria Obere Berlin 12209 Germa


Futterkiste Anders Str. 57 ny

2 Ana Trujillo Ana Trujillo Avda. de Mxic 05021 Mexico


Emparedados la o
y helados Constituci D.F.
n 2222

3 Antonio Antonio Matadero Mxic 05023 Mexico

122
Moreno Moreno s 2312 o
Taquera D.F.

4 Around the Thomas 120 Lond WA1 1DP UK


Horn Hardy Hanover on
Sq.

The following SQL statement selects all customers with a


CustomerName ending with "a":

Example

SELECT * FROM Customers


WHERE CustomerName LIKE '%a';

Number of Records: 7

Custome CustomerN ContactNa Address City PostalCo Count


rID ame me de ry

3 Antonio Antonio Matadero Mxic 05023 Mexico


Moreno Moreno s 2312 o D.F.
Taquera

13 Centro Francisco Sierras de Mxic 05022 Mexico


comercial Chang Granada o D.F.
Moctezuma 9993

30 Godos Cocina Jos Pedro C/ Sevilla 41101 Spain


Tpica Freyre Romero,
33

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificado Janeir 673
ra, 12 o

62 Queen Lcia Alameda So 05487- Brazil


Cozinha Carvalho dos Paulo 020
Canrios,
891

88 Wellington Paula Rua do Resen 08737- Brazil


Importadora Parente Mercado, de 363
12

90 Wilman Kala Matti Keskuskat Helsin 21240 Finlan


Karttunen u 45 ki d

123
The following SQL statement selects all customers with a
CustomerName that have "or" in any position:

Example

SELECT * FROM Customers


WHERE CustomerName LIKE '%or%';

Number of Records: 11

Custome CustomerN ContactN Address City PostalC Count


rID ame ame ode ry

3 Antonio Antonio Mataderos Mxico 05023 Mexico


Moreno Moreno 2312 D.F.
Taquera

4 Around the Thomas 120 London WA1 1DP UK


Horn Hardy Hanover
Sq.

36 Hungry Yoshi City Elgin 97827 USA


Coyote Latimer Center
Import Store Plaza 516
Main St.

40 La corne Daniel 67, Versaill 78000 France


d'abondance Tonini avenue de es
l'Europe

43 Lazy K John Steel 12 Walla 99362 USA


Kountry Orchestra Walla
Store Terrace

52 Morgenstern Alexander Heerstr. Leipzig 04179 Germa


Gesundkost Feuer 22 ny

53 North/South Simon South London SW7 1RZ UK


Crowther House
300
Queensbri
dge

55 Old World Rene 2743 Anchor 99508 USA


Delicatessen Phillips Bering St. age

72 Seven Seas Hari Kumar 90 London OX15 UK


Imports Wadhurst 4NB
Rd.

124
80 Tortuga Miguel Avda. Mxico 05033 Mexico
Restaurante Angel Azteca D.F.
Paolino 123

88 Wellington Paula Rua do Resend 08737- Brazil


Importadora Parente Mercado, e 363
12

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%';

Number of Records: 11

Custome CustomerN ContactNa Addres City PostalCo Countr


rID ame me s de y

4 Around the Thomas 120 Londo WA1 1DP UK


Horn Hardy Hanover n
Sq.

17 Drachenblut Sven Walserw Aache 52066 German


Delikatessen Ottlieb eg 21 n y
d

20 Ernst Handel Roland Kirchgas Graz 8010 Austria


Mendel se 6

25 Frankenversa Peter Berliner Mnch 80805 German


nd Franken Platz 43 en y

26 France Carine 54, rue Nantes 44000 France


restauration Schmitt Royale

27 Franchi Paolo Via Torino 10100 Italy


S.p.A. Accorti Monte
Bianco
34

32 Great Lakes Howard 2732 Eugen 97403 USA


Food Market Snyder Baker e
Blvd.

33 GROSELLA- Manuel 5 Ave. Caraca 1081 Venezu

125
Restaurante Pereira Los s ela
Palos
Grandes

60 Princesa Isabel de Estrada Lisboa 1756 Portuga


Isabel Castro da l
Vinhoss sade n.
58

81 Tradio Anabela Av. Ins So 05634- Brazil


Hipermercad Domingues de Paulo 030
os Castro,
414

82 Trail's Head Helvetius 722 Kirklan 98034 USA


Gourmet Nagy DaVinci d
Provisioners Blvd.

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_%_%';

Number of Records: 4

Customer CustomerNa ContactNa Address City PostalCo Count


ID me me de ry

1 Alfreds Maria Obere Berlin 12209 Germa


Futterkiste Anders Str. 57 ny

2 Ana Trujillo Ana Trujillo Avda. de Mxic 05021 Mexico


Emparedados la o
y helados Constituci D.F.
n 2222

3 Antonio Antonio Matadero Mxic 05023 Mexico


Moreno Moreno s 2312 o
Taquera D.F.

4 Around the Thomas 120 Lond WA1 1DP UK


Horn Hardy Hanover on
Sq.

126
The following SQL statement selects all customers with a
CustomerName that starts with "a" and ends with "o":

Example

SELECT * FROM Customers


WHERE ContactName LIKE 'a%o';

Number of Records: 3

Customer CustomerNa ContactNa Address City PostalCo Count


ID me me de ry

2 Ana Trujillo Ana Trujillo Avda. de Mxi 05021 Mexico


Emparedados la co
y helados Constituci D.F.
n 2222

3 Antonio Antonio Matadero Mxi 05023 Mexico


Moreno Moreno s 2312 co
Taquera D.F.

69 Romero y Alejandra Gran Va, Madri 28001 Spain


tomillo Camino 1 d

The following SQL statement selects all customers with a


CustomerName that NOT starts with "a":

Example

SELECT * FROM Customers


WHERE CustomerName NOT LIKE 'a%';

Number of Records: 87

Custom Customer ContactN Address City PostalC Countr


erID Name ame ode y

5 Berglunds Christina Berguvsv Lule S-958 Sweden


snabbkp Berglund gen 8 22

6 Blauer See Hanna Forsterstr. Mannhei 68306 German


Delikatesse Moos 57 m y
n

7 Blondel Frdrique 24, place Strasbou 67000 France


pre et fils Citeaux Klber rg

127
8 Blido Martn C/ Araquil, Madrid 28023 Spain
Comidas Sommer 67
preparadas

9 Bon app' Laurence 12, rue Marseille 13008 France


Lebihans des
Bouchers

10 Bottom- Elizabeth 23 Tsawass T2F 8M4 Canada


Dollar Lincoln Tsawassen en
Marketse Blvd.

11 B's Victoria Fauntleroy London EC2 5NT UK


Beverages Ashworth Circus

12 Cactus Patricio Cerrito Buenos 1010 Argenti


Comidas Simpson 333 Aires na
para llevar

13 Centro Francisco Sierras de Mxico 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

14 Chop-suey Yang Hauptstr. Bern 3012 Switzerl


Chinese Wang 29 and

15 Comrcio Pedro Av. dos So 05432- Brazil


Mineiro Afonso Lusadas, Paulo 043
23

16 Consolidate Elizabeth Berkeley London WX1 UK


d Holdings Brown Gardens 6LT
12
Brewery

17 Drachenblu Sven Walserweg Aachen 52066 German


t Ottlieb 21 y
Delikatesse
nd

18 Du monde Janine 67, rue Nantes 44000 France


entier Labrune des
Cinquante
Otages

19 Eastern Ann Devon 35 King London WX3 UK


Connection George 6FW

20 Ernst Roland Kirchgasse Graz 8010 Austria


Handel Mendel 6

128
21 Familia Aria Cruz Rua Ors, So 05442- Brazil
Arquibaldo 92 Paulo 030

22 FISSA Diego Roel C/ Madrid 28034 Spain


Fabrica Moralzarza
Inter. l, 86
Salchichas
S.A.

23 Folies Martine 184, Lille 59000 France


gourmande Ranc chausse
s de Tournai

24 Folk och f Maria kergatan Brcke S-844 Sweden


HB Larsson 24 67

25 Frankenver Peter Berliner Mnchen 80805 German


sand Franken Platz 43 y

26 France Carine 54, rue Nantes 44000 France


restauratio Schmitt Royale
n

27 Franchi Paolo Via Monte Torino 10100 Italy


S.p.A. Accorti Bianco 34

28 Furia Lino Jardim das Lisboa 1675 Portuga


Bacalhau e Rodriguez rosas n. l
Frutos do 32
Mar

29 Galera del Eduardo Rambla de Barcelon 08022 Spain


gastrnomo Saavedra Catalua, a
23

30 Godos Jos Pedro C/ Sevilla 41101 Spain


Cocina Freyre Romero,
Tpica 33

31 Gourmet Andr Av. Brasil, Campina 04876- Brazil


Lanchonete Fonseca 442 s 786
s

32 Great Lakes Howard 2732 Eugene 97403 USA


Food Snyder Baker
Market Blvd.

33 GROSELLA- Manuel 5 Ave. Caracas 1081 Venezu


Restaurante Pereira Los Palos ela
Grandes

129
34 Hanari Mario Rua do Rio de 05454- Brazil
Carnes Pontes Pao, 67 Janeiro 876

35 HILARIN- Carlos Carrera 22 San 5022 Venezu


Abastos Hernndez con Ave. Cristbal ela
Carlos
Soublette
#8-35

36 Hungry Yoshi City Elgin 97827 USA


Coyote Latimer Center
Import Plaza 516
Store Main St.

37 Hungry Owl Patricia 8 Cork Ireland


All-Night McKenna Johnstown
Grocers Road

38 Island Helen Garden Cowes PO31 UK


Trading Bennett House 7PJ
Crowther
Way

39 Kniglich Philip Maubelstr. Branden 14776 German


Essen Cramer 90 burg y

40 La corne Daniel 67, Versaille 78000 France


d'abondanc Tonini avenue de s
e l'Europe

41 La maison Annette 1 rue Toulouse 31000 France


d'Asie Roulet Alsace-
Lorraine

42 Laughing Yoshi 1900 Oak Vancouv V3F 2K1 Canada


Bacchus Tannamuri St. er
Wine
Cellars

43 Lazy K John Steel 12 Walla 99362 USA


Kountry Orchestra Walla
Store Terrace

44 Lehmanns Renate Magazinw Frankfurt 60528 German


Marktstand Messner eg 7 a.M. y

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


Shop Yorres St. Suite 5 Francisc
o

130
46 LILA- Carlos Carrera 52 Barquisi 3508 Venezu
Supermerca Gonzlez con Ave. meto ela
do Bolvar
#65-98
Llano
Largo

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


Delicateses Izquierdo Mayo Margarit ela
Porlamar a

48 Lonesome Fran 89 Portland 97219 USA


Pine Wilson Chiaroscur
Restaurant o Rd.

49 Magazzini Giovanni Via Bergamo 24100 Italy


Alimentari Rovelli Ludovico il
Riuniti Moro 22

50 Maison Catherine Rue Bruxelles B-1180 Belgium


Dewey Dewey Joseph-
Bens 532

51 Mre Jean 43 rue St. Montral H1J 1C3 Canada


Paillarde Fresnire Laurent

52 Morgenster Alexander Heerstr. Leipzig 04179 German


n Feuer 22 y
Gesundkost

53 North/Sout Simon South London SW7 UK


h Crowther House 300 1RZ
Queensbri
dge

54 Ocano Yvonne Ing. Buenos 1010 Argenti


Atlntico Moncada Gustavo Aires na
Ltda. Moncada
8585 Piso
20-A

55 Old World Rene 2743 Anchora 99508 USA


Delicatesse Phillips Bering St. ge
n

56 Ottilies Henriette Mehrheim Kln 50739 German


Kseladen Pfalzheim erstr. 369 y

57 Paris Marie 265, Paris 75012 France


spcialits Bertrand boulevard

131
Charonne

58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico


Comidas Fernndez Jorge D.F.
clsicas Cash 321

59 Piccolo und Georg Geislweg Salzburg 5020 Austria


mehr Pipps 14

60 Princesa Isabel de Estrada da Lisboa 1756 Portuga


Isabel Castro sade n. l
Vinhoss 58

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificado Janeiro 673
ra, 12

62 Queen Lcia Alameda So 05487- Brazil


Cozinha Carvalho dos Paulo 020
Canrios,
891

63 QUICK-Stop Horst Taucherstr Cunewal 01307 German


Kloss ae 10 de y

64 Rancho Sergio Av. del Buenos 1010 Argenti


grande Gutirrez Libertador Aires na
900

65 Rattlesnake Paula 2817 Albuquer 87110 USA


Canyon Wilson Milton Dr. que
Grocery

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacaba Janeiro 890
na, 267

68 Richter Michael Grenzache Genve 1203 Switzerl


Supermarkt Holz rweg 237 and

69 Romero y Alejandra Gran Va, Madrid 28001 Spain


tomillo Camino 1

70 Sant Jonas Erling Stavern 4110 Norway


Gourmet Bergulfsen Skakkes
gate 78

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

72 Seven Seas Hari 90 London OX15 UK


Imports Kumar Wadhurst 4NB
Rd.

73 Simons Jytte Vinbltet Kbenha 1734 Denmar


bistro Petersen 34 vn k

74 Spcialits Dominique 25, rue Paris 75016 France


du monde Perrier Lauriston

75 Split Rail Art P.O. Box Lander 82520 USA


Beer & Ale Braunschw 555
eiger

76 Suprmes Pascale Boulevard Charleroi B-6000 Belgium


dlices Cartrain Tirou, 255

77 The Big Liz Nixon 89 Portland 97201 USA


Cheese Jefferson
Way Suite
2

78 The Cracker Liu Wong 55 Grizzly Butte 59801 USA


Box Peak Rd.

79 Toms Karin Luisenstr. Mnster 44087 German


Spezialitte Josephs 48 y
n

80 Tortuga Miguel Avda. Mxico 05033 Mexico


Restaurante Angel Azteca D.F.
Paolino 123

81 Tradio Anabela Av. Ins So 05634- Brazil


Hipermerca Domingues de Castro, Paulo 030
dos 414

82 Trail's Head Helvetius 722 Kirkland 98034 USA


Gourmet Nagy DaVinci
Provisioners Blvd.

83 Vaffeljernet Palle Ibsen Smagslg rhus 8200 Denmar


et 45 k

84 Victuailles Mary 2, rue du Lyon 69004 France


en stock Saveley Commerce

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

86 Die Rita Mller Adenauera Stuttgart 70563 German


Wandernde llee 900 y
Kuh

87 Wartian Pirkko Torikatu Oulu 90110 Finland


Herkku Koskitalo 38

88 Wellington Paula Rua do Resende 08737- Brazil


Importador Parente Mercado, 363
a 12

89 White Karl 305 - 14th Seattle 98128 USA


Clover Jablonski Ave. S.
Markets Suite 3B

90 Wilman Matti Keskuskat Helsinki 21240 Finland


Kala Karttunen u 45

91 Wolski Zbyszek ul. Walla 01-012 Poland


Filtrowa
68

SQL Wildcards

A wildcard character can be used to substitute for any other character(s)


in a string.

SQL Wildcard Characters

In SQL, wildcard characters are used with the SQL LIKE operator.

SQL wildcards are used to search for data within a table.

With SQL, the wildcards are:

134
Wildcard Description

% A substitute for zero or more characters

_ A substitute for a single character

[charlist] Sets and ranges of characters to match

[^charlist] Matches only a character NOT specified within the brackets


or
[!charlist]

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 Mxico 05021 Mexico


Emparedados y Constitucin D.F.
helados 2222

135
3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico
Taquera Moreno 2312 D.F.

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

5 Berglunds Christina Berguvsvgen Lule S-958 22 Sweden


snabbkp Berglund 8

Using the SQL % Wildcard

The following SQL statement selects all customers with a City starting
with "ber":

Example

SQL Statement:
SELECT * FROM Customers
WHERE City LIKE 'ber%';

Edit the SQL Statement, and click "Run SQL" to see the result.

Run SQL
Result:
Number of Records: 2

CustomerID CustomerName ContactName Address City PostalCode Country

14 Chop-suey Yang Wang Hauptstr. Bern 3012 Switzerland


Chinese 29

49 Magazzini Giovanni Via Bergamo 24100 Italy


Alimentari Rovelli Ludovico
Riuniti il Moro
22

136
The following SQL statement selects all customers with a City containing
the pattern "es":

Example

SQL Statement:
SELECT * FROM Customers
WHERE City LIKE '%es%';

Edit the SQL Statement, and click "Run SQL" to see the result.

Run SQL
Result:
Number of Records: 9

CustomerI CustomerNa ContactNa Address City PostalCo Countr


D me me de y

12 Cactus Patricio Cerrito Buenos 1010 Argenti


Comidas para Simpson 333 Aires na
llevar

18 Du monde Janine 67, rue Nantes 44000 France


entier Labrune des
Cinquant
e Otages

26 France Carine 54, rue Nantes 44000 France


restauration Schmitt Royale

38 Island Trading Helen Garden Cowes PO31 7PJ UK


Bennett House
Crowthe
r Way

40 La corne Daniel 67, Versaill 78000 France


d'abondance Tonini avenue es
de
l'Europe

50 Maison Catherine Rue Bruxelle B-1180 Belgium


Dewey Dewey Joseph- s
Bens
532

137
54 Ocano Yvonne Ing. Buenos 1010 Argenti
Atlntico Moncada Gustavo Aires na
Ltda. Moncad
a 8585
Piso 20-
A

64 Rancho Sergio Av. del Buenos 1010 Argenti


grande Gutirrez Libertad Aires na
or 900

88 Wellington Paula Rua do Resende 08737- Brazil


Importadora Parente Mercado 363
, 12

Using the SQL _ Wildcard

The following SQL statement selects all customers with a City starting
with any character, followed by "erlin":

SQL Statement:
SELECT * FROM Customers
WHERE City LIKE '_erlin';

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
No result.

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

SQL Statement:
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:

138
Number of Records: 6

CustomerI CustomerNa ContactNa Address City PostalCo Countr


D me me de y

4 Around the Thomas 120 Londo WA1 1DP UK


Horn Hardy Hanover n
Sq.

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


Ashworth Circus n

16 Consolidated Elizabeth Berkeley Londo WX1 6LT UK


Holdings Brown Gardens 12 n
Brewery

19 Eastern Ann Devon 35 King Londo WX3 UK


Connection George n 6FW

53 North/South Simon South Londo SW7 1RZ UK


Crowther House 300 n
Queensbrid
ge

72 Seven Seas Hari Kumar 90 Londo OX15 UK


Imports Wadhurst n 4NB
Rd.

The two following SQL statements selects all customers with a City NOT
starting with "b", "s", or "p":

Example
Number of Records: 62

Custome CustomerN ContactNa Address City PostalC Country


rID ame me ode

2 Ana Trujillo Ana Avda. de la Mxico 05021 Mexico


Emparedado Trujillo Constituci D.F.
s y helados n 2222

3 Antonio Antonio Mataderos Mxico 05023 Mexico


Moreno Moreno 2312 D.F.
Taquera

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

5 Berglunds Christina Berguvsvg Lule S-958 Sweden


snabbkp Berglund en 8 22

6 Blauer See Hanna Forsterstr. Mannhei 68306 Germany


Delikatessen Moos 57 m

8 Blido Martn C/ Araquil, Madrid 28023 Spain


Comidas Sommer 67
preparadas

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


Lebihans Bouchers

10 Bottom- Elizabeth 23 Tsawasse T2F Canada


Dollar Lincoln Tsawassen n 8M4
Marketse Blvd.

11 B's Victoria Fauntleroy London EC2 UK


Beverages Ashworth Circus 5NT

13 Centro Francisco Sierras de Mxico 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

16 Consolidate Elizabeth Berkeley London WX1 UK


d Holdings Brown Gardens 12 6LT
Brewery

17 Drachenblut Sven Walserweg Aachen 52066 Germany


Delikatessen Ottlieb 21
d

18 Du monde Janine 67, rue des Nantes 44000 France


entier Labrune Cinquante
Otages

19 Eastern Ann Devon 35 King London WX3 UK


Connection George 6FW

20 Ernst Roland Kirchgasse Graz 8010 Austria


Handel Mendel 6

140
22 FISSA Diego Roel C/ Madrid 28034 Spain
Fabrica Moralzarza
Inter. l, 86
Salchichas
S.A.

23 Folies Martine 184, Lille 59000 France


gourmandes Ranc chausse de
Tournai

25 Frankenvers Peter Berliner Mnchen 80805 Germany


and Franken Platz 43

26 France Carine 54, rue Nantes 44000 France


restauration Schmitt Royale

27 Franchi Paolo Via Monte Torino 10100 Italy


S.p.A. Accorti Bianco 34

28 Furia Lino Jardim das Lisboa 1675 Portugal


Bacalhau e Rodriguez rosas n. 32
Frutos do
Mar

31 Gourmet Andr Av. Brasil, Campinas 04876- Brazil


Lanchonetes Fonseca 442 786

32 Great Lakes Howard 2732 Baker Eugene 97403 USA


Food Snyder Blvd.
Market

33 GROSELL Manuel 5 Ave. Los Caracas 1081 Venezuel


A- Pereira Palos a
Restaurante Grandes

34 Hanari Mario Rua do Rio de 05454- Brazil


Carnes Pontes Pao, 67 Janeiro 876

36 Hungry Yoshi City Center Elgin 97827 USA


Coyote Latimer Plaza 516
Import Main St.
Store

37 Hungry Owl Patricia 8 Cork Ireland


All-Night McKenna Johnstown
Grocers Road

141
38 Island Helen Garden Cowes PO31 UK
Trading Bennett House 7PJ
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

42 Laughing Yoshi 1900 Oak Vancouve V3F Canada


Bacchus Tannamuri St. r 2K1
Wine
Cellars

43 Lazy K John Steel 12 Walla 99362 USA


Kountry Orchestra Walla
Store Terrace

44 Lehmanns Renate Magazinwe Frankfurt 60528 Germany


Marktstand Messner g7 a.M.

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


Delicateses Izquierdo Mayo Margarita a
Porlamar

51 Mre Jean 43 rue St. Montral H1J Canada


Paillarde Fresnire Laurent 1C3

52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 Germany


Gesundkost Feuer

53 North/South Simon South London SW7 UK


Crowther House 300 1RZ
Queensbrid
ge

55 Old World Rene 2743 Anchorag 99508 USA


Delicatessen Phillips Bering St. e

56 Ottilies Henriette Mehrheime Kln 50739 Germany


Kseladen Pfalzheim rstr. 369

142
58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico
Comidas Fernndez Jorge Cash D.F.
clsicas 321

60 Princesa Isabel de Estrada da Lisboa 1756 Portugal


Isabel Castro sade n. 58
Vinhoss

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificador Janeiro 673
a, 12

63 QUICK- Horst Kloss Taucherstra Cunewald 01307 Germany


Stop e 10 e

65 Rattlesnake Paula 2817 Albuquer 87110 USA


Canyon Wilson Milton Dr. que
Grocery

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacaban Janeiro 890
a, 267

68 Richter Michael Grenzacher Genve 1203 Switzerla


Supermarkt Holz weg 237 nd

69 Romero y Alejandra Gran Va, Madrid 28001 Spain


tomillo Camino 1

72 Seven Seas Hari Kumar 90 London OX15 UK


Imports Wadhurst 4NB
Rd.

73 Simons Jytte Vinbltet Kbenhav 1734 Denmark


bistro Petersen 34 n

75 Split Rail Art P.O. Box Lander 82520 USA


Beer & Ale Braunschwe 555
iger

76 Suprmes Pascale Boulevard Charleroi B-6000 Belgium


dlices Cartrain Tirou, 255

143
79 Toms Karin Luisenstr. Mnster 44087 Germany
Spezialitte Josephs 48
n

80 Tortuga Miguel Avda. Mxico 05033 Mexico


Restaurante Angel Azteca 123 D.F.
Paolino

82 Trail's Head Helvetius 722 Kirkland 98034 USA


Gourmet Nagy DaVinci
Provisioners Blvd.

83 Vaffeljernet Palle Ibsen Smagslget rhus 8200 Denmark


45

84 Victuailles Mary 2, rue du Lyon 69004 France


en stock Saveley Commerce

85 Vins et Paul 59 rue de Reims 51100 France


alcools Henriot l'Abbaye
Chevalier

87 Wartian Pirkko Torikatu Oulu 90110 Finland


Herkku Koskitalo 38

88 Wellington Paula Rua do Resende 08737- Brazil


Importadora Parente Mercado, 363
12

90 Wilman Matti Keskuskatu Helsinki 21240 Finland


Kala Karttunen 45

91 Wolski Zbyszek ul. Walla 01-


Filtrowa 012
68

144
Or:

Example
Number of Records: 62

Custome CustomerN ContactNa Address City PostalC Country


rID ame me ode

2 Ana Trujillo Ana Avda. de la Mxico 05021 Mexico


Emparedado Trujillo Constituci D.F.
s y helados n 2222

3 Antonio Antonio Mataderos Mxico 05023 Mexico


Moreno Moreno 2312 D.F.
Taquera

4 Around the Thomas 120 London WA1 UK


Horn Hardy Hanover 1DP
Sq.

5 Berglunds Christina Berguvsvg Lule S-958 Sweden


snabbkp Berglund en 8 22

6 Blauer See Hanna Forsterstr. Mannhei 68306 Germany


Delikatessen Moos 57 m

8 Blido Martn C/ Araquil, Madrid 28023 Spain


Comidas Sommer 67
preparadas

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


Lebihans Bouchers

10 Bottom- Elizabeth 23 Tsawasse T2F Canada


Dollar Lincoln Tsawassen n 8M4
Marketse Blvd.

11 B's Victoria Fauntleroy London EC2 UK


Beverages Ashworth Circus 5NT

13 Centro Francisco Sierras de Mxico 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

16 Consolidate Elizabeth Berkeley London WX1 UK


d Holdings Brown Gardens 12 6LT

145
Brewery

17 Drachenblut Sven Walserweg Aachen 52066 Germany


Delikatessen Ottlieb 21
d

18 Du monde Janine 67, rue des Nantes 44000 France


entier Labrune Cinquante
Otages

19 Eastern Ann Devon 35 King London WX3 UK


Connection George 6FW

20 Ernst Roland Kirchgasse Graz 8010 Austria


Handel Mendel 6

22 FISSA Diego Roel C/ Madrid 28034 Spain


Fabrica Moralzarza
Inter. l, 86
Salchichas
S.A.

23 Folies Martine 184, Lille 59000 France


gourmandes Ranc chausse de
Tournai

25 Frankenvers Peter Berliner Mnchen 80805 Germany


and Franken Platz 43

26 France Carine 54, rue Nantes 44000 France


restauration Schmitt Royale

27 Franchi Paolo Via Monte Torino 10100 Italy


S.p.A. Accorti Bianco 34

28 Furia Lino Jardim das Lisboa 1675 Portugal


Bacalhau e Rodriguez rosas n. 32
Frutos do
Mar

31 Gourmet Andr Av. Brasil, Campinas 04876- Brazil


Lanchonetes Fonseca 442 786

32 Great Lakes Howard 2732 Baker Eugene 97403 USA


Food Snyder Blvd.
Market

146
33 GROSELL Manuel 5 Ave. Los Caracas 1081 Venezuel
A- Pereira Palos a
Restaurante Grandes

34 Hanari Mario Rua do Rio de 05454- Brazil


Carnes Pontes Pao, 67 Janeiro 876

36 Hungry Yoshi City Center Elgin 97827 USA


Coyote Latimer Plaza 516
Import Main St.
Store

37 Hungry Owl Patricia 8 Cork Ireland


All-Night McKenna Johnstown
Grocers Road

38 Island Helen Garden Cowes PO31 UK


Trading Bennett House 7PJ
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

42 Laughing Yoshi 1900 Oak Vancouve V3F Canada


Bacchus Tannamuri St. r 2K1
Wine
Cellars

43 Lazy K John Steel 12 Walla 99362 USA


Kountry Orchestra Walla
Store Terrace

44 Lehmanns Renate Magazinwe Frankfurt 60528 Germany


Marktstand Messner g7 a.M.

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


Delicateses Izquierdo Mayo Margarita a
Porlamar

51 Mre Jean 43 rue St. Montral H1J Canada


Paillarde Fresnire Laurent 1C3

147
52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 Germany
Gesundkost Feuer

53 North/South Simon South London SW7 UK


Crowther House 300 1RZ
Queensbrid
ge

55 Old World Rene 2743 Anchorag 99508 USA


Delicatessen Phillips Bering St. e

56 Ottilies Henriette Mehrheime Kln 50739 Germany


Kseladen Pfalzheim rstr. 369

58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico


Comidas Fernndez Jorge Cash D.F.
clsicas 321

60 Princesa Isabel de Estrada da Lisboa 1756 Portugal


Isabel Castro sade n. 58
Vinhoss

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificador Janeiro 673
a, 12

63 QUICK- Horst Kloss Taucherstra Cunewald 01307 Germany


Stop e 10 e

65 Rattlesnake Paula 2817 Albuquer 87110 USA


Canyon Wilson Milton Dr. que
Grocery

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacaban Janeiro 890
a, 267

68 Richter Michael Grenzacher Genve 1203 Switzerla


Supermarkt Holz weg 237 nd

69 Romero y Alejandra Gran Va, Madrid 28001 Spain


tomillo Camino 1

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

73 Simons Jytte Vinbltet Kbenhav 1734 Denmark


bistro Petersen 34 n

75 Split Rail Art P.O. Box Lander 82520 USA


Beer & Ale Braunschwe 555
iger

76 Suprmes Pascale Boulevard Charleroi B-6000 Belgium


dlices Cartrain Tirou, 255

79 Toms Karin Luisenstr. Mnster 44087 Germany


Spezialitte Josephs 48
n

80 Tortuga Miguel Avda. Mxico 05033 Mexico


Restaurante Angel Azteca 123 D.F.
Paolino

82 Trail's Head Helvetius 722 Kirkland 98034 USA


Gourmet Nagy DaVinci
Provisioners Blvd.

83 Vaffeljernet Palle Ibsen Smagslget rhus 8200 Denmark


45

84 Victuailles Mary 2, rue du Lyon 69004 France


en stock Saveley Commerce

85 Vins et Paul 59 rue de Reims 51100 France


alcools Henriot l'Abbaye
Chevalier

87 Wartian Pirkko Torikatu Oulu 90110 Finland


Herkku Koskitalo 38

88 Wellington Paula Rua do Resende 08737- Brazil


Importadora Parente Mercado, 363
12

90 Wilman Matti Keskuskatu Helsinki 21240 Finland


Kala Karttunen 45

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

SQL IN Operator

The IN Operator

The IN operator allows you to specify multiple values in a WHERE


clause.

SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);

Demo Database

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


database:

CustomerI CustomerNa ContactNa Address City PostalCo Countr


D me me de y

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de la Mxic 05021 Mexico


Emparedados Constituci o D.F.
y helados n 2222

3 Antonio Antonio Mataderos Mxic 05023 Mexico


Moreno Moreno 2312 o D.F.
Taquera

150
4 Around the Thomas 120 Londo WA1 1DP UK
Horn Hardy Hanover n
Sq.

5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden


snabbkp Berglund en 8

IN Operator Example

The following SQL statement selects all customers with a City of "Paris"
or "London":

Example
SQL Statement:
SELECT * FROM Customers
WHERE City IN ('Paris','London');

Edit the SQL Statement, and click "Run SQL" to see the result.

Run SQL
Result:
Number of Records: 8

CustomerI CustomerNa ContactNa Address City PostalCo Countr


D me me de y

4 Around the Thomas 120 Londo WA1 1DP UK


Horn Hardy Hanover n
Sq.

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


Ashworth Circus n

16 Consolidated Elizabeth Berkeley Londo WX1 6LT UK


Holdings Brown Gardens 12 n
Brewery

19 Eastern Ann Devon 35 King Londo WX3 UK


Connection George n 6FW

151
53 North/South Simon South Londo SW7 1RZ UK
Crowther House 300 n
Queensbrid
ge

57 Paris Marie 265, Paris 75012 France


spcialits Bertrand boulevard
Charonne

72 Seven Seas Hari Kumar 90 Londo OX15 UK


Imports Wadhurst n 4NB
Rd.

74 Spcialits du Dominique 25, rue Paris 75016 France


monde Perrier Lauriston

SQL BETWEEN Operator

The BETWEEN operator is used to select values within a range.

The SQL BETWEEN Operator

The BETWEEN operator selects values within a range. The values can be
numbers, text, or dates.

SQL BETWEEN Syntax


SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

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 18
20 bags

152
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 1 2 36 boxes 21.35


Mix

BETWEEN Operator Example

The following SQL statement selects all products with a price BETWEEN
10 and 20:

Example

SQL Statement:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
Number of Records: 29

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 18
20 bags

2 Chang 1 1 24 - 12 oz 19
bottles

153
3 Aniseed Syrup 1 2 12 - 550 ml 10
bottles

15 Genen Shouyu 6 2 24 - 250 ml 15.5


bottles

16 Pavlova 7 3 32 - 500 g 17.45


boxes

21 Sir Rodney's Scones 8 3 24 pkgs. x 4 10


pieces

25 NuNuCa Nu-Nougat- 11 3 20 - 450 g 14


Creme glasses

31 Gorgonzola Telino 14 4 12 - 100 g 12.5


pkgs

34 Sasquatch Ale 16 1 24 - 12 oz 14
bottles

35 Steeleye Stout 16 1 24 - 12 oz 18
bottles

36 Inlagd Sill 17 8 24 - 250 g 19


jars

39 Chartreuse verte 18 1 750 cc per 18


bottle

40 Boston Crab Meat 19 8 24 - 4 oz tins 18.4

42 Singaporean Hokkien 20 5 32 - 1 kg 14
Fried Mee pkgs.

44 Gula Malacca 20 2 20 - 2 kg 19.45


bags

46 Spegesild 21 8 4 - 450 g 12
glasses

48 Chocolade 22 3 10 pkgs. 12.75

49 Maxilaku 23 3 24 - 50 g 20
pkgs.

50 Valkoinen suklaa 23 3 12 - 100 g 16.25


bars

154
57 Ravioli Angelo 26 5 24 - 250 g 19.5
pkgs.

58 Escargots de Bourgogne 27 8 24 pieces 13.25

66 Louisiana Hot Spiced 2 2 24 - 8 oz jars 17


Okra

67 Laughing Lumberjack 16 1 24 - 12 oz 14
Lager bottles

68 Scottish Longbreads 8 3 10 boxes x 8 12.5


pieces

70 Outback Lager 7 1 24 - 355 ml 15


bottles

73 Rd Kaviar 17 8 24 - 150 g 15
jars

74 Longlife Tofu 4 7 5 kg pkg. 10

76 Lakkalikri 23 1 500 ml 18

77 Original Frankfurter 12 2 12 boxes 13


grne Soe

NOT BETWEEN Operator Example

To display the products outside the range of the previous example, use
NOT BETWEEN:

Example

SQL Statement:

SELECT * FROM Products


WHERE Price NOT BETWEEN 10 AND 20;

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
Number of Records: 48

155
ProductID ProductName SupplierID CategoryID Unit Price

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


Seasoning jars

5 Chef Anton's Gumbo 2 2 36 boxes 21.35


Mix

6 Grandma's Boysenberry 3 2 12 - 8 oz 25
Spread jars

7 Uncle Bob's Organic 3 7 12 - 1 lb 30


Dried Pears pkgs.

8 Northwoods Cranberry 3 2 12 - 12 oz 40
Sauce jars

9 Mishi Kobe Niku 4 6 18 - 500 g 97


pkgs.

10 Ikura 4 8 12 - 200 ml 31
jars

11 Queso Cabrales 5 4 1 kg pkg. 21

12 Queso Manchego La 5 4 10 - 500 g 38


Pastora pkgs.

13 Konbu 6 8 2 kg box 6

14 Tofu 6 7 40 - 100 g 23.25


pkgs.

17 Alice Mutton 7 6 20 - 1 kg 39
tins

18 Carnarvon Tigers 7 8 16 kg pkg. 62.5

19 Teatime Chocolate 8 3 10 boxes x 9.2


Biscuits 12 pieces

20 Sir Rodney's 8 3 30 gift 81


Marmalade boxes

22 Gustaf's Knckebrd 9 5 24 - 500 g 21


pkgs.

23 Tunnbrd 9 5 12 - 250 g 9

156
pkgs.

24 Guaran Fantstica 10 1 12 - 355 ml 4.5


cans

26 Gumbr Gummibrchen 11 3 100 - 250 g 31.23


bags

27 Schoggi Schokolade 11 3 100 - 100 g 43.9


pieces

28 Rssle Sauerkraut 12 7 25 - 825 g 45.6


cans

29 Thringer 12 6 50 bags x 123.79


Rostbratwurst 30 sausgs.

30 Nord-Ost Matjeshering 13 8 10 - 200 g 25.89


glasses

32 Mascarpone Fabioli 14 4 24 - 200 g 32


pkgs.

33 Geitost 15 4 500 g 2.5

37 Gravad lax 17 8 12 - 500 g 26


pkgs.

38 Cte de Blaye 18 1 12 - 75 cl 263.5


bottles

41 Jack's New England 19 8 12 - 12 oz 9.65


Clam Chowder cans

43 Ipoh Coffee 20 1 16 - 500 g 46


tins

45 Rgede sild 21 8 1k pkg. 9.5

47 Zaanse koeken 22 3 10 - 4 oz 9.5


boxes

51 Manjimup Dried Apples 24 7 50 - 300 g 53


pkgs.

52 Filo Mix 24 5 16 - 2 kg 7
boxes

157
53 Perth Pasties 24 6 48 pieces 32.8

54 Tourtire 25 6 16 pies 7.45

55 Pt chinois 25 6 24 boxes x 24
2 pies

56 Gnocchi di nonna Alice 26 5 24 - 250 g 38


pkgs.

59 Raclette Courdavault 28 4 5 kg pkg. 55

60 Camembert Pierrot 28 4 15 - 300 g 34


rounds

61 Sirop d'rable 29 2 24 - 500 ml 28.5


bottles

62 Tarte au sucre 29 3 48 pies 49.3

63 Vegie-spread 7 2 15 - 625 g 43.9


jars

64 Wimmers gute 12 5 20 bags x 4 33.25


Semmelkndel pieces

65 Louisiana Fiery Hot 2 2 32 - 8 oz 21.05


Pepper Sauce bottles

69 Gudbrandsdalsost 15 4 10 kg pkg. 36

71 Fltemysost 15 4 10 - 500 g 21.5


pkgs.

72 Mozzarella di Giovanni 14 4 24 - 200 g 34.8


pkgs.

75 Rhnbru Klosterbier 12 1 24 - 0.5 l 7.75


bottles

BETWEEN Operator with IN Example

The following SQL statement selects all products with a price BETWEEN
10 and 20, but products with a CategoryID of 1,2, or 3 should not be
displayed:

Example

158
SQL Statement:
SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3);

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
Number of Records: 9

ProductID ProductName SupplierID CategoryID Unit Price

31 Gorgonzola Telino 14 4 12 - 100 g 12.5


pkgs

36 Inlagd Sill 17 8 24 - 250 g 19


jars

40 Boston Crab Meat 19 8 24 - 4 oz 18.4


tins

42 Singaporean Hokkien 20 5 32 - 1 kg 14
Fried Mee pkgs.

46 Spegesild 21 8 4 - 450 g 12
glasses

57 Ravioli Angelo 26 5 24 - 250 g 19.5


pkgs.

58 Escargots de Bourgogne 27 8 24 pieces 13.25

73 Rd Kaviar 17 8 24 - 150 g 15
jars

74 Longlife Tofu 4 7 5 kg pkg. 10

Sample Table

Below is a selection from the "Orders" table in the Northwind sample


database:

159
OrderID CustomerID EmployeeID OrderDate ShipperID

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 Operator with Date Value Example

The following SQL statement selects all orders with an OrderDate


BETWEEN '04-July-1996' and '09-July-1996':

Example

Number of Records: 5

OrderID CustomerID EmployeeID OrderDate ShipperID

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/8/1996 1

10252 76 4 7/9/1996 2

160
Notice that the BETWEEN operator can produce different result in
different databases!
In some databases, BETWEEN selects fields that are between and
excluding the test values.
In other databases, BETWEEN selects fields that are between and
including the test values.
And in other databases, BETWEEN selects fields between the test values,
including the first test value and excluding the last test value.

Therefore: Check how your database treats the BETWEEN


operator!

SQL Aliases

SQL aliases are used to temporarily rename a table or a column


heading.

SQL Aliases

SQL aliases are used to give a database table, or a column in a table, a


temporary name.

Basically aliases are created to make column names more readable.

SQL Alias Syntax for Columns


SELECT column_name AS alias_name
FROM table_name;

SQL Alias Syntax for Tables


SELECT column_name(s)
FROM table_name AS alias_name;

Demo Database

In this tutorial we will use the well-known Northwind sample database.

161
Below is a selection from the "Customers" table:

CustomerI CustomerNa ContactNa Address City PostalCo Countr


D me me de y

2 Ana Trujillo Ana Trujillo Avda. de Mxic 05021 Mexico


Emparedados la o D.F.
y helados Constituci
n 2222

3 Antonio Antonio Mataderos Mxic 05023 Mexico


Moreno Moreno 2312 o D.F.
Taquera

4 Around the Thomas 120 Londo WA1 1DP UK


Horn Hardy Hanover n
Sq.

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10354 58 8 1996-11-14 3

10355 4 6 1996-11-15 1

10356 86 6 1996-11-18 2

162
Alias Example for Table Columns

The following SQL statement specifies two aliases, one for the
CustomerName column and one for the ContactName column. Tip: It
requires double quotation marks or square brackets if the column name
contains spaces:

Example
SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;

In the following SQL statement we combine four columns (Address, City,


PostalCode, and Country) and create an alias named "Address":

Example
SELECT CustomerName, Address+', '+City+', '+PostalCode+',
'+Country AS Address
FROM Customers;

Note: To get the SQL statement above to work in MySQL use the
following:

SELECT CustomerName, CONCAT(Address,', ',City,', ',PostalCode,',


',Country) AS Address
FROM Customers

Alias Example for Tables

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 have used aliases to make the SQL shorter):

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 same SQL statement without aliases:

163
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName="Around the
Horn" ANDCustomers.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

SQL Joins

SQL joins are used to combine rows from two or more tables.

SQL JOIN

An SQL JOIN clause is used to combine rows from two or more tables,
based on a common field between them.

The most common type of join is: SQL INNER JOIN (simple join). An
SQL INNER JOIN returns all rows from multiple tables where the join
condition is met.

Let's look at a selection from the "Orders" table:

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

164
Then, have a 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 Taquera 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, if we run the following SQL statement (that contains an INNER


JOIN):

Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;

it will produce something like this:

OrderID CustomerName OrderDate

10308 Ana Trujillo Emparedados y helados 9/18/1996

165
10365 Antonio Moreno Taquera 11/27/1996

10383 Around the Horn 12/16/1996

10355 Around the Horn 11/15/1996

10278 Berglunds snabbkp 8/12/1996

Different SQL JOINs

Before we continue with examples, we will list the types of the different
SQL JOINs you can use:

INNER JOIN: Returns all rows when there is at least one match
in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched
rows from the right table
RIGHT JOIN: Return all rows from the right table, and the
matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the
tables

SQL INNER JOIN Keyword

SQL INNER JOIN Keyword

The INNER JOIN keyword selects all rows from both tables as long as
there is a match between the columns in both tables.

SQL INNER JOIN Syntax


SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;

166
or:

SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;

PS! INNER JOIN is the same as JOIN.

Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerI CustomerNa ContactNa Address City PostalCo Countr


D me me de y

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de Mxic 05021 Mexico


Emparedados la o D.F.
y helados Constituci
n 2222

167
3 Antonio Antonio Mataderos Mxic 05023 Mexico
Moreno Moreno 2312 o D.F.
Taquera

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 INNER JOIN Example

The following SQL statement will return all customers with orders:

Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

SQL Statement:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

168
Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
Number of Records: 196

CustomerName OrderID

Ana Trujillo Emparedados y helados 10308

Antonio Moreno Taquera 10365

Around the Horn 10355

Around the Horn 10383

B's Beverages 10289

Berglunds snabbkp 10278

Berglunds snabbkp 10280

Berglunds snabbkp 10384

Blondel pre et fils 10265

Blondel pre et fils 10297

Blondel pre et fils 10360

Blondel pre et fils 10436

Bon app' 10331

Bon app' 10340

Bon app' 10362

Bottom-Dollar Marketse 10389

Bottom-Dollar Marketse 10410

Bottom-Dollar Marketse 10411

Bottom-Dollar Marketse 10431

Blido Comidas preparadas 10326

169
Centro comercial Moctezuma 10259

Chop-suey Chinese 10254

Chop-suey Chinese 10370

Comrcio Mineiro 10290

Consolidated Holdings 10435

Die Wandernde Kuh 10301

Die Wandernde Kuh 10312

Die Wandernde Kuh 10348

Die Wandernde Kuh 10356

Drachenblut Delikatessend 10363

Drachenblut Delikatessend 10391

Du monde entier 10311

Eastern Connection 10364

Eastern Connection 10400

Ernst Handel 10258

Ernst Handel 10263

Ernst Handel 10351

Ernst Handel 10368

Ernst Handel 10382

Ernst Handel 10390

Ernst Handel 10402

Ernst Handel 10403

Ernst Handel 10430

Ernst Handel 10442

Familia Arquibaldo 10347

170
Familia Arquibaldo 10386

Familia Arquibaldo 10414

Folies gourmandes 10408

Folk och f HB 10264

Folk och f HB 10327

Folk och f HB 10378

Folk och f HB 10434

Franchi S.p.A. 10422

Frankenversand 10267

Frankenversand 10337

Frankenversand 10342

Frankenversand 10396

Furia Bacalhau e Frutos do Mar 10328

Furia Bacalhau e Frutos do Mar 10352

GROSELLA-Restaurante 10268

Galera del gastrnomo 10366

Galera del gastrnomo 10426

Godos Cocina Tpica 10303

Gourmet Lanchonetes 10423

HILARIN-Abastos 10257

HILARIN-Abastos 10395

Hanari Carnes 10250

Hanari Carnes 10253

Hungry Coyote Import Store 10375

Hungry Coyote Import Store 10394

171
Hungry Coyote Import Store 10415

Hungry Owl All-Night Grocers 10298

Hungry Owl All-Night Grocers 10309

Hungry Owl All-Night Grocers 10335

Hungry Owl All-Night Grocers 10373

Hungry Owl All-Night Grocers 10380

Hungry Owl All-Night Grocers 10429

Island Trading 10315

Island Trading 10318

Island Trading 10321

Kniglich Essen 10323

Kniglich Essen 10325

LILA-Supermercado 10283

LILA-Supermercado 10296

LILA-Supermercado 10330

LILA-Supermercado 10357

LILA-Supermercado 10381

LINO-Delicateses 10405

La maison d'Asie 10350

La maison d'Asie 10358

La maison d'Asie 10371

La maison d'Asie 10413

La maison d'Asie 10425

Lehmanns Marktstand 10279

Lehmanns Marktstand 10284

172
Lehmanns Marktstand 10343

Lonesome Pine Restaurant 10307

Lonesome Pine Restaurant 10317

Magazzini Alimentari Riuniti 10275

Magazzini Alimentari Riuniti 10300

Magazzini Alimentari Riuniti 10404

Morgenstern Gesundkost 10277

Mre Paillarde 10332

Mre Paillarde 10339

Mre Paillarde 10376

Mre Paillarde 10424

Mre Paillarde 10439

Ocano Atlntico Ltda. 10409

Old World Delicatessen 10260

Old World Delicatessen 10305

Old World Delicatessen 10338

Old World Delicatessen 10441

Ottilies Kseladen 10407

Pericles Comidas clsicas 10322

Pericles Comidas clsicas 10354

Piccolo und mehr 10353

Piccolo und mehr 10392

Piccolo und mehr 10427

Princesa Isabel Vinhoss 10336

Princesa Isabel Vinhoss 10397

173
Princesa Isabel Vinhoss 10433

QUICK-Stop 10273

QUICK-Stop 10285

QUICK-Stop 10286

QUICK-Stop 10313

QUICK-Stop 10345

QUICK-Stop 10361

QUICK-Stop 10418

Que Delcia 10261

Que Delcia 10291

Que Delcia 10379

Que Delcia 10421

Queen Cozinha 10372

Queen Cozinha 10406

Rattlesnake Canyon Grocery 10262

Rattlesnake Canyon Grocery 10272

Rattlesnake Canyon Grocery 10294

Rattlesnake Canyon Grocery 10314

Rattlesnake Canyon Grocery 10316

Rattlesnake Canyon Grocery 10346

Rattlesnake Canyon Grocery 10401

Reggiani Caseifici 10288

Reggiani Caseifici 10428

Reggiani Caseifici 10443

Ricardo Adocicados 10287

174
Ricardo Adocicados 10299

Richter Supermarkt 10255

Richter Supermarkt 10419

Romero y tomillo 10281

Romero y tomillo 10282

Romero y tomillo 10306

Sant Gourmet 10387

Save-a-lot Markets 10324

Save-a-lot Markets 10393

Save-a-lot Markets 10398

Save-a-lot Markets 10440

Seven Seas Imports 10359

Seven Seas Imports 10377

Seven Seas Imports 10388

Simons bistro 10341

Simons bistro 10417

Split Rail Beer & Ale 10271

Split Rail Beer & Ale 10329

Split Rail Beer & Ale 10349

Split Rail Beer & Ale 10369

Split Rail Beer & Ale 10385

Split Rail Beer & Ale 10432

Suprmes dlices 10252

Suprmes dlices 10302

The Big Cheese 10310

175
Toms Spezialitten 10438

Tortuga Restaurante 10276

Tortuga Restaurante 10293

Tortuga Restaurante 10304

Tortuga Restaurante 10319

Tradio Hipermercados 10249

Tradio Hipermercados 10292

Vaffeljernet 10367

Vaffeljernet 10399

Victuailles en stock 10251

Victuailles en stock 10334

Vins et alcools Chevalier 10274

Vins et alcools Chevalier 10295

Wartian Herkku 10266

Wartian Herkku 10270

Wartian Herkku 10320

Wartian Herkku 10333

Wartian Herkku 10412

Wartian Herkku 10416

Wartian Herkku 10437

Wellington Importadora 10256

Wellington Importadora 10420

White Clover Markets 10269

White Clover Markets 10344

Wilman Kala 10248

176
Wolski 10374

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
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 CustomerNa ContactNam Address City PostalCod Country


D me e e

177
1 Alfreds Maria Obere Str. Berlin 12209 German
Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de la Mxic 05021 Mexico


Emparedados Constituci o D.F.
y helados n 2222

3 Antonio Antonio Mataderos Mxic 05023 Mexico


Moreno Moreno 2312 o D.F.
Taquera

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 LEFT JOIN Example

The following SQL statement will select all customers, and any orders
they might have:

178
Example

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

Number of Records: 213

CustomerName OrderID

Alfreds Futterkiste null

Ana Trujillo Emparedados y helados 10308

Antonio Moreno Taquera 10365

Around the Horn 10355

Around the Horn 10383

B's Beverages 10289

Berglunds snabbkp 10278

Berglunds snabbkp 10280

Berglunds snabbkp 10384

Blauer See Delikatessen null

Blondel pre et fils 10265

Blondel pre et fils 10297

Blondel pre et fils 10360

Blondel pre et fils 10436

Bon app' 10331

Bon app' 10340

Bon app' 10362

Bottom-Dollar Marketse 10389

Bottom-Dollar Marketse 10410

Bottom-Dollar Marketse 10411

179
Bottom-Dollar Marketse 10431

Blido Comidas preparadas 10326

Cactus Comidas para llevar null

Centro comercial Moctezuma 10259

Chop-suey Chinese 10254

Chop-suey Chinese 10370

Comrcio Mineiro 10290

Consolidated Holdings 10435

Die Wandernde Kuh 10301

Die Wandernde Kuh 10312

Die Wandernde Kuh 10348

Die Wandernde Kuh 10356

Drachenblut Delikatessend 10363

Drachenblut Delikatessend 10391

Du monde entier 10311

Eastern Connection 10364

Eastern Connection 10400

Ernst Handel 10258

Ernst Handel 10263

Ernst Handel 10351

Ernst Handel 10368

Ernst Handel 10382

Ernst Handel 10390

Ernst Handel 10402

Ernst Handel 10403

Ernst Handel 10430

180
Ernst Handel 10442

FISSA Fabrica Inter. Salchichas S.A. null

Familia Arquibaldo 10347

Familia Arquibaldo 10386

Familia Arquibaldo 10414

Folies gourmandes 10408

Folk och f HB 10264

Folk och f HB 10327

Folk och f HB 10378

Folk och f HB 10434

France restauration null

Franchi S.p.A. 10422

Frankenversand 10267

Frankenversand 10337

Frankenversand 10342

Frankenversand 10396

Furia Bacalhau e Frutos do Mar 10328

Furia Bacalhau e Frutos do Mar 10352

GROSELLA-Restaurante 10268

Galera del gastrnomo 10366

Galera del gastrnomo 10426

Godos Cocina Tpica 10303

Gourmet Lanchonetes 10423

Great Lakes Food Market null

HILARIN-Abastos 10257

HILARIN-Abastos 10395

181
Hanari Carnes 10250

Hanari Carnes 10253

Hungry Coyote Import Store 10375

Hungry Coyote Import Store 10394

Hungry Coyote Import Store 10415

Hungry Owl All-Night Grocers 10298

Hungry Owl All-Night Grocers 10309

Hungry Owl All-Night Grocers 10335

Hungry Owl All-Night Grocers 10373

Hungry Owl All-Night Grocers 10380

Hungry Owl All-Night Grocers 10429

Island Trading 10315

Island Trading 10318

Island Trading 10321

Kniglich Essen 10323

Kniglich Essen 10325

LILA-Supermercado 10283

LILA-Supermercado 10296

LILA-Supermercado 10330

LILA-Supermercado 10357

LILA-Supermercado 10381

LINO-Delicateses 10405

La corne d'abondance null

La maison d'Asie 10350

La maison d'Asie 10358

La maison d'Asie 10371

182
La maison d'Asie 10413

La maison d'Asie 10425

Laughing Bacchus Wine Cellars null

Lazy K Kountry Store null

Lehmanns Marktstand 10279

Lehmanns Marktstand 10284

Lehmanns Marktstand 10343

Let's Stop N Shop null

Lonesome Pine Restaurant 10307

Lonesome Pine Restaurant 10317

Magazzini Alimentari Riuniti 10275

Magazzini Alimentari Riuniti 10300

Magazzini Alimentari Riuniti 10404

Maison Dewey null

Morgenstern Gesundkost 10277

Mre Paillarde 10332

Mre Paillarde 10339

Mre Paillarde 10376

Mre Paillarde 10424

Mre Paillarde 10439

North/South null

Ocano Atlntico Ltda. 10409

Old World Delicatessen 10260

Old World Delicatessen 10305

Old World Delicatessen 10338

Old World Delicatessen 10441

183
Ottilies Kseladen 10407

Paris spcialits null

Pericles Comidas clsicas 10322

Pericles Comidas clsicas 10354

Piccolo und mehr 10353

Piccolo und mehr 10392

Piccolo und mehr 10427

Princesa Isabel Vinhoss 10336

Princesa Isabel Vinhoss 10397

Princesa Isabel Vinhoss 10433

QUICK-Stop 10273

QUICK-Stop 10285

QUICK-Stop 10286

QUICK-Stop 10313

QUICK-Stop 10345

QUICK-Stop 10361

QUICK-Stop 10418

Que Delcia 10261

Que Delcia 10291

Que Delcia 10379

Que Delcia 10421

Queen Cozinha 10372

Queen Cozinha 10406

Rancho grande null

Rattlesnake Canyon Grocery 10262

Rattlesnake Canyon Grocery 10272

184
Rattlesnake Canyon Grocery 10294

Rattlesnake Canyon Grocery 10314

Rattlesnake Canyon Grocery 10316

Rattlesnake Canyon Grocery 10346

Rattlesnake Canyon Grocery 10401

Reggiani Caseifici 10288

Reggiani Caseifici 10428

Reggiani Caseifici 10443

Ricardo Adocicados 10287

Ricardo Adocicados 10299

Richter Supermarkt 10255

Richter Supermarkt 10419

Romero y tomillo 10281

Romero y tomillo 10282

Romero y tomillo 10306

Sant Gourmet 10387

Save-a-lot Markets 10324

Save-a-lot Markets 10393

Save-a-lot Markets 10398

Save-a-lot Markets 10440

Seven Seas Imports 10359

Seven Seas Imports 10377

Seven Seas Imports 10388

Simons bistro 10341

Simons bistro 10417

Split Rail Beer & Ale 10271

185
Split Rail Beer & Ale 10329

Split Rail Beer & Ale 10349

Split Rail Beer & Ale 10369

Split Rail Beer & Ale 10385

Split Rail Beer & Ale 10432

Spcialits du monde null

Suprmes dlices 10252

Suprmes dlices 10302

The Big Cheese 10310

The Cracker Box null

Toms Spezialitten 10438

Tortuga Restaurante 10276

Tortuga Restaurante 10293

Tortuga Restaurante 10304

Tortuga Restaurante 10319

Tradio Hipermercados 10249

Tradio Hipermercados 10292

Trail's Head Gourmet Provisioners null

Vaffeljernet 10367

Vaffeljernet 10399

Victuailles en stock 10251

Victuailles en stock 10334

Vins et alcools Chevalier 10274

Vins et alcools Chevalier 10295

Wartian Herkku 10266

Wartian Herkku 10270

186
Wartian Herkku 10320

Wartian Herkku 10333

Wartian Herkku 10412

Wartian Herkku 10416

Wartian Herkku 10437

Wellington Importadora 10256

Wellington Importadora 10420

White Clover Markets 10269

White Clover Markets 10344

Wilman Kala 10248

Wolski 10374

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

The RIGHT JOIN keyword returns all rows from the right table (table2),
with the matching rows in the left table (table1). The result is NULL in
the left side when there is no match.

SQL RIGHT JOIN Syntax


SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;

or:

SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;

PS! In some databases RIGHT JOIN is called RIGHT OUTER JOIN.


187
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 "Employees" table:

EmployeeID LastName FirstName BirthDate Photo Notes

1 Davolio Nancy 12/8/1968 EmpID1.pic Education includes a


BA in
psychology.....

188
2 Fuller Andrew 2/19/1952 EmpID2.pic Andrew received his
BTS commercial
and....

3 Leverling Janet 8/30/1963 EmpID3.pic Janet has a BS


degree in
chemistry....

SQL RIGHT JOIN Example

The following SQL statement will return all employees, and any orders
they have placed:

Example
Note: The RIGHT JOIN keyword returns all the rows from the right table
(Employees), even if there ar

SQL FULL OUTER JOIN Keyword

The FULL OUTER JOIN keyword returns all rows from the left table
(table1) and from the right table (table2).

The FULL OUTER JOIN keyword combines the result of both LEFT and
RIGHT joins.

SQL FULL OUTER JOIN Syntax


SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;

189
Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerI CustomerNa ContactNa Address City PostalCo Countr


D me me de y

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de Mxic 05021 Mexico


Emparedados la o D.F.
y helados Constituci
n 2222

3 Antonio Antonio Mataderos Mxic 05023 Mexico


Moreno Moreno 2312 o D.F.
Taquera

And a selection from the "Orders" table:

190
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

Ana Trujillo Emparedados y helados 10308

191
Antonio Moreno Taquera 10365

10382

10351

Note: The FULL OUTER JOIN keyword returns all the rows from the left
table (Customers), and all the rows from the right table (Orders). 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 CustomerNa ContactNam Address City PostalCod Country


D me e e

192
1 Alfreds Maria Obere Str. Berlin 12209 German
Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de la Mxic 05021 Mexico


Emparedados Constituci o D.F.
y helados n 2222

3 Antonio Antonio Mataderos Mxic 05023 Mexico


Moreno Moreno 2312 o D.F.
Taquera

SQL Self JOIN Example

The following SQL statement matches customers that are from the same
city:

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;

Number of Records: 88

CustomerName1 CustomerName2 City

Cactus Comidas para llevar Ocano Atlntico Ltda. Buenos


Aires

Cactus Comidas para llevar Rancho grande Buenos


Aires

Ocano Atlntico Ltda. Cactus Comidas para llevar Buenos


Aires

193
Ocano Atlntico Ltda. Rancho grande Buenos
Aires

Rancho grande Cactus Comidas para llevar Buenos


Aires

Rancho grande Ocano Atlntico Ltda. Buenos


Aires

Furia Bacalhau e Frutos do Mar Princesa Isabel Vinhoss Lisboa

Princesa Isabel Vinhoss Furia Bacalhau e Frutos do Mar Lisboa

Around the Horn B's Beverages London

Around the Horn Consolidated Holdings London

Around the Horn Eastern Connection London

Around the Horn North/South London

Around the Horn Seven Seas Imports London

B's Beverages Around the Horn London

B's Beverages Consolidated Holdings London

B's Beverages Eastern Connection London

B's Beverages North/South London

B's Beverages Seven Seas Imports London

Consolidated Holdings Around the Horn London

Consolidated Holdings B's Beverages London

Consolidated Holdings Eastern Connection London

Consolidated Holdings North/South London

Consolidated Holdings Seven Seas Imports London

Eastern Connection Around the Horn London

Eastern Connection B's Beverages London

Eastern Connection Consolidated Holdings London

Eastern Connection North/South London

194
Eastern Connection Seven Seas Imports London

North/South Around the Horn London

North/South B's Beverages London

North/South Consolidated Holdings London

North/South Eastern Connection London

North/South Seven Seas Imports London

Seven Seas Imports Around the Horn London

Seven Seas Imports B's Beverages London

Seven Seas Imports Consolidated Holdings London

Seven Seas Imports Eastern Connection London

Seven Seas Imports North/South London

Blido Comidas preparadas FISSA Fabrica Inter. Salchichas Madrid


S.A.

Blido Comidas preparadas Romero y tomillo Madrid

FISSA Fabrica Inter. Salchichas Blido Comidas preparadas Madrid


S.A.

FISSA Fabrica Inter. Salchichas Romero y tomillo Madrid


S.A.

Romero y tomillo Blido Comidas preparadas Madrid

Romero y tomillo FISSA Fabrica Inter. Salchichas Madrid


S.A.

Ana Trujillo Emparedados y Antonio Moreno Taquera Mxico D.F.


helados

Ana Trujillo Emparedados y Centro comercial Moctezuma Mxico D.F.


helados

Ana Trujillo Emparedados y Pericles Comidas clsicas Mxico D.F.


helados

Ana Trujillo Emparedados y Tortuga Restaurante Mxico D.F.


helados

Antonio Moreno Taquera Ana Trujillo Emparedados y Mxico D.F.

195
helados

Antonio Moreno Taquera Centro comercial Moctezuma Mxico D.F.

Antonio Moreno Taquera Pericles Comidas clsicas Mxico D.F.

Antonio Moreno Taquera Tortuga Restaurante Mxico D.F.

Centro comercial Moctezuma Ana Trujillo Emparedados y Mxico D.F.


helados

Centro comercial Moctezuma Antonio Moreno Taquera Mxico D.F.

Centro comercial Moctezuma Pericles Comidas clsicas Mxico D.F.

Centro comercial Moctezuma Tortuga Restaurante Mxico D.F.

Pericles Comidas clsicas Ana Trujillo Emparedados y Mxico D.F.


helados

Pericles Comidas clsicas Antonio Moreno Taquera Mxico D.F.

Pericles Comidas clsicas Centro comercial Moctezuma Mxico D.F.

Pericles Comidas clsicas Tortuga Restaurante Mxico D.F.

Tortuga Restaurante Ana Trujillo Emparedados y Mxico D.F.


helados

Tortuga Restaurante Antonio Moreno Taquera Mxico D.F.

Tortuga Restaurante Centro comercial Moctezuma Mxico D.F.

Tortuga Restaurante Pericles Comidas clsicas Mxico D.F.

Du monde entier France restauration Nantes

France restauration Du monde entier Nantes

Paris spcialits Spcialits du monde Paris

Spcialits du monde Paris spcialits Paris

Lonesome Pine Restaurant The Big Cheese Portland

The Big Cheese Lonesome Pine Restaurant Portland

Hanari Carnes Que Delcia Rio de


Janeiro

Hanari Carnes Ricardo Adocicados Rio de

196
Janeiro

Que Delcia Hanari Carnes Rio de


Janeiro

Que Delcia Ricardo Adocicados Rio de


Janeiro

Ricardo Adocicados Hanari Carnes Rio de


Janeiro

Ricardo Adocicados Que Delcia Rio de


Janeiro

Comrcio Mineiro Familia Arquibaldo So Paulo

Comrcio Mineiro Queen Cozinha So Paulo

Comrcio Mineiro Tradio Hipermercados So Paulo

Familia Arquibaldo Comrcio Mineiro So Paulo

Familia Arquibaldo Queen Cozinha So Paulo

Familia Arquibaldo Tradio Hipermercados So Paulo

Queen Cozinha Comrcio Mineiro So Paulo

Queen Cozinha Familia Arquibaldo So Paulo

Queen Cozinha Tradio Hipermercados So Paulo

Tradio Hipermercados Comrcio Mineiro So Paulo

Tradio Hipermercados Familia Arquibaldo So Paulo

Tradio Hipermercados Queen Cozinha So Paulo

SQL UNION Operator

The SQL UNION operator combines the result of two or more SELECT
statements.

The SQL UNION Operator

The UNION operator is used to combine the result-set of two or more


SELECT statements.

197
Notice that each SELECT statement within the UNION must have the
same number of columns. The columns must also have similar data
types. Also, the columns in each SELECT statement must be in the same
order.

SQL UNION Syntax


SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

Note: The UNION operator selects only distinct values by default. To


allow duplicate values, use the ALL keyword with UNION.

SQL UNION ALL Syntax


SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

PS: The column names in the result-set of a UNION 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:

CustomerI CustomerNa ContactNa Address City PostalCo Countr


D me me de y

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de Mxic 05021 Mexico


Emparedados la o D.F.
y helados Constituci
n 2222

198
3 Antonio Antonio Mataderos Mxic 05023 Mexico
Moreno Moreno 2312 o D.F.
Taquera

And a selection from the "Suppliers" table:

SupplierI SupplierNam ContactNam Addres City PostalCod Countr


D e e s e y

1 Exotic Liquid Charlotte 49 Londo EC1 4SD UK


Cooper Gilbert n
St.

2 New Orleans Shelley P.O. New 70117 USA


Cajun Burke Box Orlean
Delights 78934 s

3 Grandma Regina 707 Ann 48104 USA


Kelly's Murphy Oxford Arbor
Homestead Rd.

SQL UNION Example

The following SQL statement selects all the different cities (only distinct
values) from the "Customers" and the "Suppliers" tables:

Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

199
Number of Records: 94

City

Aachen

Albuquerque

Anchorage

Ann Arbor

Annecy

Barcelona

Barquisimeto

Bend

Bergamo

Berlin

Bern

Boise

Boston

Brandenburg

Bruxelles

Brcke

Buenos Aires

Butte

Campinas

Caracas

Charleroi

Cork

Cowes

200
Cunewalde

Cuxhaven

Elgin

Eugene

Frankfurt

Frankfurt a.M.

Genve

Graz

Gteborg

Helsinki

I. de Margarita

Kirkland

Kln

Kbenhavn

Lander

Lappeenranta

Leipzig

Lille

Lisboa

London

Londona

Lule

Lyngby

Lyon

Madrid

Manchester

201
Mannheim

Marseille

Melbourne

Montceau

Montral

Mxico D.F.

Mnchen

Mnster

Nantes

New Orleans

Osaka

Oulu

Oviedo

Paris

Portland

Ravenna

Reggio Emilia

Reims

Resende

Rio de Janeiro

Salerno

Salzburg

San Cristbal

San Francisco

Sandvika

Seattle

202
Sevilla

Singapore

Stavern

Ste-Hyacinthe

Stockholm

Strasbourg

Stuttgart

Sydney

So Paulo

Tokyo

Torino

Toulouse

Tsawassen

Vancouver

Versailles

Walla

Walla Walla

Zaandam

rhus

Note: UNION cannot be used to list ALL cities from the two tables. If
several customers and suppliers share the same city, each city will only
be listed once. UNION selects only distinct values. Use UNION ALL to
also select duplicate values!

SQL UNION ALL Example

The following SQL statement uses UNION ALL to select all (duplicate
values also) cities from the "Customers" and "Suppliers" tables:

203
Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
Number of Records: 120

City

Aachen

Albuquerque

Anchorage

Ann Arbor

Annecy

Barcelona

Barquisimeto

Bend

Bergamo

Berlin

Berlin

Bern

Boise

Boston

Brandenburg

Bruxelles

Brcke

Buenos Aires

Buenos Aires

Buenos Aires

204
Butte

Campinas

Caracas

Charleroi

Cork

Cowes

Cunewalde

Cuxhaven

Elgin

Eugene

Frankfurt

Frankfurt a.M.

Genve

Graz

Gteborg

Helsinki

I. de Margarita

Kirkland

Kln

Kbenhavn

Lander

Lappeenranta

Leipzig

Lille

Lisboa

Lisboa

205
London

London

London

London

London

London

Londona

Lule

Lyngby

Lyon

Madrid

Madrid

Madrid

Manchester

Mannheim

Marseille

Melbourne

Montceau

Montral

Montral

Mxico D.F.

Mxico D.F.

Mxico D.F.

Mxico D.F.

Mxico D.F.

Mnchen

206
Mnster

Nantes

Nantes

New Orleans

Osaka

Oulu

Oviedo

Paris

Paris

Paris

Portland

Portland

Ravenna

Reggio Emilia

Reims

Resende

Rio de Janeiro

Rio de Janeiro

Rio de Janeiro

Salerno

Salzburg

San Cristbal

San Francisco

Sandvika

Seattle

Sevilla

207
Singapore

Stavern

Ste-Hyacinthe

Stockholm

Strasbourg

Stuttgart

Sydney

So Paulo

So Paulo

So Paulo

So Paulo

So Paulo

Tokyo

Torino

Toulouse

Tsawassen

Vancouver

Versailles

Walla

Walla Walla

Zaandam

rhus

SQL UNION With WHERE

The following SQL statement selects all the different German cities (only
distinct values) from "Customers" and "Suppliers":

208
Example

SELECT City, Country FROM Customers


WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

Number of Records: 13

City Country

Aachen Germany

Berlin Germany

Brandenburg Germany

Cunewalde Germany

Cuxhaven Germany

Frankfurt Germany

Frankfurt a.M. Germany

Kln Germany

Leipzig Germany

Mannheim Germany

Mnchen Germany

Mnster Germany

Stuttgart Germany

SQL UNION ALL With WHERE

The following SQL statement uses UNION ALL to select all (duplicate
values also) German cities from the "Customers" and "Suppliers"
tables:

Example

209
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Number of Records: 14

City Country

Aachen Germany

Berlin Germany

Berlin Germany

Brandenburg Germany

Cunewalde Germany

Cuxhaven Germany

Frankfurt Germany

Frankfurt a.M. Germany

Kln Germany

Leipzig Germany

Mannheim Germany

Mnchen Germany

Mnster Germany

Stuttgart Germany

Another UNION Example

The following SQL statement lists all customers and suppliers:

Example

SELECT 'Customer' As Type, ContactName, City, Country


FROM Customers
UNION

210
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;

Number of Records: 120

Type ContactName City Country

Customer Alejandra Camino Madrid Spain

Customer Alexander Feuer Leipzig Germany

Customer Ana Trujillo Mxico D.F. Mexico

Customer Anabela Domingues So Paulo Brazil

Customer Andr Fonseca Campinas Brazil

Customer Ann Devon London UK

Customer Annette Roulet Toulouse France

Customer Antonio Moreno Mxico D.F. Mexico

Customer Aria Cruz So Paulo Brazil

Customer Art Braunschweiger Lander USA

Customer Bernardo Batista Rio de Janeiro Brazil

Customer Carine Schmitt Nantes France

Customer Carlos Gonzlez Barquisimeto Venezuela

Customer Carlos Hernndez San Cristbal Venezuela

Customer Catherine Dewey Bruxelles Belgium

Customer Christina Berglund Lule Sweden

Customer Daniel Tonini Versailles France

Customer Diego Roel Madrid Spain

Customer Dominique Perrier Paris France

Customer Eduardo Saavedra Barcelona Spain

Customer Elizabeth Brown London UK

Customer Elizabeth Lincoln Tsawassen Canada

211
Customer Felipe Izquierdo I. de Margarita Venezuela

Customer Fran Wilson Portland USA

Customer Francisco Chang Mxico D.F. Mexico

Customer Frdrique Citeaux Strasbourg France

Customer Georg Pipps Salzburg Austria

Customer Giovanni Rovelli Bergamo Italy

Customer Guillermo Fernndez Mxico D.F. Mexico

Customer Hanna Moos Mannheim Germany

Customer Hari Kumar London UK

Customer Helen Bennett Cowes UK

Customer Helvetius Nagy Kirkland USA

Customer Henriette Pfalzheim Kln Germany

Customer Horst Kloss Cunewalde Germany

Customer Howard Snyder Eugene USA

Customer Isabel de Castro Lisboa Portugal

Customer Jaime Yorres San Francisco USA

Customer Janete Limeira Rio de Janeiro Brazil

Customer Janine Labrune Nantes France

Customer Jean Fresnire Montral Canada

Customer John Steel Walla Walla USA

Customer Jonas Bergulfsen Stavern Norway

Customer Jose Pavarotti Boise USA

Customer Jos Pedro Freyre Sevilla Spain

Customer Jytte Petersen Kbenhavn Denmark

Customer Karin Josephs Mnster Germany

Customer Karl Jablonski Seattle USA

212
Customer Laurence Lebihans Marseille France

Customer Lino Rodriguez Lisboa Portugal

Customer Liu Wong Butte USA

Customer Liz Nixon Portland USA

Customer Lcia Carvalho So Paulo Brazil

Customer Manuel Pereira Caracas Venezuela

Customer Maria Anders Berlin Germany

Customer Maria Larsson Brcke Sweden

Customer Marie Bertrand Paris France

Customer Mario Pontes Rio de Janeiro Brazil

Customer Martine Ranc Lille France

Customer Martn Sommer Madrid Spain

Customer Mary Saveley Lyon France

Customer Matti Karttunen Helsinki Finland

Customer Maurizio Moroni Reggio Emilia Italy

Customer Michael Holz Genve Switzerland

Customer Miguel Angel Paolino Mxico D.F. Mexico

Customer Palle Ibsen rhus Denmark

Customer Paolo Accorti Torino Italy

Customer Pascale Cartrain Charleroi Belgium

Customer Patricia McKenna Cork Ireland

Customer Patricio Simpson Buenos Aires Argentina

Customer Paul Henriot Reims France

Customer Paula Parente Resende Brazil

Customer Paula Wilson Albuquerque USA

Customer Pedro Afonso So Paulo Brazil

213
Customer Peter Franken Mnchen Germany

Customer Philip Cramer Brandenburg Germany

Customer Pirkko Koskitalo Oulu Finland

Customer Renate Messner Frankfurt a.M. Germany

Customer Rene Phillips Anchorage USA

Customer Rita Mller Stuttgart Germany

Customer Roland Mendel Graz Austria

Customer Sergio Gutirrez Buenos Aires Argentina

Customer Simon Crowther London UK

Customer Sven Ottlieb Aachen Germany

Customer Thomas Hardy London UK

Customer Victoria Ashworth London UK

Customer Yang Wang Bern Switzerland

Customer Yoshi Latimer Elgin USA

Customer Yoshi Tannamuri Vancouver Canada

Customer Yvonne Moncada Buenos Aires Argentina

Customer Zbyszek Walla Poland

Supplier Anne Heikkonen Lappeenranta Finland

Supplier Antonio del Valle Saavedra Oviedo Spain

Supplier Beate Vileid Sandvika Norway

Supplier Carlos Diaz So Paulo Brazil

Supplier Chandra Leka Singapore Singapore

Supplier Chantal Goulet Ste-Hyacinthe Canada

Supplier Charlotte Cooper Londona UK

Supplier Cheryl Saylor Bend USA

Supplier Dirk Luchte Zaandam Netherlands

214
Supplier Eliane Noz Annecy France

Supplier Elio Rossi Ravenna Italy

Supplier Giovanni Giudici Salerno Italy

Supplier Guylne Nodier Paris France

Supplier Ian Devling Melbourne Australia

Supplier Jean-Guy Lauzon Montral Canada

Supplier Lars Peterson Gteborg Sweden

Supplier Marie Delamare Montceau France

Supplier Martin Bein Frankfurt Germany

Supplier Mayumi Ohno Osaka Japan

Supplier Michael Bjrn Stockholm Sweden

Supplier Niels Petersen Lyngby Denmark

Supplier Peter Wilson Manchester UK

Supplier Petra Winkler Berlin Germany

Supplier Regina Murphy Ann Arbor USA

Supplier Robb Merchant Boston USA

Supplier Shelley Burke New Orleans USA

Supplier Sven Petersen Cuxhaven Germany

Supplier Wendy Mackenzie Sydney Australia

Supplier Yoshi Nagase Tokyo Japan

SQL GROUP BY Statement

The SQL GROUP BY Statement

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.

215
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:

CustomerI CustomerNa ContactNa Address City PostalCod Country


D me me e

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de la Mxic 05021 Mexico


Emparedados Constituci o D.F.
y helados n 2222

3 Antonio Antonio Mataderos Mxic 05023 Mexico


Moreno Moreno 2312 o D.F.
Taquera

4 Around the Thomas 120 Londo WA1 1DP UK


Horn Hardy Hanover Sq. n

216
5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden
snabbkp Berglund en 8

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;

Number of Records: 21

COUNT(CustomerID) Country

3 Argentina

2 Austria

2 Belgium

9 Brazil

3 Canada

2 Denmark

2 Finland

11 France

11 Germany

1 Ireland

3 Italy

5 Mexico

1 Norway

1 Poland

217
2 Portugal

5 Spain

2 Sweden

2 Switzerland

7 UK

13 USA

4 Venezuela

The following SQL statement lists the number of customers in each


country, sorted high to low:

Example

SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

Number of Records: 21

COUNT(CustomerID) Country

13 USA

11 France

11 Germany

9 Brazil

7 UK

5 Mexico

5 Spain

4 Venezuela

3 Argentina

3 Canada

218
3 Italy

2 Austria

2 Belgium

2 Denmark

2 Finland

2 Portugal

2 Sweden

2 Switzerland

1 Ireland

1 Norway

1 Poland

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:

219
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 NumberOfOrde


rs FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;

Number of Records: 3

ShipperName NumberOfOrders

Federal Shipping 68

Speedy Express 54

United Package 74

220
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

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:

CustomerI CustomerNa ContactNa Address City PostalCod Country


D me me e

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de la Mxic 05021 Mexico


Emparedados Constituci o D.F.
y helados n 2222

3 Antonio Antonio Mataderos Mxic 05023 Mexico


Moreno Moreno 2312 o D.F.
Taquera

221
4 Around the Thomas 120 Londo WA1 1DP UK
Horn Hardy Hanover Sq. n

5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden


snabbkp Berglund en 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;

Number of Records: 5

COUNT(CustomerID) Country

9 Brazil

11 France

11 Germany

7 UK

13 USA

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

222
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;

Number of Records: 5

COUNT(CustomerID) Country

13 USA

11 France

11 Germany

9 Brazil

7 UK

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:

223
EmployeeID LastName FirstName BirthDate Photo Notes

1 Davolio Nancy 1968-12- EmpID1.pic Education includes a


08 BA....

2 Fuller Andrew 1952-02- EmpID2.pic Andrew received his


19 BTS....

3 Leverling Janet 1963-08- EmpID3.pic Janet has a BS


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

Number of Records: 8

LastName NumberOfOrders

Buchanan 11

Callahan 27

Davolio 29

Fuller 20

224
King 14

Leverling 31

Peacock 40

Suyama 18

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;

Number of Records: 1

LastName NumberOfOrders

Davolio 29

SQL EXISTS Operator

The SQL EXISTS Operator

The EXISTS operator is used to test for the existence of any record in a
subquery.

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

225
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

And a selection from the "Suppliers" table:

SupplierI SupplierNam ContactNam Address City PostalCod Countr


D e e e y

226
1 Exotic Liquid Charlotte 49 Gilbert Londo EC1 4SD UK
Cooper St. n

2 New Orleans Shelley Burke P.O. Box New 70117 USA


Cajun 78934 Orlean
Delights s

3 Grandma Regina 707 Oxford Ann 48104 USA


Kelly's Murphy Rd. Arbor
Homestead

4 Tokyo Yoshi Nagase 9-8 Tokyo 100 Japan


Traders Sekimai
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 SupplierId =
Suppliers.supplierId AND Price < 20);

Number of Records: 24

SupplierName

Exotic Liquid

227
New Orleans Cajun Delights

Tokyo Traders

Mayumi's

Pavlova, Ltd.

Specialty Biscuits, Ltd.

PB Knckebrd AB

Refrescos Americanas LTDA

Heli Swaren GmbH & Co. KG

Plutzer Lebensmittelgromrkte AG

Formaggi Fortini s.r.l.

Norske Meierier

Bigfoot Breweries

Svensk Sjfda AB

Aux joyeux ecclsiastiques

New England Seafood Cannery

Leka Trading

Lyngbysild

Zaanse Snoepfabriek

Karkki Oy

G'day, Mate

Ma Maison

Pasta Buttini s.r.l.

Escargots Nouveaux

The following SQL statement returns TRUE and lists the suppliers with a
product price equal to 22:

228
Example

SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE SupplierId =
Suppliers.supplierId AND Price = 22);

Number of Records: 1

SupplierName

New Orleans Cajun Delights

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.

Note: The examples in this chapter will not work in Chrome,


Safari and Opera!

ANY and ALL are not supported in Web SQL databases. Chrome, Safari
and Opera are using Web SQL in our examples.

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

229
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 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

And a selection from the "OrderDetails" table:

OrderDetailID OrderID ProductID Quantity

230
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 productnames 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);

Number of Records: 1

ProductName

Singaporean Hokkien Fried Mee

231
The following SQL statement returns TRUE and lists the productnames 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);

Number of Records: 1

ProductName

Steeleye Stout

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 productnames if
ALL the records in the OrderDetails table has quantity = 10:

Example

SELECT ProductName
FROM Products
WHERE ProductID
= ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);

Number of Records: 1

ProductName

Singaporean Hokkien Fried Mee

232
SQL SELECT INTO Statement

With SQL, you can copy information from one table into another.

The SELECT INTO statement copies data from one table and inserts it
into a new table.

The SQL SELECT INTO Statement

The SELECT INTO statement selects data from one table and inserts it
into a new table.

SQL SELECT INTO Syntax

We can copy all columns into the new table:

SELECT *
INTO newtable [IN externaldb]
FROM table1;

Or we can copy only the columns we want into the new table:

SELECT column_name(s)
INTO newtable [IN externaldb]
FROM table1;

The new table will be created with the column-names and types as
defined in the SELECT statement. You can apply new names using the
AS clause.

SQL SELECT INTO Examples

Create a backup copy of Customers:

SELECT *
INTO CustomersBackup2013
FROM Customers;

Use the IN clause to copy the table into another database:

SELECT *
INTO CustomersBackup2013 IN 'Backup.mdb'
FROM Customers;

233
Copy only a few columns into the new table:

SELECT CustomerName, ContactName


INTO CustomersBackup2013
FROM Customers;

Copy only the German customers into the new table:

SELECT *
INTO CustomersBackup2013
FROM Customers
WHERE Country='Germany';

Copy data from more than one table into the new table:

SELECT Customers.CustomerName, Orders.OrderID


INTO CustomersOrderBackup2013
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID;

Tip: The SELECT INTO statement 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 table1
WHERE 1=0;

SQL INSERT INTO SELECT Statement

With SQL, you can copy information from one table into another.

The INSERT INTO SELECT statement copies data from one table and
inserts it into an existing table.

The SQL INSERT INTO SELECT Statement

The INSERT INTO SELECT statement selects data from one table and
inserts it into an existing table. Any existing rows in the target table are
unaffected.

234
SQL INSERT INTO SELECT Syntax

We can copy all columns from one table to another, existing table:

INSERT INTO table2


SELECT * FROM table1;

Or we can copy only the columns we want to into another, existing


table:

INSERT INTO table2


(column_name(s))
SELECT column_name(s)
FROM table1;

Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerI CustomerNa ContactNa Address City PostalCo Countr


D me me de y

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de Mxic 05021 Mexico


Emparedados la o D.F.
y helados Constituci
n 2222

3 Antonio Antonio Mataderos Mxic 05023 Mexico


Moreno Moreno 2312 o D.F.
Taquera

235
And a selection from the "Suppliers" table:

SupplierI SupplierNa ContactNa Addres City Posta Countr Phon


D me me s l y e
Code

1 Exotic Liquid Charlotte 49 London EC1 UK (171)


Cooper Gilbert a 4SD 555-
St. 2222

2 New Orleans Shelley P.O. New 7011 USA (100)


Cajun Burke Box Orleans 7 555-
Delights 78934 4822

3 Grandma Regina 707 Ann 4810 USA (313)


Kelly's Murphy Oxford Arbor 4 555-
Homestead Rd. 5735

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;

Result:
You have made changes to the database. Rows affected: 29

The following SQL statement copies "Suppliers" into "Customers" (fill all
columns):

236
Example

INSERT INTO Customers (CustomerName, ContactName, Address, City,


PostalCode, Country)
SELECT SupplierName, ContactName, Address, City,
PostalCode, Country FROM Suppliers;

Result:
You have made changes to the database. Rows affected: 29

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

Result:
You have made changes to the database. Rows affected: 3

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

237
The following example uses a single-line comment as an explanation:

Example

--Select all:
SELECT * FROM Customers;

Number of Records: 274

Custom CustomerNa ContactN Address City Postal Countr


erID me ame Code y

1 Alfreds Maria Obere Str. Berlin 12209 Germa


Futterkiste Anders 57 ny

2 Ana Trujillo Ana Avda. de Mxico 05021 Mexico


Emparedados y Trujillo la D.F.
helados Constituci
n 2222

3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico


Taquera Moreno 2312 D.F.

4 Around the Thomas 120 London WA1 UK


Horn Hardy Hanover 1DP
Sq.

5 Berglunds Christina Berguvsv Lule S-958 Swede


snabbkp Berglund gen 8 22 n

6 Blauer See Hanna Forsterstr. Mannhei 68306 Germa


Delikatessen Moos 57 m ny

7 Blondel pre et Frdriqu 24, place Strasbo 67000 France


fils e Citeaux Klber urg

8 Blido Comidas Martn C/ Araquil, Madrid 28023 Spain


preparadas Sommer 67

9 Bon app' Laurence 12, rue Marseille 13008 France


Lebihans des
Bouchers

10 Bottom-Dollar Elizabeth 23 Tsawass T2F Canada


Marketse Lincoln Tsawasse en 8M4
n Blvd.

11 B's Beverages Victoria Fauntleroy London EC2 UK


Ashworth Circus 5NT

238
12 Cactus Patricio Cerrito Buenos 1010 Argenti
Comidas para Simpson 333 Aires na
llevar

13 Centro Francisco Sierras de Mxico 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

14 Chop-suey Yang Hauptstr. Bern 3012 Switzer


Chinese Wang 29 land

15 Comrcio Pedro Av. dos So 05432- Brazil


Mineiro Afonso Lusadas, Paulo 043
23

16 Consolidated Elizabeth Berkeley London WX1 UK


Holdings Brown Gardens 6LT
12
Brewery

17 Drachenblut Sven Walserwe Aachen 52066 Germa


Delikatessend Ottlieb g 21 ny

18 Du monde Janine 67, rue Nantes 44000 France


entier Labrune des
Cinquante
Otages

19 Eastern Ann 35 King London WX3 UK


Connection Devon George 6FW

20 Ernst Handel Roland Kirchgass Graz 8010 Austria


Mendel e6

21 Familia Aria Cruz Rua Ors, So 05442- Brazil


Arquibaldo 92 Paulo 030

22 FISSA Fabrica Diego C/ Madrid 28034 Spain


Inter. Roel Moralzarz
Salchichas S.A. al, 86

23 Folies Martine 184, Lille 59000 France


gourmandes Ranc chausse
de Tournai

24 Folk och f HB Maria kergatan Brcke S-844 Swede


Larsson 24 67 n

25 Frankenversan Peter Berliner Mnche 80805 Germa


d Franken Platz 43 n ny

239
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 Bacalhau Lino Jardim Lisboa 1675 Portuga


e Frutos do Mar Rodriguez das rosas l
n. 32

29 Galera del Eduardo Rambla de Barcelon 08022 Spain


gastrnomo Saavedra Catalua, a
23

30 Godos Cocina Jos C/ Sevilla 41101 Spain


Tpica Pedro Romero,
Freyre 33

31 Gourmet Andr Av. Brasil, Campina 04876- Brazil


Lanchonetes Fonseca 442 s 786

32 Great Lakes Howard 2732 Eugene 97403 USA


Food Market Snyder Baker
Blvd.

33 GROSELLA- Manuel 5 Ave. Caracas 1081 Venezu


Restaurante Pereira Los Palos ela
Grandes

34 Hanari Carnes Mario Rua do Rio de 05454- Brazil


Pontes Pao, 67 Janeiro 876

35 HILARIN- Carlos Carrera San 5022 Venezu


Abastos Hernnde 22 con Cristbal ela
z Ave.
Carlos
Soublette
#8-35

36 Hungry Coyote Yoshi City Elgin 97827 USA


Import Store Latimer Center
Plaza 516
Main St.

37 Hungry Owl All- Patricia 8 Cork Ireland


Night Grocers McKenna Johnstown
Road

38 Island Trading Helen Garden Cowes PO31 UK


Bennett House 7PJ

240
Crowther
Way

39 Kniglich Essen Philip Maubelstr. Branden 14776 Germa


Cramer 90 burg ny

40 La corne Daniel 67, Versaille 78000 France


d'abondance Tonini avenue de s
l'Europe

41 La maison Annette 1 rue Toulous 31000 France


d'Asie Roulet Alsace- e
Lorraine

42 Laughing Yoshi 1900 Oak Vancouv V3F Canada


Bacchus Wine Tannamur St. er 2K1
Cellars i

43 Lazy K Kountry John 12 Walla 99362 USA


Store Steel Orchestra Walla
Terrace

44 Lehmanns Renate Magazinw Frankfur 60528 Germa


Marktstand Messner eg 7 t a.M. ny

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


Shop Yorres St. Suite 5 Francisc
o

46 LILA- Carlos Carrera Barquisi 3508 Venezu


Supermercado Gonzlez 52 con meto ela
Ave.
Bolvar
#65-98
Llano
Largo

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


Delicateses Izquierdo Mayo Margarit ela
Porlamar a

48 Lonesome Pine Fran 89 Portland 97219 USA


Restaurant Wilson Chiaroscur
o Rd.

49 Magazzini Giovanni Via Bergam 24100 Italy


Alimentari Rovelli Ludovico il o
Riuniti Moro 22

50 Maison Dewey Catherine Rue Bruxelle B-1180 Belgiu

241
Dewey Joseph- s m
Bens 532

51 Mre Paillarde Jean 43 rue St. Montral H1J Canada


Fresnire Laurent 1C3

52 Morgenstern Alexander Heerstr. Leipzig 04179 Germa


Gesundkost Feuer 22 ny

53 North/South Simon South London SW7 UK


Crowther House 300 1RZ
Queensbri
dge

54 Ocano Yvonne Ing. Buenos 1010 Argenti


Atlntico Ltda. Moncada Gustavo Aires na
Moncada
8585 Piso
20-A

55 Old World Rene 2743 Anchora 99508 USA


Delicatessen Phillips Bering St. ge

56 Ottilies Henriette Mehrheim Kln 50739 Germa


Kseladen Pfalzheim erstr. 369 ny

57 Paris Marie 265, Paris 75012 France


spcialits Bertrand boulevard
Charonne

58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico


Comidas Fernnde Jorge D.F.
clsicas z Cash 321

59 Piccolo und Georg Geislweg Salzburg 5020 Austria


mehr Pipps 14

60 Princesa Isabel Isabel de Estrada da Lisboa 1756 Portuga


Vinhoss Castro sade n. l
58

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificado Janeiro 673
ra, 12

62 Queen Cozinha Lcia Alameda So 05487- Brazil


Carvalho dos Paulo 020
Canrios,
891

242
63 QUICK-Stop Horst Taucherstr Cunewal 01307 Germa
Kloss ae 10 de ny

64 Rancho grande Sergio Av. del Buenos 1010 Argenti


Gutirrez Libertador Aires na
900

65 Rattlesnake Paula 2817 Albuque 87110 USA


Canyon Wilson Milton Dr. rque
Grocery

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provincial Emilia
e 124

67 Ricardo Janete Av. Rio de 02389- Brazil


Adocicados Limeira Copacaba Janeiro 890
na, 267

68 Richter Michael Grenzache Genve 1203 Switzer


Supermarkt Holz rweg 237 land

69 Romero y Alejandra Gran Va, Madrid 28001 Spain


tomillo Camino 1

70 Sant Gourmet Jonas Erling Stavern 4110 Norway


Bergulfse Skakkes
n gate 78

71 Save-a-lot Jose 187 Boise 83720 USA


Markets Pavarotti Suffolk
Ln.

72 Seven Seas Hari 90 London OX15 UK


Imports Kumar Wadhurst 4NB
Rd.

73 Simons bistro Jytte Vinbltet Kbenha 1734 Denma


Petersen 34 vn rk

74 Spcialits du Dominiqu 25, rue Paris 75016 France


monde e Perrier Lauriston

75 Split Rail Beer Art P.O. Box Lander 82520 USA


& Ale Braunsch 555
weiger

76 Suprmes Pascale Boulevard Charlero B-6000 Belgiu


dlices Cartrain Tirou, 255 i m

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

78 The Cracker Liu Wong 55 Grizzly Butte 59801 USA


Box Peak Rd.

79 Toms Karin Luisenstr. Mnster 44087 Germa


Spezialitten Josephs 48 ny

80 Tortuga Miguel Avda. Mxico 05033 Mexico


Restaurante Angel Azteca D.F.
Paolino 123

81 Tradio Anabela Av. Ins So 05634- Brazil


Hipermercados Domingue de Castro, Paulo 030
s 414

82 Trail's Head Helvetius 722 Kirkland 98034 USA


Gourmet Nagy DaVinci
Provisioners Blvd.

83 Vaffeljernet Palle Smagslg rhus 8200 Denma


Ibsen et 45 rk

84 Victuailles en Mary 2, rue du Lyon 69004 France


stock Saveley Commerc
e

85 Vins et alcools Paul 59 rue de Reims 51100 France


Chevalier Henriot l'Abbaye

86 Die Wandernde Rita Adenauer Stuttgar 70563 Germa


Kuh Mller allee 900 t ny

87 Wartian Herkku Pirkko Torikatu Oulu 90110 Finland


Koskitalo 38

88 Wellington Paula Rua do Resende 08737- Brazil


Importadora Parente Mercado, 363
12

89 White Clover Karl 305 - 14th Seattle 98128 USA


Markets Jablonski Ave. S.
Suite 3B

90 Wilman Kala Matti Keskuskat Helsinki 21240 Finland


Karttunen u 45

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

92 Exotic Liquid null null Londona null UK

93 New Orleans null null New null USA


Cajun Delights Orleans

94 Grandma null null Ann null USA


Kelly's Arbor
Homestead

95 Tokyo Traders null null Tokyo null Japan

96 Cooperativa de null null Oviedo null Spain


Quesos 'Las
Cabras'

97 Mayumi's null null Osaka null Japan

98 Pavlova, Ltd. null null Melbour null Australi


ne a

99 Specialty null null Manches null UK


Biscuits, Ltd. ter

100 PB Knckebrd null null Gtebor null Swede


AB g n

101 Refrescos null null So null Brazil


Americanas Paulo
LTDA

102 Heli Swaren null null Berlin null Germa


GmbH & Co. ny
KG

103 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny
omrkte AG

104 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny
haft mbH

105 Formaggi null null Ravenna null Italy


Fortini s.r.l.

106 Norske Meierier null null Sandvik null Norway

245
a

107 Bigfoot null null Bend null USA


Breweries

108 Svensk Sjfda null null Stockhol null Swede


AB m n

109 Aux joyeux null null Paris null France


ecclsiastiques

110 New England null null Boston null USA


Seafood
Cannery

111 Leka Trading null null Singapo null Singap


re ore

112 Lyngbysild null null Lyngby null Denma


rk

113 Zaanse null null Zaanda null Netherl


Snoepfabriek m ands

114 Karkki Oy null null Lappeen null Finland


ranta

115 G'day, Mate null null Sydney null Australi


a

116 Ma Maison null null Montral null Canada

117 Pasta Buttini null null Salerno null Italy


s.r.l.

118 Escargots null null Montcea null France


Nouveaux u

119 Gai pturage null null Annecy null France

120 Forts null null Ste- null Canada


d'rables Hyacinth
e

121 Exotic Liquid null null Londona null UK

122 New Orleans null null New null USA


Cajun Delights Orleans

123 Grandma null null Ann null USA

246
Kelly's Arbor
Homestead

124 Tokyo Traders null null Tokyo null Japan

125 Cooperativa de null null Oviedo null Spain


Quesos 'Las
Cabras'

126 Mayumi's null null Osaka null Japan

127 Pavlova, Ltd. null null Melbour null Australi


ne a

128 Specialty null null Manches null UK


Biscuits, Ltd. ter

129 PB Knckebrd null null Gtebor null Swede


AB g n

130 Refrescos null null So null Brazil


Americanas Paulo
LTDA

131 Heli Swaren null null Berlin null Germa


GmbH & Co. ny
KG

132 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny
omrkte AG

133 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny
haft mbH

134 Formaggi null null Ravenna null Italy


Fortini s.r.l.

135 Norske Meierier null null Sandvik null Norway


a

136 Bigfoot null null Bend null USA


Breweries

137 Svensk Sjfda null null Stockhol null Swede


AB m n

138 Aux joyeux null null Paris null France


ecclsiastiques

247
139 New England null null Boston null USA
Seafood
Cannery

140 Leka Trading null null Singapo null Singap


re ore

141 Lyngbysild null null Lyngby null Denma


rk

142 Zaanse null null Zaanda null Netherl


Snoepfabriek m ands

143 Karkki Oy null null Lappeen null Finland


ranta

144 G'day, Mate null null Sydney null Australi


a

145 Ma Maison null null Montral null Canada

146 Pasta Buttini null null Salerno null Italy


s.r.l.

147 Escargots null null Montcea null France


Nouveaux u

148 Gai pturage null null Annecy null France

149 Forts null null Ste- null Canada


d'rables Hyacinth
e

150 Exotic Liquid null null Londona null UK

151 New Orleans null null New null USA


Cajun Delights Orleans

152 Grandma null null Ann null USA


Kelly's Arbor
Homestead

153 Tokyo Traders null null Tokyo null Japan

154 Cooperativa de null null Oviedo null Spain


Quesos 'Las
Cabras'

155 Mayumi's null null Osaka null Japan

248
156 Pavlova, Ltd. null null Melbour null Australi
ne a

157 Specialty null null Manches null UK


Biscuits, Ltd. ter

158 PB Knckebrd null null Gtebor null Swede


AB g n

159 Refrescos null null So null Brazil


Americanas Paulo
LTDA

160 Heli Swaren null null Berlin null Germa


GmbH & Co. ny
KG

161 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny
omrkte AG

162 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny
haft mbH

163 Formaggi null null Ravenna null Italy


Fortini s.r.l.

164 Norske Meierier null null Sandvik null Norway


a

165 Bigfoot null null Bend null USA


Breweries

166 Svensk Sjfda null null Stockhol null Swede


AB m n

167 Aux joyeux null null Paris null France


ecclsiastiques

168 New England null null Boston null USA


Seafood
Cannery

169 Leka Trading null null Singapo null Singap


re ore

170 Lyngbysild null null Lyngby null Denma


rk

249
171 Zaanse null null Zaanda null Netherl
Snoepfabriek m ands

172 Karkki Oy null null Lappeen null Finland


ranta

173 G'day, Mate null null Sydney null Australi


a

174 Ma Maison null null Montral null Canada

175 Pasta Buttini null null Salerno null Italy


s.r.l.

176 Escargots null null Montcea null France


Nouveaux u

177 Gai pturage null null Annecy null France

178 Forts null null Ste- null Canada


d'rables Hyacinth
e

179 Exotic Liquid Charlotte 49 Gilbert Londona EC1 UK


Cooper St. 4SD

180 New Orleans Shelley P.O. Box New 70117 USA


Cajun Delights Burke 78934 Orleans

181 Grandma Regina 707 Ann 48104 USA


Kelly's Murphy Oxford Arbor
Homestead Rd.

182 Tokyo Traders Yoshi 9-8 Tokyo 100 Japan


Nagase Sekimai
Musashino
-shi

183 Cooperativa de Antonio Calle del Oviedo 33007 Spain


Quesos 'Las del Valle Rosal 4
Cabras' Saavedra

184 Mayumi's Mayumi 92 Osaka 545 Japan


Ohno Setsuko
Chuo-ku

185 Pavlova, Ltd. Ian 74 Rose Melbour 3058 Australi


Devling St. Moonie ne a
Ponds

250
186 Specialty Peter 29 King's Manches M14 UK
Biscuits, Ltd. Wilson Way ter GSD

187 PB Knckebrd Lars Kaloadaga Gtebor S-345 Swede


AB Peterson tan 13 g 67 n

188 Refrescos Carlos Av. das So 5442 Brazil


Americanas Diaz Americana Paulo
LTDA s 12.890

189 Heli Swaren Petra Tiergarten Berlin 10785 Germa


GmbH & Co. Winkler strae 5 ny
KG

190 Plutzer Martin Bogenalle Frankfur 60439 Germa


Lebensmittelgr Bein e 51 t ny
omrkte AG

191 Nord-Ost-Fisch Sven Frahmred Cuxhave 27478 Germa


Handelsgesellsc Petersen der 112a n ny
haft mbH

192 Formaggi Elio Rossi Viale Ravenna 48100 Italy


Fortini s.r.l. Dante, 75

193 Norske Meierier Beate Hatlevege Sandvik 1320 Norway


Vileid n5 a

194 Bigfoot Cheryl 3400 - 8th Bend 97101 USA


Breweries Saylor Avenue
Suite 210

195 Svensk Sjfda Michael Brovallav Stockhol S-123 Swede


AB Bjrn gen 231 m 45 n

196 Aux joyeux Guylne 203, Rue Paris 75004 France


ecclsiastiques Nodier des
Francs-
Bourgeois

197 New England Robb Order Boston 02134 USA


Seafood Merchant Processing
Cannery Dept.
2100 Paul
Revere
Blvd.

198 Leka Trading Chandra 471 Singapo 0512 Singap


Leka Serangoo re ore
n Loop,

251
Suite
#402

199 Lyngbysild Niels Lyngbysild Lyngby 2800 Denma


Petersen Fiskebakk rk
en 10

200 Zaanse Dirk Verkoop Zaanda 9999 Netherl


Snoepfabriek Luchte Rijnweg m ZZ ands
22

201 Karkki Oy Anne Valtakatu Lappeen 53120 Finland


Heikkone 12 ranta
n

202 G'day, Mate Wendy 170 Prince Sydney 2042 Australi


Mackenzi Edward a
e Parade
Hunter's
Hill

203 Ma Maison Jean-Guy 2960 Rue Montral H1J Canada


Lauzon St. 1C3
Laurent

204 Pasta Buttini Giovanni Via dei Salerno 84100 Italy


s.r.l. Giudici Gelsomini,
153

205 Escargots Marie 22, rue H. Montcea 71300 France


Nouveaux Delamare Voiron u

206 Gai pturage Eliane Bat. B 3, Annecy 74000 France


Noz rue des
Alpes

207 Forts Chantal 148 rue Ste- J2S Canada


d'rables Goulet Chasseur Hyacinth 7S8
e

208 Heli Swaren null null Berlin null Germa


GmbH & Co. ny
KG

209 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny
omrkte AG

210 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny

252
haft mbH

211 Heli Swaren null null Berlin null Germa


GmbH & Co. ny
KG

212 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny
omrkte AG

213 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny
haft mbH

214 Exotic Liquid null null Londona null UK

215 New Orleans null null New null USA


Cajun Delights Orleans

216 Grandma null null Ann null USA


Kelly's Arbor
Homestead

217 Tokyo Traders null null Tokyo null Japan

218 Cooperativa de null null Oviedo null Spain


Quesos 'Las
Cabras'

219 Mayumi's null null Osaka null Japan

220 Pavlova, Ltd. null null Melbour null Australi


ne a

221 Specialty null null Manches null UK


Biscuits, Ltd. ter

222 PB Knckebrd null null Gtebor null Swede


AB g n

223 Refrescos null null So null Brazil


Americanas Paulo
LTDA

224 Heli Swaren null null Berlin null Germa


GmbH & Co. ny
KG

225 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny

253
omrkte AG

226 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny
haft mbH

227 Formaggi null null Ravenna null Italy


Fortini s.r.l.

228 Norske Meierier null null Sandvik null Norway


a

229 Bigfoot null null Bend null USA


Breweries

230 Svensk Sjfda null null Stockhol null Swede


AB m n

231 Aux joyeux null null Paris null France


ecclsiastiques

232 New England null null Boston null USA


Seafood
Cannery

233 Leka Trading null null Singapo null Singap


re ore

234 Lyngbysild null null Lyngby null Denma


rk

235 Zaanse null null Zaanda null Netherl


Snoepfabriek m ands

236 Karkki Oy null null Lappeen null Finland


ranta

237 G'day, Mate null null Sydney null Australi


a

238 Ma Maison null null Montral null Canada

239 Pasta Buttini null null Salerno null Italy


s.r.l.

240 Escargots null null Montcea null France


Nouveaux u

241 Gai pturage null null Annecy null France

254
242 Forts null null Ste- null Canada
d'rables Hyacinth
e

243 Exotic Liquid Charlotte 49 Gilbert Londona EC1 UK


Cooper St. 4SD

244 New Orleans Shelley P.O. Box New 70117 USA


Cajun Delights Burke 78934 Orleans

245 Grandma Regina 707 Ann 48104 USA


Kelly's Murphy Oxford Arbor
Homestead Rd.

246 Tokyo Traders Yoshi 9-8 Tokyo 100 Japan


Nagase Sekimai
Musashino
-shi

247 Cooperativa de Antonio Calle del Oviedo 33007 Spain


Quesos 'Las del Valle Rosal 4
Cabras' Saavedra

248 Mayumi's Mayumi 92 Osaka 545 Japan


Ohno Setsuko
Chuo-ku

249 Pavlova, Ltd. Ian 74 Rose Melbour 3058 Australi


Devling St. Moonie ne a
Ponds

250 Specialty Peter 29 King's Manches M14 UK


Biscuits, Ltd. Wilson Way ter GSD

251 PB Knckebrd Lars Kaloadaga Gtebor S-345 Swede


AB Peterson tan 13 g 67 n

252 Refrescos Carlos Av. das So 5442 Brazil


Americanas Diaz Americana Paulo
LTDA s 12.890

253 Heli Swaren Petra Tiergarten Berlin 10785 Germa


GmbH & Co. Winkler strae 5 ny
KG

254 Plutzer Martin Bogenalle Frankfur 60439 Germa


Lebensmittelgr Bein e 51 t ny
omrkte AG

255 Nord-Ost-Fisch Sven Frahmred Cuxhave 27478 Germa

255
Handelsgesellsc Petersen der 112a n ny
haft mbH

256 Formaggi Elio Rossi Viale Ravenna 48100 Italy


Fortini s.r.l. Dante, 75

257 Norske Meierier Beate Hatlevege Sandvik 1320 Norway


Vileid n5 a

258 Bigfoot Cheryl 3400 - 8th Bend 97101 USA


Breweries Saylor Avenue
Suite 210

259 Svensk Sjfda Michael Brovallav Stockhol S-123 Swede


AB Bjrn gen 231 m 45 n

260 Aux joyeux Guylne 203, Rue Paris 75004 France


ecclsiastiques Nodier des
Francs-
Bourgeois

261 New England Robb Order Boston 02134 USA


Seafood Merchant Processing
Cannery Dept.
2100 Paul
Revere
Blvd.

262 Leka Trading Chandra 471 Singapo 0512 Singap


Leka Serangoo re ore
n Loop,
Suite
#402

263 Lyngbysild Niels Lyngbysild Lyngby 2800 Denma


Petersen Fiskebakk rk
en 10

264 Zaanse Dirk Verkoop Zaanda 9999 Netherl


Snoepfabriek Luchte Rijnweg m ZZ ands
22

265 Karkki Oy Anne Valtakatu Lappeen 53120 Finland


Heikkone 12 ranta
n

266 G'day, Mate Wendy 170 Prince Sydney 2042 Australi


Mackenzi Edward a
e Parade
Hunter's

256
Hill

267 Ma Maison Jean-Guy 2960 Rue Montral H1J Canada


Lauzon St. 1C3
Laurent

268 Pasta Buttini Giovanni Via dei Salerno 84100 Italy


s.r.l. Giudici Gelsomini,
153

269 Escargots Marie 22, rue H. Montcea 71300 France


Nouveaux Delamare Voiron u

270 Gai pturage Eliane Bat. B 3, Annecy 74000 France


Noz rue des
Alpes

271 Forts Chantal 148 rue Ste- J2S Canada


d'rables Goulet Chasseur Hyacinth 7S8
e

272 Heli Swaren null null Berlin null Germa


GmbH & Co. ny
KG

273 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny
omrkte AG

274 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny
haft mbH

The following example uses a single-line comment to ignore the end of a


line:

Example

SELECT * FROM Customers -- WHERE City='Berlin';

Number of Records: 274

Custom CustomerNa ContactN Address City Postal Countr


erID me ame Code y

1 Alfreds Maria Obere Str. Berlin 12209 Germa


Futterkiste Anders 57 ny

2 Ana Trujillo Ana Avda. de Mxico 05021 Mexico

257
Emparedados y Trujillo la D.F.
helados Constituci
n 2222

3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico


Taquera Moreno 2312 D.F.

4 Around the Thomas 120 London WA1 UK


Horn Hardy Hanover 1DP
Sq.

5 Berglunds Christina Berguvsv Lule S-958 Swede


snabbkp Berglund gen 8 22 n

6 Blauer See Hanna Forsterstr. Mannhei 68306 Germa


Delikatessen Moos 57 m ny

7 Blondel pre et Frdriqu 24, place Strasbo 67000 France


fils e Citeaux Klber urg

8 Blido Comidas Martn C/ Araquil, Madrid 28023 Spain


preparadas Sommer 67

9 Bon app' Laurence 12, rue Marseille 13008 France


Lebihans des
Bouchers

10 Bottom-Dollar Elizabeth 23 Tsawass T2F Canada


Marketse Lincoln Tsawasse en 8M4
n Blvd.

11 B's Beverages Victoria Fauntleroy London EC2 UK


Ashworth Circus 5NT

12 Cactus Patricio Cerrito Buenos 1010 Argenti


Comidas para Simpson 333 Aires na
llevar

13 Centro Francisco Sierras de Mxico 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

14 Chop-suey Yang Hauptstr. Bern 3012 Switzer


Chinese Wang 29 land

15 Comrcio Pedro Av. dos So 05432- Brazil


Mineiro Afonso Lusadas, Paulo 043
23

16 Consolidated Elizabeth Berkeley London WX1 UK

258
Holdings Brown Gardens 6LT
12
Brewery

17 Drachenblut Sven Walserwe Aachen 52066 Germa


Delikatessend Ottlieb g 21 ny

18 Du monde Janine 67, rue Nantes 44000 France


entier Labrune des
Cinquante
Otages

19 Eastern Ann 35 King London WX3 UK


Connection Devon George 6FW

20 Ernst Handel Roland Kirchgass Graz 8010 Austria


Mendel e6

21 Familia Aria Cruz Rua Ors, So 05442- Brazil


Arquibaldo 92 Paulo 030

22 FISSA Fabrica Diego C/ Madrid 28034 Spain


Inter. Roel Moralzarz
Salchichas S.A. al, 86

23 Folies Martine 184, Lille 59000 France


gourmandes Ranc chausse
de Tournai

24 Folk och f HB Maria kergatan Brcke S-844 Swede


Larsson 24 67 n

25 Frankenversan Peter Berliner Mnche 80805 Germa


d Franken Platz 43 n ny

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 Bacalhau Lino Jardim Lisboa 1675 Portuga


e Frutos do Mar Rodriguez das rosas l
n. 32

29 Galera del Eduardo Rambla de Barcelon 08022 Spain


gastrnomo Saavedra Catalua, a
23

30 Godos Cocina Jos C/ Sevilla 41101 Spain

259
Tpica Pedro Romero,
Freyre 33

31 Gourmet Andr Av. Brasil, Campina 04876- Brazil


Lanchonetes Fonseca 442 s 786

32 Great Lakes Howard 2732 Eugene 97403 USA


Food Market Snyder Baker
Blvd.

33 GROSELLA- Manuel 5 Ave. Caracas 1081 Venezu


Restaurante Pereira Los Palos ela
Grandes

34 Hanari Carnes Mario Rua do Rio de 05454- Brazil


Pontes Pao, 67 Janeiro 876

35 HILARIN- Carlos Carrera San 5022 Venezu


Abastos Hernnde 22 con Cristbal ela
z Ave.
Carlos
Soublette
#8-35

36 Hungry Coyote Yoshi City Elgin 97827 USA


Import Store Latimer Center
Plaza 516
Main St.

37 Hungry Owl All- Patricia 8 Cork Ireland


Night Grocers McKenna Johnstown
Road

38 Island Trading Helen Garden Cowes PO31 UK


Bennett House 7PJ
Crowther
Way

39 Kniglich Essen Philip Maubelstr. Branden 14776 Germa


Cramer 90 burg ny

40 La corne Daniel 67, Versaille 78000 France


d'abondance Tonini avenue de s
l'Europe

41 La maison Annette 1 rue Toulous 31000 France


d'Asie Roulet Alsace- e
Lorraine

42 Laughing Yoshi 1900 Oak Vancouv V3F Canada

260
Bacchus Wine Tannamur St. er 2K1
Cellars i

43 Lazy K Kountry John 12 Walla 99362 USA


Store Steel Orchestra Walla
Terrace

44 Lehmanns Renate Magazinw Frankfur 60528 Germa


Marktstand Messner eg 7 t a.M. ny

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


Shop Yorres St. Suite 5 Francisc
o

46 LILA- Carlos Carrera Barquisi 3508 Venezu


Supermercado Gonzlez 52 con meto ela
Ave.
Bolvar
#65-98
Llano
Largo

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


Delicateses Izquierdo Mayo Margarit ela
Porlamar a

48 Lonesome Pine Fran 89 Portland 97219 USA


Restaurant Wilson Chiaroscur
o Rd.

49 Magazzini Giovanni Via Bergam 24100 Italy


Alimentari Rovelli Ludovico il o
Riuniti Moro 22

50 Maison Dewey Catherine Rue Bruxelle B-1180 Belgiu


Dewey Joseph- s m
Bens 532

51 Mre Paillarde Jean 43 rue St. Montral H1J Canada


Fresnire Laurent 1C3

52 Morgenstern Alexander Heerstr. Leipzig 04179 Germa


Gesundkost Feuer 22 ny

53 North/South Simon South London SW7 UK


Crowther House 300 1RZ
Queensbri
dge

54 Ocano Yvonne Ing. Buenos 1010 Argenti

261
Atlntico Ltda. Moncada Gustavo Aires na
Moncada
8585 Piso
20-A

55 Old World Rene 2743 Anchora 99508 USA


Delicatessen Phillips Bering St. ge

56 Ottilies Henriette Mehrheim Kln 50739 Germa


Kseladen Pfalzheim erstr. 369 ny

57 Paris Marie 265, Paris 75012 France


spcialits Bertrand boulevard
Charonne

58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico


Comidas Fernnde Jorge D.F.
clsicas z Cash 321

59 Piccolo und Georg Geislweg Salzburg 5020 Austria


mehr Pipps 14

60 Princesa Isabel Isabel de Estrada da Lisboa 1756 Portuga


Vinhoss Castro sade n. l
58

61 Que Delcia Bernardo Rua da Rio de 02389- Brazil


Batista Panificado Janeiro 673
ra, 12

62 Queen Cozinha Lcia Alameda So 05487- Brazil


Carvalho dos Paulo 020
Canrios,
891

63 QUICK-Stop Horst Taucherstr Cunewal 01307 Germa


Kloss ae 10 de ny

64 Rancho grande Sergio Av. del Buenos 1010 Argenti


Gutirrez Libertador Aires na
900

65 Rattlesnake Paula 2817 Albuque 87110 USA


Canyon Wilson Milton Dr. rque
Grocery

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provincial Emilia
e 124

262
67 Ricardo Janete Av. Rio de 02389- Brazil
Adocicados Limeira Copacaba Janeiro 890
na, 267

68 Richter Michael Grenzache Genve 1203 Switzer


Supermarkt Holz rweg 237 land

69 Romero y Alejandra Gran Va, Madrid 28001 Spain


tomillo Camino 1

70 Sant Gourmet Jonas Erling Stavern 4110 Norway


Bergulfse Skakkes
n gate 78

71 Save-a-lot Jose 187 Boise 83720 USA


Markets Pavarotti Suffolk
Ln.

72 Seven Seas Hari 90 London OX15 UK


Imports Kumar Wadhurst 4NB
Rd.

73 Simons bistro Jytte Vinbltet Kbenha 1734 Denma


Petersen 34 vn rk

74 Spcialits du Dominiqu 25, rue Paris 75016 France


monde e Perrier Lauriston

75 Split Rail Beer Art P.O. Box Lander 82520 USA


& Ale Braunsch 555
weiger

76 Suprmes Pascale Boulevard Charlero B-6000 Belgiu


dlices Cartrain Tirou, 255 i m

77 The Big Cheese Liz Nixon 89 Portland 97201 USA


Jefferson
Way Suite
2

78 The Cracker Liu Wong 55 Grizzly Butte 59801 USA


Box Peak Rd.

79 Toms Karin Luisenstr. Mnster 44087 Germa


Spezialitten Josephs 48 ny

80 Tortuga Miguel Avda. Mxico 05033 Mexico


Restaurante Angel Azteca D.F.
Paolino 123

263
81 Tradio Anabela Av. Ins So 05634- Brazil
Hipermercados Domingue de Castro, Paulo 030
s 414

82 Trail's Head Helvetius 722 Kirkland 98034 USA


Gourmet Nagy DaVinci
Provisioners Blvd.

83 Vaffeljernet Palle Smagslg rhus 8200 Denma


Ibsen et 45 rk

84 Victuailles en Mary 2, rue du Lyon 69004 France


stock Saveley Commerc
e

85 Vins et alcools Paul 59 rue de Reims 51100 France


Chevalier Henriot l'Abbaye

86 Die Wandernde Rita Adenauer Stuttgar 70563 Germa


Kuh Mller allee 900 t ny

87 Wartian Herkku Pirkko Torikatu Oulu 90110 Finland


Koskitalo 38

88 Wellington Paula Rua do Resende 08737- Brazil


Importadora Parente Mercado, 363
12

89 White Clover Karl 305 - 14th Seattle 98128 USA


Markets Jablonski Ave. S.
Suite 3B

90 Wilman Kala Matti Keskuskat Helsinki 21240 Finland


Karttunen u 45

91 Wolski Zbyszek ul. Walla 01-012 Poland


Filtrowa
68

92 Exotic Liquid null null Londona null UK

93 New Orleans null null New null USA


Cajun Delights Orleans

94 Grandma null null Ann null USA


Kelly's Arbor
Homestead

95 Tokyo Traders null null Tokyo null Japan

264
96 Cooperativa de null null Oviedo null Spain
Quesos 'Las
Cabras'

97 Mayumi's null null Osaka null Japan

98 Pavlova, Ltd. null null Melbour null Australi


ne a

99 Specialty null null Manches null UK


Biscuits, Ltd. ter

100 PB Knckebrd null null Gtebor null Swede


AB g n

101 Refrescos null null So null Brazil


Americanas Paulo
LTDA

102 Heli Swaren null null Berlin null Germa


GmbH & Co. ny
KG

103 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny
omrkte AG

104 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny
haft mbH

105 Formaggi null null Ravenna null Italy


Fortini s.r.l.

106 Norske Meierier null null Sandvik null Norway


a

107 Bigfoot null null Bend null USA


Breweries

108 Svensk Sjfda null null Stockhol null Swede


AB m n

109 Aux joyeux null null Paris null France


ecclsiastiques

110 New England null null Boston null USA


Seafood
Cannery

265
111 Leka Trading null null Singapo null Singap
re ore

112 Lyngbysild null null Lyngby null Denma


rk

113 Zaanse null null Zaanda null Netherl


Snoepfabriek m ands

114 Karkki Oy null null Lappeen null Finland


ranta

115 G'day, Mate null null Sydney null Australi


a

116 Ma Maison null null Montral null Canada

117 Pasta Buttini null null Salerno null Italy


s.r.l.

118 Escargots null null Montcea null France


Nouveaux u

119 Gai pturage null null Annecy null France

120 Forts null null Ste- null Canada


d'rables Hyacinth
e

121 Exotic Liquid null null Londona null UK

122 New Orleans null null New null USA


Cajun Delights Orleans

123 Grandma null null Ann null USA


Kelly's Arbor
Homestead

124 Tokyo Traders null null Tokyo null Japan

125 Cooperativa de null null Oviedo null Spain


Quesos 'Las
Cabras'

126 Mayumi's null null Osaka null Japan

127 Pavlova, Ltd. null null Melbour null Australi


ne a

128 Specialty null null Manches null UK

266
Biscuits, Ltd. ter

129 PB Knckebrd null null Gtebor null Swede


AB g n

130 Refrescos null null So null Brazil


Americanas Paulo
LTDA

131 Heli Swaren null null Berlin null Germa


GmbH & Co. ny
KG

132 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny
omrkte AG

133 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny
haft mbH

134 Formaggi null null Ravenna null Italy


Fortini s.r.l.

135 Norske Meierier null null Sandvik null Norway


a

136 Bigfoot null null Bend null USA


Breweries

137 Svensk Sjfda null null Stockhol null Swede


AB m n

138 Aux joyeux null null Paris null France


ecclsiastiques

139 New England null null Boston null USA


Seafood
Cannery

140 Leka Trading null null Singapo null Singap


re ore

141 Lyngbysild null null Lyngby null Denma


rk

142 Zaanse null null Zaanda null Netherl


Snoepfabriek m ands

143 Karkki Oy null null Lappeen null Finland

267
ranta

144 G'day, Mate null null Sydney null Australi


a

145 Ma Maison null null Montral null Canada

146 Pasta Buttini null null Salerno null Italy


s.r.l.

147 Escargots null null Montcea null France


Nouveaux u

148 Gai pturage null null Annecy null France

149 Forts null null Ste- null Canada


d'rables Hyacinth
e

150 Exotic Liquid null null Londona null UK

151 New Orleans null null New null USA


Cajun Delights Orleans

152 Grandma null null Ann null USA


Kelly's Arbor
Homestead

153 Tokyo Traders null null Tokyo null Japan

154 Cooperativa de null null Oviedo null Spain


Quesos 'Las
Cabras'

155 Mayumi's null null Osaka null Japan

156 Pavlova, Ltd. null null Melbour null Australi


ne a

157 Specialty null null Manches null UK


Biscuits, Ltd. ter

158 PB Knckebrd null null Gtebor null Swede


AB g n

159 Refrescos null null So null Brazil


Americanas Paulo
LTDA

160 Heli Swaren null null Berlin null Germa

268
GmbH & Co. ny
KG

161 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny
omrkte AG

162 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny
haft mbH

163 Formaggi null null Ravenna null Italy


Fortini s.r.l.

164 Norske Meierier null null Sandvik null Norway


a

165 Bigfoot null null Bend null USA


Breweries

166 Svensk Sjfda null null Stockhol null Swede


AB m n

167 Aux joyeux null null Paris null France


ecclsiastiques

168 New England null null Boston null USA


Seafood
Cannery

169 Leka Trading null null Singapo null Singap


re ore

170 Lyngbysild null null Lyngby null Denma


rk

171 Zaanse null null Zaanda null Netherl


Snoepfabriek m ands

172 Karkki Oy null null Lappeen null Finland


ranta

173 G'day, Mate null null Sydney null Australi


a

174 Ma Maison null null Montral null Canada

175 Pasta Buttini null null Salerno null Italy


s.r.l.

269
176 Escargots null null Montcea null France
Nouveaux u

177 Gai pturage null null Annecy null France

178 Forts null null Ste- null Canada


d'rables Hyacinth
e

179 Exotic Liquid Charlotte 49 Gilbert Londona EC1 UK


Cooper St. 4SD

180 New Orleans Shelley P.O. Box New 70117 USA


Cajun Delights Burke 78934 Orleans

181 Grandma Regina 707 Ann 48104 USA


Kelly's Murphy Oxford Arbor
Homestead Rd.

182 Tokyo Traders Yoshi 9-8 Tokyo 100 Japan


Nagase Sekimai
Musashino
-shi

183 Cooperativa de Antonio Calle del Oviedo 33007 Spain


Quesos 'Las del Valle Rosal 4
Cabras' Saavedra

184 Mayumi's Mayumi 92 Osaka 545 Japan


Ohno Setsuko
Chuo-ku

185 Pavlova, Ltd. Ian 74 Rose Melbour 3058 Australi


Devling St. Moonie ne a
Ponds

186 Specialty Peter 29 King's Manches M14 UK


Biscuits, Ltd. Wilson Way ter GSD

187 PB Knckebrd Lars Kaloadaga Gtebor S-345 Swede


AB Peterson tan 13 g 67 n

188 Refrescos Carlos Av. das So 5442 Brazil


Americanas Diaz Americana Paulo
LTDA s 12.890

189 Heli Swaren Petra Tiergarten Berlin 10785 Germa


GmbH & Co. Winkler strae 5 ny
KG

270
190 Plutzer Martin Bogenalle Frankfur 60439 Germa
Lebensmittelgr Bein e 51 t ny
omrkte AG

191 Nord-Ost-Fisch Sven Frahmred Cuxhave 27478 Germa


Handelsgesellsc Petersen der 112a n ny
haft mbH

192 Formaggi Elio Rossi Viale Ravenna 48100 Italy


Fortini s.r.l. Dante, 75

193 Norske Meierier Beate Hatlevege Sandvik 1320 Norway


Vileid n5 a

194 Bigfoot Cheryl 3400 - 8th Bend 97101 USA


Breweries Saylor Avenue
Suite 210

195 Svensk Sjfda Michael Brovallav Stockhol S-123 Swede


AB Bjrn gen 231 m 45 n

196 Aux joyeux Guylne 203, Rue Paris 75004 France


ecclsiastiques Nodier des
Francs-
Bourgeois

197 New England Robb Order Boston 02134 USA


Seafood Merchant Processing
Cannery Dept.
2100 Paul
Revere
Blvd.

198 Leka Trading Chandra 471 Singapo 0512 Singap


Leka Serangoo re ore
n Loop,
Suite
#402

199 Lyngbysild Niels Lyngbysild Lyngby 2800 Denma


Petersen Fiskebakk rk
en 10

200 Zaanse Dirk Verkoop Zaanda 9999 Netherl


Snoepfabriek Luchte Rijnweg m ZZ ands
22

201 Karkki Oy Anne Valtakatu Lappeen 53120 Finland


Heikkone 12 ranta
n

271
202 G'day, Mate Wendy 170 Prince Sydney 2042 Australi
Mackenzi Edward a
e Parade
Hunter's
Hill

203 Ma Maison Jean-Guy 2960 Rue Montral H1J Canada


Lauzon St. 1C3
Laurent

204 Pasta Buttini Giovanni Via dei Salerno 84100 Italy


s.r.l. Giudici Gelsomini,
153

205 Escargots Marie 22, rue H. Montcea 71300 France


Nouveaux Delamare Voiron u

206 Gai pturage Eliane Bat. B 3, Annecy 74000 France


Noz rue des
Alpes

207 Forts Chantal 148 rue Ste- J2S Canada


d'rables Goulet Chasseur Hyacinth 7S8
e

208 Heli Swaren null null Berlin null Germa


GmbH & Co. ny
KG

209 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny
omrkte AG

210 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny
haft mbH

211 Heli Swaren null null Berlin null Germa


GmbH & Co. ny
KG

212 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny
omrkte AG

213 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny
haft mbH

214 Exotic Liquid null null Londona null UK

272
215 New Orleans null null New null USA
Cajun Delights Orleans

216 Grandma null null Ann null USA


Kelly's Arbor
Homestead

217 Tokyo Traders null null Tokyo null Japan

218 Cooperativa de null null Oviedo null Spain


Quesos 'Las
Cabras'

219 Mayumi's null null Osaka null Japan

220 Pavlova, Ltd. null null Melbour null Australi


ne a

221 Specialty null null Manches null UK


Biscuits, Ltd. ter

222 PB Knckebrd null null Gtebor null Swede


AB g n

223 Refrescos null null So null Brazil


Americanas Paulo
LTDA

224 Heli Swaren null null Berlin null Germa


GmbH & Co. ny
KG

225 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny
omrkte AG

226 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny
haft mbH

227 Formaggi null null Ravenna null Italy


Fortini s.r.l.

228 Norske Meierier null null Sandvik null Norway


a

229 Bigfoot null null Bend null USA


Breweries

230 Svensk Sjfda null null Stockhol null Swede

273
AB m n

231 Aux joyeux null null Paris null France


ecclsiastiques

232 New England null null Boston null USA


Seafood
Cannery

233 Leka Trading null null Singapo null Singap


re ore

234 Lyngbysild null null Lyngby null Denma


rk

235 Zaanse null null Zaanda null Netherl


Snoepfabriek m ands

236 Karkki Oy null null Lappeen null Finland


ranta

237 G'day, Mate null null Sydney null Australi


a

238 Ma Maison null null Montral null Canada

239 Pasta Buttini null null Salerno null Italy


s.r.l.

240 Escargots null null Montcea null France


Nouveaux u

241 Gai pturage null null Annecy null France

242 Forts null null Ste- null Canada


d'rables Hyacinth
e

243 Exotic Liquid Charlotte 49 Gilbert Londona EC1 UK


Cooper St. 4SD

244 New Orleans Shelley P.O. Box New 70117 USA


Cajun Delights Burke 78934 Orleans

245 Grandma Regina 707 Ann 48104 USA


Kelly's Murphy Oxford Arbor
Homestead Rd.

246 Tokyo Traders Yoshi 9-8 Tokyo 100 Japan


Nagase Sekimai

274
Musashino
-shi

247 Cooperativa de Antonio Calle del Oviedo 33007 Spain


Quesos 'Las del Valle Rosal 4
Cabras' Saavedra

248 Mayumi's Mayumi 92 Osaka 545 Japan


Ohno Setsuko
Chuo-ku

249 Pavlova, Ltd. Ian 74 Rose Melbour 3058 Australi


Devling St. Moonie ne a
Ponds

250 Specialty Peter 29 King's Manches M14 UK


Biscuits, Ltd. Wilson Way ter GSD

251 PB Knckebrd Lars Kaloadaga Gtebor S-345 Swede


AB Peterson tan 13 g 67 n

252 Refrescos Carlos Av. das So 5442 Brazil


Americanas Diaz Americana Paulo
LTDA s 12.890

253 Heli Swaren Petra Tiergarten Berlin 10785 Germa


GmbH & Co. Winkler strae 5 ny
KG

254 Plutzer Martin Bogenalle Frankfur 60439 Germa


Lebensmittelgr Bein e 51 t ny
omrkte AG

255 Nord-Ost-Fisch Sven Frahmred Cuxhave 27478 Germa


Handelsgesellsc Petersen der 112a n ny
haft mbH

256 Formaggi Elio Rossi Viale Ravenna 48100 Italy


Fortini s.r.l. Dante, 75

257 Norske Meierier Beate Hatlevege Sandvik 1320 Norway


Vileid n5 a

258 Bigfoot Cheryl 3400 - 8th Bend 97101 USA


Breweries Saylor Avenue
Suite 210

259 Svensk Sjfda Michael Brovallav Stockhol S-123 Swede


AB Bjrn gen 231 m 45 n

275
260 Aux joyeux Guylne 203, Rue Paris 75004 France
ecclsiastiques Nodier des
Francs-
Bourgeois

261 New England Robb Order Boston 02134 USA


Seafood Merchant Processing
Cannery Dept.
2100 Paul
Revere
Blvd.

262 Leka Trading Chandra 471 Singapo 0512 Singap


Leka Serangoo re ore
n Loop,
Suite
#402

263 Lyngbysild Niels Lyngbysild Lyngby 2800 Denma


Petersen Fiskebakk rk
en 10

264 Zaanse Dirk Verkoop Zaanda 9999 Netherl


Snoepfabriek Luchte Rijnweg m ZZ ands
22

265 Karkki Oy Anne Valtakatu Lappeen 53120 Finland


Heikkone 12 ranta
n

266 G'day, Mate Wendy 170 Prince Sydney 2042 Australi


Mackenzi Edward a
e Parade
Hunter's
Hill

267 Ma Maison Jean-Guy 2960 Rue Montral H1J Canada


Lauzon St. 1C3
Laurent

268 Pasta Buttini Giovanni Via dei Salerno 84100 Italy


s.r.l. Giudici Gelsomini,
153

269 Escargots Marie 22, rue H. Montcea 71300 France


Nouveaux Delamare Voiron u

270 Gai pturage Eliane Bat. B 3, Annecy 74000 France


Noz rue des
Alpes

276
271 Forts Chantal 148 rue Ste- J2S Canada
d'rables Goulet Chasseur Hyacinth 7S8
e

272 Heli Swaren null null Berlin null Germa


GmbH & Co. ny
KG

273 Plutzer null null Frankfur null Germa


Lebensmittelgr t ny
omrkte AG

274 Nord-Ost-Fisch null null Cuxhave null Germa


Handelsgesellsc n ny
haft mbH

The following example uses a single-line comment to ignore a


statement:

Example

--SELECT * FROM Customers;


SELECT * FROM Products;

Number of Records: 77

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes 18
x 20
bags

2 Chang 1 1 24 - 12 19
oz
bottles

3 Aniseed Syrup 1 2 12 - 550 10


ml
bottles

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


Seasoning jars

5 Chef Anton's 2 2 36 boxes 21.35


Gumbo Mix

6 Grandma's 3 2 12 - 8 oz 25
Boysenberry jars

277
Spread

7 Uncle Bob's 3 7 12 - 1 lb 30
Organic Dried pkgs.
Pears

8 Northwoods 3 2 12 - 12 40
Cranberry Sauce oz jars

9 Mishi Kobe Niku 4 6 18 - 500 97


g pkgs.

10 Ikura 4 8 12 - 200 31
ml jars

11 Queso Cabrales 5 4 1 kg 21
pkg.

12 Queso Manchego 5 4 10 - 500 38


La Pastora g pkgs.

13 Konbu 6 8 2 kg box 6

14 Tofu 6 7 40 - 100 23.25


g pkgs.

15 Genen Shouyu 6 2 24 - 250 15.5


ml
bottles

16 Pavlova 7 3 32 - 500 17.45


g boxes

17 Alice Mutton 7 6 20 - 1 kg 39
tins

18 Carnarvon Tigers 7 8 16 kg 62.5


pkg.

19 Teatime Chocolate 8 3 10 boxes 9.2


Biscuits x 12
pieces

20 Sir Rodney's 8 3 30 gift 81


Marmalade boxes

21 Sir Rodney's 8 3 24 pkgs. 10


Scones x4
pieces

278
22 Gustaf's 9 5 24 - 500 21
Knckebrd g pkgs.

23 Tunnbrd 9 5 12 - 250 9
g pkgs.

24 Guaran Fantstica 10 1 12 - 355 4.5


ml cans

25 NuNuCa Nu- 11 3 20 - 450 14


Nougat-Creme g glasses

26 Gumbr 11 3 100 - 31.23


Gummibrchen 250 g
bags

27 Schoggi 11 3 100 - 43.9


Schokolade 100 g
pieces

28 Rssle Sauerkraut 12 7 25 - 825 45.6


g cans

29 Thringer 12 6 50 bags 123.79


Rostbratwurst x 30
sausgs.

30 Nord-Ost 13 8 10 - 200 25.89


Matjeshering g glasses

31 Gorgonzola Telino 14 4 12 - 100 12.5


g pkgs

32 Mascarpone Fabioli 14 4 24 - 200 32


g pkgs.

33 Geitost 15 4 500 g 2.5

34 Sasquatch Ale 16 1 24 - 12 14
oz
bottles

35 Steeleye Stout 16 1 24 - 12 18
oz
bottles

36 Inlagd Sill 17 8 24 - 250 19


g jars

37 Gravad lax 17 8 12 - 500 26

279
g pkgs.

38 Cte de Blaye 18 1 12 - 75 263.5


cl bottles

39 Chartreuse verte 18 1 750 cc 18


per
bottle

40 Boston Crab Meat 19 8 24 - 4 oz 18.4


tins

41 Jack's New England 19 8 12 - 12 9.65


Clam Chowder oz cans

42 Singaporean 20 5 32 - 1 kg 14
Hokkien Fried Mee pkgs.

43 Ipoh Coffee 20 1 16 - 500 46


g tins

44 Gula Malacca 20 2 20 - 2 kg 19.45


bags

45 Rgede sild 21 8 1k pkg. 9.5

46 Spegesild 21 8 4 - 450 g 12
glasses

47 Zaanse koeken 22 3 10 - 4 oz 9.5


boxes

48 Chocolade 22 3 10 pkgs. 12.75

49 Maxilaku 23 3 24 - 50 g 20
pkgs.

50 Valkoinen suklaa 23 3 12 - 100 16.25


g bars

51 Manjimup Dried 24 7 50 - 300 53


Apples g pkgs.

52 Filo Mix 24 5 16 - 2 kg 7
boxes

53 Perth Pasties 24 6 48 32.8


pieces

54 Tourtire 25 6 16 pies 7.45

280
55 Pt chinois 25 6 24 boxes 24
x 2 pies

56 Gnocchi di nonna 26 5 24 - 250 38


Alice g pkgs.

57 Ravioli Angelo 26 5 24 - 250 19.5


g pkgs.

58 Escargots de 27 8 24 13.25
Bourgogne pieces

59 Raclette 28 4 5 kg 55
Courdavault pkg.

60 Camembert Pierrot 28 4 15 - 300 34


g rounds

61 Sirop d'rable 29 2 24 - 500 28.5


ml
bottles

62 Tarte au sucre 29 3 48 pies 49.3

63 Vegie-spread 7 2 15 - 625 43.9


g jars

64 Wimmers gute 12 5 20 bags 33.25


Semmelkndel x4
pieces

65 Louisiana Fiery Hot 2 2 32 - 8 oz 21.05


Pepper Sauce bottles

66 Louisiana Hot 2 2 24 - 8 oz 17
Spiced Okra jars

67 Laughing 16 1 24 - 12 14
Lumberjack Lager oz
bottles

68 Scottish 8 3 10 boxes 12.5


Longbreads x8
pieces

69 Gudbrandsdalsost 15 4 10 kg 36
pkg.

70 Outback Lager 7 1 24 - 355 15


ml

281
bottles

71 Fltemysost 15 4 10 - 500 21.5


g pkgs.

72 Mozzarella di 14 4 24 - 200 34.8


Giovanni g pkgs.

73 Rd Kaviar 17 8 24 - 150 15
g jars

74 Longlife Tofu 4 7 5 kg 10
pkg.

75 Rhnbru 12 1 24 - 0.5 l 7.75


Klosterbier bottles

76 Lakkalikri 23 1 500 ml 18

77 Original Frankfurter 12 2 12 boxes 13


grne Soe

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;

282
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 CREATE TABLE Statement

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.

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

284
Create Table Using Another Table

A copy of an existing table can be created using a combination of the


CREATE TABLE statement and the SELECT statement.

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

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

SQL Statement:
DROP TABLE Shippers;

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL

285
Result:
You have made changes to the database.

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

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;

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):

ALTER TABLE table_name


DROP COLUMN column_name;

ALTER TABLE - ALTER/MODIFY COLUMN

To change the data type of a column in a table, use the following


syntax:

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

287
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

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.

288
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,
....
);

289
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 - Use to create and retrieve data from the database very
quickly

SQL NOT NULL Constraint

The NOT NULL constraint enforces a field to always contain a value.

SQL NOT NULL Constraint

By default, a column can hold NULL values. The NOT NULL constraint
enforces a column to NOT accept NULL values.

The NOT NULL constraint enforces a field to always contain a value. This
means that you cannot insert a new record, or update a record without
adding a value to this field.

The following SQL ensures that the "ID", "LastName", and "FirstName"
columns will NOT accept NULL values:

290
Example
SQL Statement:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
You have made changes to the database.

Tip: If the table has already been created, you can add a NOT NULL
constraint to a column with the ALTER TABLE statement.

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,

291
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,
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);

292
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


database table.

Primary keys must contain UNIQUE values, and cannot contain NULL
values.

A table can have only one primary key, which may consist of single or
multiple 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,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

293
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:

294
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).

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 in a table points to a PRIMARY KEY in another table.

Look at the following two tables:

"Persons" table:

PersonID LastName FirstName Age

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

296
The FOREIGN KEY constraint is used to prevent actions that would
destroy links between tables.

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

297
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:

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

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.

298
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
you can not have any person below 18 years:

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:

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

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

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.

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),
300
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 / 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;

301
SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ALTER COLUMN City DROP DEFAULT;

SQL CREATE INDEX Statement

The CREATE INDEX statement is used to create indexes in tables.

Indexes are used to retrieve data from the database very fast. 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);

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

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 "ID" column to be an auto-


increment primary key field in the "Persons" table:

303
CREATE TABLE Persons (
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

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 "ID" 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 "ID" 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 "ID" column to be an auto-


increment primary key field in the "Persons" table:

CREATE TABLE Persons (


ID int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

304
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 "ID" 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 "ID" 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 "ID" 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 "ID" column to be an auto-


increment primary key field in the "Persons" table:

CREATE TABLE Persons (


ID Integer PRIMARY KEY AUTOINCREMENT,
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 "ID" column should start at value 10 and
increment by 5, change the autoincrement to AUTOINCREMENT(10,5).

305
To insert a new record into the "Persons" table, we will NOT have to
specify a value for the "ID" 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 "P_Id" 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 (ID,FirstName,LastName)


VALUES (seq_person.nextval,'Lars','Monsen');

The SQL statement above would insert a new record into the "Persons"
table. The "ID" 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".

306
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

If you have the Northwind database you can see that it has several
views installed by default.

The view "Current Product List" lists all active products (products that
are not discontinued) from the "Products" table. The view is created with
the following SQL:

CREATE VIEW [Current Product List] AS


SELECT ProductID, ProductName
FROM Products
WHERE Discontinued = No;

Then, we can query the view as follows:

SELECT * FROM [Current Product List];

307
Another view in the Northwind sample database selects every product in
the "Products" table with a unit price higher than the average unit price:

CREATE VIEW [Products Above Average Price] AS


SELECT ProductName, UnitPrice
FROM Products
WHERE UnitPrice > (SELECT AVG(UnitPrice) FROM Products);

We can query the view above as follows:

SELECT * FROM [Products Above Average Price];

Another view in the Northwind database calculates the total sale for
each category in 1997. Note that this view selects its data from another
view called "Product Sales for 1997":

CREATE VIEW [Category Sales For 1997] AS


SELECT DISTINCT CategoryName, Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName;

We can query the view above as follows:

SELECT * FROM [Category Sales For 1997];

We can also add a condition to the query. Let's see the total sale only
for the category "Beverages":

SELECT * FROM [Category Sales For 1997]


WHERE CategoryName = 'Beverages';

SQL Updating a View

You can update a view by using the following syntax:

SQL CREATE OR REPLACE VIEW Syntax


CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Now we want to add the "Category" column to the "Current Product List"
view. We will update the view with the following SQL:

308
CREATE OR REPLACE VIEW [Current Product List] AS
SELECT ProductID, ProductName, Category
FROM Products
WHERE Discontinued = No;

SQL Dropping a View

You can delete a view with the DROP VIEW command.

SQL DROP VIEW Syntax


DROP VIEW view_name;

SQL Injection

An SQL Injection can destroy your database.

SQL in Web Pages

In the previous chapters, you have learned to retrieve (and update)


database data, using SQL.

When SQL is used to display data on a web page, it is common to let


web users input their own search values.

Since SQL statements are text only, it is easy, with a little piece of
computer code, to dynamically change SQL statements to provide the
user with selected data:

Server Code
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;

The example above, creates a select statement by adding a variable


(txtUserId) to a select string. The variable is fetched from the user input
(Request) to the page.

The rest of this chapter describes the potential dangers of using user
input in SQL statements

SQL Injection

309
SQL injection is a technique where malicious users can inject SQL
commands into an SQL statement, via web page input.

Injected SQL commands can alter SQL statement and compromise the
security of a web application.

SQL Injection Based on 1=1 is Always True

Look at the example above, one more time.

Let's say that 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:
105 or 1=1

Server Result
SELECT * FROM Users WHERE UserId = 105 or 1=1;

The SQL above is valid. It will return all rows from the table Users,
since WHERE 1=1 is always true.

Does the example above seem 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 smart hacker might get access to all the user names and passwords in
a database by simply inserting 105 or 1=1 into the input box.

SQL Injection Based on ""="" is Always True

Here is a common construction, used to verify user login to a web site:

User Name:
John Doe

310
Password:
myPass

Server Code
uName = getRequestString("UserName");
uPass = getRequestString("UserPass");

sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass
="' + uPass + '"'

Result
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"

A smart 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 result SQL is valid. It will return all rows from the table Users,
since WHERE ""="" is always true.

SQL Injection Based on Batched SQL Statements

Most databases support batched SQL statement, separated by


semicolon.

Example
SELECT * FROM Users; DROP TABLE Suppliers

The SQL above will return all rows in the Users table, and then delete
the table called Suppliers.

311
If we had the following server code:

Server Code
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;

And the following input:

User id:
105; DROP

The code at the server would create a valid SQL statement like this:

Result
SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers

Parameters for Protection

Some web developers use a "blacklist" of words or characters to search


for in SQL input, to prevent SQL injection attacks.

This is not a very good idea. Many of these words (like delete or drop)
and characters (like semicolons and quotation marks), are used in
common language, and should be allowed in many types of input.

(In fact it should be perfectly legal to input an SQL statement in a


database field.)

The only proven way to protect a web site from SQL injection attacks, is
to 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.

312
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);

You have just learned to avoid SQL injection. One of the top website
vulnerabilities.

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");
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)
313
VALUES (:nam, :add, :cit)");
$stmt->bindParam(':nam', $txtNam);
$stmt->bindParam(':add', $txtAdd);
$stmt->bindParam(':cit', $txtCit);
$stmt->execute();

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.

314
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

SQL Functions

SQL has many built-in functions for performing calculations on data.

SQL Aggregate Functions

SQL aggregate functions return a single value, calculated from values in


a column.

Function Description

AVG() Returns the average value

COUNT() Returns the number of rows

FIRST() Returns the first value

315
LAST() Returns the last value

MAX() Returns the largest value

MIN() Returns the smallest value

ROUND() Rounds a numeric field to the number of decimals specified

SUM() Returns the sum

SQL String Functions

Function Description

CHARINDEX Searches an expression in a string expression and returns its starting


position if found

CONCAT()

LEFT()

LEN() / LENGTH() Returns the length of the value in a text field

316
LOWER() / Converts character data to lower case
LCASE()

LTRIM()

SUBSTRING() / Extract characters from a text field


MID()

PATINDEX()

REPLACE()

RIGHT()

RTRIM()

UPPER() / Converts character data to upper case


UCASE()

SQL Date Functions


MySQL Date Functions

The following table lists the most important built-in date functions in
MySQL:

317
Function Description

NOW() Returns the current date and time

CURDATE() Returns the current date

CURTIME() Returns the current time

DATE() Extracts the date part of a date or date/time


expression

EXTRACT() Returns a single part of a date/time

DATE_ADD() Adds a specified time interval to a date

DATE_SUB() Subtracts a specified time interval from a date

DATEDIFF() Returns the number of days between two dates

DATE_FORMAT() Displays date/time data in different formats

SQL Server Date Functions

The following table lists the most important built-in date functions in
SQL Server:
318
Function Description

GETDATE() Returns the current date and time

DATEPART() Returns a single part of a date/time

DATEADD() Adds or subtracts a specified time interval from a date

DATEDIFF() Returns the time between two dates

CONVERT() Displays date/time data in different formats

SQL Date and Time Data Types and Functions

Function Description

FORMAT() Formats how a field is to be displayed

NOW() Returns the current system date and time

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.

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

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!

For an overview of all data types available, go to our complete Data


Types reference.

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

320
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):

321
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: If you want to keep your queries simple and easy to maintain, do
not allow time components in your dates!

SQL NULL Functions


SQL ISNULL(), NVL(), IFNULL() and COALESCE() Functions

Look at the following "Products" table:

P_Id ProductName UnitPrice UnitsInStock UnitsOnOrder

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

We have 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 is NULL.

Microsoft's ISNULL() function is used to specify how we want to treat


NULL values.

The NVL(), IFNULL(), and COALESCE() functions can also be used to


achieve the same result.

In this case we want NULL values to be zero.

Below, if "UnitsOnOrder" is NULL it will not harm the calculation,


because ISNULL() returns a zero if the value is NULL:

MS Access

SELECT ProductName,UnitPrice*(UnitsInStock+IIF(ISNULL(UnitsOnOrder
),0,UnitsOnOrder))
FROM Products

SQL Server

SELECT ProductName,UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0))
FROM Products

323
Oracle

Oracle does not have an ISNULL() function. However, we can use the
NVL() function to achieve the same result:

SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0))
FROM Products

MySQL

MySQL does have an ISNULL() function. However, it works a little bit


different from Microsoft's ISNULL() function.

In MySQL we can use the IFNULL() function, like this:

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

SQL Operators
SQL Arithmetic Operators

Operator Description Example

30 +
+ Add 20

50

30 -
- Subtract 20

10

324
30 *
* Multiply 20

600

Number of
/ Divide Records: 1

30 /
10

17 %
% Modulo 5

SQL Bitwise Operators

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

SQL Comparison Operators

O De Example
pe scr
ra ipti
to

325
r on

= Equ
al ProductI ProductNa SupplierI CategoryI Unit Pric
D me D D e
to
1 Chais 1 1 10 18
boxes
x 20
bags

35 Steeleye 16 1 24 - 18
Stout 12 oz
bottle
s

39 Chartreuse 18 1 750 18
verte cc
per
bottle

76 Lakkalikri 23 1 500 18
ml

Product ProductNam Supplier Category Unit Price


> Gre ID e ID ID
ate
r 8 Northwoods 3 2 12 - 40
tha Cranberry 12 oz
n Sauce jars

9 Mishi Kobe 4 6 18 - 97
Niku 500 g
pkgs.

10 Ikura 4 8 12 - 31
200
ml
jars

12 Queso 5 4 10 - 38
Manchego La 500 g
Pastora pkgs.

17 Alice Mutton 7 6 20 - 1 39
kg

326
tins

18 Carnarvon 7 8 16 kg 62.5
Tigers pkg.

20 Sir Rodney's 8 3 30 81
Marmalade gift
boxes

26 Gumbr 11 3 100 - 31.23


Gummibrche 250 g
n bags

27 Schoggi 11 3 100 - 43.9


Schokolade 100 g
piece
s

28 Rssle 12 7 25 - 45.6
Sauerkraut 825 g
cans

29 Thringer 12 6 50 123.7
Rostbratwurst bags 9
x 30
sausg
s.

32 Mascarpone 14 4 24 - 32
Fabioli 200 g
pkgs.

38 Cte de Blaye 18 1 12 - 263.5


75 cl
bottle
s

43 Ipoh Coffee 20 1 16 - 46
500 g
tins

51 Manjimup 24 7 50 - 53
Dried Apples 300 g
pkgs.

53 Perth Pasties 24 6 48 32.8


piece
s

327
56 Gnocchi di 26 5 24 - 38
nonna Alice 250 g
pkgs.

59 Raclette 28 4 5 kg 55
Courdavault pkg.

60 Camembert 28 4 15 - 34
Pierrot 300 g
round
s

62 Tarte au sucre 29 3 48 49.3


pies

63 Vegie-spread 7 2 15 - 43.9
625 g
jars

64 Wimmers gute 12 5 20 33.25


Semmelknde bags
l x4
piece
s

69 Gudbrandsdal 15 4 10 kg 36
sost pkg.

72 Mozzarella di 14 4 24 - 34.8
Giovanni 200 g
pkgs.

ProductID ProductName
< Les
s 1 Chais
tha
n 2 Chang

3 Aniseed Syrup

4 Chef Anton's Cajun Seasoning

5 Chef Anton's Gumbo Mix

6 Grandma's Boysenberry Spread

11 Queso Cabrales

328
13 Konbu

14 Tofu

15 Genen Shouyu

16 Pavlova

19 Teatime Chocolate Biscuits

21 Sir Rodney's Scones

22 Gustaf's Knckebrd

23 Tunnbrd

24 Guaran Fantstica

25 NuNuCa Nu-Nougat-Creme

30 Nord-Ost Matjeshering

31 Gorgonzola Telino

33 Geitost

34 Sasquatch Ale

35 Steeleye Stout

36 Inlagd Sill

37 Gravad lax

39 Chartreuse verte

40 Boston Crab Meat

41 Jack's New England Clam Chowder

42 Singaporean Hokkien Fried Mee

44 Gula Malacca

45 Rgede sild

46 Spegesild

47 Zaanse koeken

329
48 Chocolade

49 Maxilaku

50 Valkoinen suklaa

52 Filo Mix

54 Tourtire

55 Pt chinois

57 Ravioli Angelo

58 Escargots de Bourgogne

61 Sirop d'rable

65 Louisiana Fiery Hot Pepper Sauce

66 Louisiana Hot Spiced Okra

67 Laughing Lumberjack Lager

68 Scottish Longbreads

70 Outback Lager

71 Fltemysost

73 Rd Kaviar

74 Longlife Tofu

75 Rhnbru Klosterbier

76 Lakkalikri

77 Original Frankfurter grne Soe

ProductID ProductName
> Gre
= ate 7 Uncle Bob's Organic Dried Pears
r
tha 8 Northwoods Cranberry Sauce
n
9 Mishi Kobe Niku
or
equ 10 Ikura

330
al 12 Queso Manchego La Pastora
to
17 Alice Mutton

18 Carnarvon Tigers

20 Sir Rodney's Marmalade

26 Gumbr Gummibrchen

27 Schoggi Schokolade

28 Rssle Sauerkraut

29 Thringer Rostbratwurst

32 Mascarpone Fabioli

38 Cte de Blaye

43 Ipoh Coffee

51 Manjimup Dried Apples

53 Perth Pasties

56 Gnocchi di nonna Alice

59 Raclette Courdavault

60 Camembert Pierrot

62 Tarte au sucre

63 Vegie-spread

64 Wimmers gute Semmelkndel

69 Gudbrandsdalsost

72 Mozzarella di Giovanni

ProductID ProductName
< Les
= s 1 Chais
tha
n 2 Chang
or
3 Aniseed Syrup
equ

331
al 4 Chef Anton's Cajun Seasoning
to
5 Chef Anton's Gumbo Mix

6 Grandma's Boysenberry Spread

7 Uncle Bob's Organic Dried Pears

11 Queso Cabrales

13 Konbu

14 Tofu

15 Genen Shouyu

16 Pavlova

19 Teatime Chocolate Biscuits

21 Sir Rodney's Scones

22 Gustaf's Knckebrd

23 Tunnbrd

24 Guaran Fantstica

25 NuNuCa Nu-Nougat-Creme

30 Nord-Ost Matjeshering

31 Gorgonzola Telino

33 Geitost

34 Sasquatch Ale

35 Steeleye Stout

36 Inlagd Sill

37 Gravad lax

39 Chartreuse verte

40 Boston Crab Meat

41 Jack's New England Clam Chowder

332
42 Singaporean Hokkien Fried Mee

44 Gula Malacca

45 Rgede sild

46 Spegesild

47 Zaanse koeken

48 Chocolade

49 Maxilaku

50 Valkoinen suklaa

52 Filo Mix

54 Tourtire

55 Pt chinois

57 Ravioli Angelo

58 Escargots de Bourgogne

61 Sirop d'rable

65 Louisiana Fiery Hot Pepper Sauce

66 Louisiana Hot Spiced Okra

67 Laughing Lumberjack Lager

68 Scottish Longbreads

70 Outback Lager

71 Fltemysost

73 Rd Kaviar

74 Longlife Tofu

75 Rhnbru Klosterbier

76 Lakkalikri

77 Original Frankfurter grne Soe

333
ProductID ProductName
< Not
> equ 2 Chang
al
to 3 Aniseed Syrup

4 Chef Anton's Cajun Seasoning

5 Chef Anton's Gumbo Mix

6 Grandma's Boysenberry Spread

7 Uncle Bob's Organic Dried Pears

8 Northwoods Cranberry Sauce

9 Mishi Kobe Niku

10 Ikura

11 Queso Cabrales

12 Queso Manchego La Pastora

13 Konbu

14 Tofu

15 Genen Shouyu

16 Pavlova

17 Alice Mutton

18 Carnarvon Tigers

19 Teatime Chocolate Biscuits

20 Sir Rodney's Marmalade

21 Sir Rodney's Scones

22 Gustaf's Knckebrd

23 Tunnbrd

24 Guaran Fantstica

25 NuNuCa Nu-Nougat-Creme

334
26 Gumbr Gummibrchen

27 Schoggi Schokolade

28 Rssle Sauerkraut

29 Thringer Rostbratwurst

30 Nord-Ost Matjeshering

31 Gorgonzola Telino

32 Mascarpone Fabioli

33 Geitost

34 Sasquatch Ale

36 Inlagd Sill

37 Gravad lax

38 Cte de Blaye

40 Boston Crab Meat

41 Jack's New England Clam Chowder

42 Singaporean Hokkien Fried Mee

43 Ipoh Coffee

44 Gula Malacca

45 Rgede sild

46 Spegesild

47 Zaanse koeken

48 Chocolade

49 Maxilaku

50 Valkoinen suklaa

51 Manjimup Dried Apples

52 Filo Mix

335
53 Perth Pasties

54 Tourtire

55 Pt chinois

56 Gnocchi di nonna Alice

57 Ravioli Angelo

58 Escargots de Bourgogne

59 Raclette Courdavault

60 Camembert Pierrot

61 Sirop d'rable

62 Tarte au sucre

63 Vegie-spread

64 Wimmers gute Semmelkndel

65 Louisiana Fiery Hot Pepper Sauce

66 Louisiana Hot Spiced Okra

67 Laughing Lumberjack Lager

68 Scottish Longbreads

69 Gudbrandsdalsost

70 Outback Lager

71 Fltemysost

72 Mozzarella di Giovanni

73 Rd Kaviar

74 Longlife Tofu

75 Rhnbru Klosterbier

77 Original Frankfurter grne Soe

336
SQL Compound Operators

Operator Description

+= Add equals

-= Subtract equals

*= Multiply equals

/= Divide equals

%= Modulo equals

&= Bitwise AND equals

^-= Bitwise exclusive equals

|*= Bitwise OR equals

337
SQL Logical Operators

Ope Desc Example


rato ripti
r on

ALL TRUE No result.


if all
of a
set of
comp
ariso
ns
are
TRUE

Number of Records: 6
AND TRUE
if Custo Custome Contac Addres Cit Postal Cou
merID rName tName s y Code ntry
both
expre 4 Around Thomas 120 Lon WA1 UK
ssion the Horn Hardy Hanove don 1DP
s are r Sq.
TRUE
11 B's Victoria Fauntle Lon EC2 UK
Beverage Ashwort roy don 5NT
s h Circus

16 Consolida Elizabet Berkele Lon WX1 UK


ted h Brown y don 6LT
Holdings Garden
s 12
Brewer
y

19 Eastern Ann 35 King Lon WX3 UK


Connecti Devon George don 6FW
on

53 North/So Simon South Lon SW7 UK


uth Crowthe House don 1RZ
r 300

338
Queens
bridge

72 Seven Hari 90 Lon OX15 UK


Seas Kumar Wadhur don 4NB
Imports st Rd.

Error
ANY TRUE
if any
one
of a
set of
comp
ariso
ns
are
TRUE

Product ProductNa Supplier Category Uni Pric


BET TRUE ID me ID ID t e
WEE if the
N opera 51 Manjimup 24 7 50 - 53
nd is Dried Apples 300
withi g
pkg
n the s.
range
of 59 Raclette 28 4 5 kg 55
comp Courdavault pkg.
ariso
ns

Product ProductNa Supplie Categor Unit Pric


EXI TRUE ID me rID yID e
STS if a
subq 1 Chais 1 1 10 18
uery boxe
conta sx
20
ins bags
any
2 Chang 1 1 24 - 19

339
rows 12 oz
bottl
es

3 Aniseed 1 2 12 - 10
Syrup 550
ml
bottl
es

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

5 Chef Anton's 2 2 36 21.3


Gumbo Mix boxe 5
s

6 Grandma's 3 2 12 - 25
Boysenberry 8 oz
Spread jars

7 Uncle Bob's 3 7 12 - 30
Organic 1 lb
Dried Pears pkgs.

8 Northwoods 3 2 12 - 40
Cranberry 12 oz
Sauce jars

9 Mishi Kobe 4 6 18 - 97
Niku 500
g
pkgs.

10 Ikura 4 8 12 - 31
200
ml
jars

11 Queso 5 4 1 kg 21
Cabrales pkg.

12 Queso 5 4 10 - 38
Manchego La 500
Pastora g
pkgs.

13 Konbu 6 8 2 kg 6

340
box

14 Tofu 6 7 40 - 23.2
100 5
g
pkgs.

15 Genen 6 2 24 - 15.5
Shouyu 250
ml
bottl
es

16 Pavlova 7 3 32 - 17.4
500 5
g
boxe
s

17 Alice Mutton 7 6 20 - 39
1 kg
tins

18 Carnarvon 7 8 16 kg 62.5
Tigers pkg.

19 Teatime 8 3 10 9.2
Chocolate boxe
Biscuits sx
12
piece
s

20 Sir Rodney's 8 3 30 81
Marmalade gift
boxe
s

21 Sir Rodney's 8 3 24 10
Scones pkgs.
x4
piece
s

22 Gustaf's 9 5 24 - 21
Knckebrd 500
g
pkgs.

341
23 Tunnbrd 9 5 12 - 9
250
g
pkgs.

24 Guaran 10 1 12 - 4.5
Fantstica 355
ml
cans

25 NuNuCa 11 3 20 - 14
Nu-Nougat- 450
Creme g
glass
es

26 Gumbr 11 3 100 - 31.2


Gummibrch 250 3
en g
bags

27 Schoggi 11 3 100 - 43.9


Schokolade 100
g
piece
s

28 Rssle 12 7 25 - 45.6
Sauerkraut 825
g
cans

29 Thringer 12 6 50 123.
Rostbratwurs bags 79
t x 30
saus
gs.

30 Nord-Ost 13 8 10 - 25.8
Matjeshering 200 9
g
glass
es

31 Gorgonzola 14 4 12 - 12.5
Telino 100
g
pkgs

342
32 Mascarpone 14 4 24 - 32
Fabioli 200
g
pkgs.

33 Geitost 15 4 500 2.5


g

34 Sasquatch 16 1 24 - 14
Ale 12 oz
bottl
es

35 Steeleye 16 1 24 - 18
Stout 12 oz
bottl
es

36 Inlagd Sill 17 8 24 - 19
250
g jars

37 Gravad lax 17 8 12 - 26
500
g
pkgs.

38 Cte de 18 1 12 - 263.
Blaye 75 cl 5
bottl
es

39 Chartreuse 18 1 750 18
verte cc
per
bottl
e

40 Boston Crab 19 8 24 - 18.4


Meat 4 oz
tins

41 Jack's New 19 8 12 - 9.65


England 12 oz
Clam cans
Chowder

42 Singaporean 20 5 32 - 14
Hokkien 1 kg

343
Fried Mee pkgs.

43 Ipoh Coffee 20 1 16 - 46
500
g tins

44 Gula Malacca 20 2 20 - 19.4


2 kg 5
bags

45 Rgede sild 21 8 1k 9.5


pkg.

46 Spegesild 21 8 4- 12
450
g
glass
es

47 Zaanse 22 3 10 - 9.5
koeken 4 oz
boxe
s

48 Chocolade 22 3 10 12.7
pkgs. 5

49 Maxilaku 23 3 24 - 20
50 g
pkgs.

50 Valkoinen 23 3 12 - 16.2
suklaa 100 5
g
bars

51 Manjimup 24 7 50 - 53
Dried Apples 300
g
pkgs.

52 Filo Mix 24 5 16 - 7
2 kg
boxe
s

53 Perth Pasties 24 6 48 32.8


piece
s

344
54 Tourtire 25 6 16 7.45
pies

55 Pt chinois 25 6 24 24
boxe
sx2
pies

56 Gnocchi di 26 5 24 - 38
nonna Alice 250
g
pkgs.

57 Ravioli 26 5 24 - 19.5
Angelo 250
g
pkgs.

58 Escargots de 27 8 24 13.2
Bourgogne piece 5
s

59 Raclette 28 4 5 kg 55
Courdavault pkg.

60 Camembert 28 4 15 - 34
Pierrot 300
g
roun
ds

61 Sirop 29 2 24 - 28.5
d'rable 500
ml
bottl
es

62 Tarte au 29 3 48 49.3
sucre pies

63 Vegie-spread 7 2 15 - 43.9
625
g jars

64 Wimmers 12 5 20 33.2
gute bags 5
Semmelknd x4
el piece
s

345
65 Louisiana 2 2 32 - 21.0
Fiery Hot 8 oz 5
Pepper bottl
Sauce es

66 Louisiana Hot 2 2 24 - 17
Spiced Okra 8 oz
jars

67 Laughing 16 1 24 - 14
Lumberjack 12 oz
Lager bottl
es

68 Scottish 8 3 10 12.5
Longbreads boxe
sx8
piece
s

69 Gudbrandsda 15 4 10 kg 36
lsost pkg.

70 Outback 7 1 24 - 15
Lager 355
ml
bottl
es

71 Fltemysost 15 4 10 - 21.5
500
g
pkgs.

72 Mozzarella di 14 4 24 - 34.8
Giovanni 200
g
pkgs.

73 Rd Kaviar 17 8 24 - 15
150
g jars

74 Longlife Tofu 4 7 5 kg 10
pkg.

75 Rhnbru 12 1 24 - 7.75
Klosterbier 0.5 l
bottl

346
es

76 Lakkalikri 23 1 500 18
ml

77 Original 12 2 12 13
Frankfurter boxe
grne Soe s

Custo Custome Contac Addres Cit Postal Cou


IN TRUE merID rName tName s y Code ntry
if the
opera 4 Around Thomas 120 Lon WA1 UK
nd is the Horn Hardy Hanove don 1DP
equal r Sq.
to 11 B's Victoria Fauntle Lon EC2 UK
one Beverage Ashwort roy don 5NT
of a s h Circus
list of
expre 16 Consolida Elizabet Berkele Lon WX1 UK
ssion ted h Brown y don 6LT
Holdings Garden
s
s 12
Brewer
y

19 Eastern Ann 35 King Lon WX3 UK


Connecti Devon George don 6FW
on

53 North/So Simon South Lon SW7 UK


uth Crowthe House don 1RZ
r 300
Queens
bridge

57 Paris Marie 265, Pari 75012 Fran


spcialit Bertran bouleva s ce
s d rd
Charon
ne

72 Seven Hari 90 Lon OX15 UK


Seas Kumar Wadhur don 4NB
Imports st Rd.

74 Spcialit Dominiq 25, rue Pari 75016 Fran

347
s du ue Laurist s ce
monde Perrier on

109 Aux null null Pari null Fran


joyeux s ce
ecclsiast
iques

138 Aux null null Pari null Fran


joyeux s ce
ecclsiast
iques

167 Aux null null Pari null Fran


joyeux s ce
ecclsiast
iques

196 Aux Guylne 203, Pari 75004 Fran


joyeux Nodier Rue s ce
ecclsiast des
iques Francs-
Bourge
ois

231 Aux null null Pari null Fran


joyeux s ce
ecclsiast
iques

260 Aux Guylne 203, Pari 75004 Fran


joyeux Nodier Rue s ce
ecclsiast des
iques Francs-
Bourge
ois

Custo Custom Contac Addre City Posta Cou


LIKE TRUE merID erName tName ss lCode ntry
if the
opera 7 Blondel Frdri 24, Stras 67000 Fran
nd pre et que place bourg ce
matc fils Citeaux Klber
hes a 15 Comrci Pedro Av. dos So 05432 Brazi
patte o Mineiro Afonso Lusada Paulo -043 l
rn s, 23

348
21 Familia Aria Rua So 05442 Brazi
Arquibal Cruz Ors, Paulo -030 l
do 92

30 Godos Jos C/ Sevill 41101 Spai


Cocina Pedro Romer a n
Tpica Freyre o, 33

35 HILARI Carlos Carrera San 5022 Vene


N- Hernn 22 con Crist zuela
Abastos dez Ave. bal
Carlos
Soublet
te #8-
35

45 Let's Jaime 87 Polk San 94117 USA


Stop N Yorres St. Franc
Shop Suite 5 isco

59 Piccolo Georg Geislw Salzb 5020 Austr


und Pipps eg 14 urg ia
mehr

62 Queen Lcia Alamed So 05487 Brazi


Cozinha Carvalh a dos Paulo -020 l
o Canri
os, 891

70 Sant Jonas Erling Stave 4110 Norw


Gourmet Bergulf Skakke rn ay
sen s gate
78

81 Tradio Anabela Av. So 05634 Brazi


Hiperme Doming Ins de Paulo -030 l
rcados ues Castro,
414

86 Die Rita Adenau Stutt 70563 Ger


Wandern Mller erallee gart man
de Kuh 900 y

89 White Karl 305 - Seattl 98128 USA


Clover Jablons 14th e
Markets ki Ave. S.
Suite
3B

349
101 Refresco null null So null Brazi
s Paulo l
America
nas
LTDA

106 Norske null null Sand null Norw


Meierier vika ay

108 Svensk null null Stock null Swed


Sjfda holm en
AB

111 Leka null null Singa null Sing


Trading pore apor
e

115 G'day, null null Sydn null Austr


Mate ey alia

117 Pasta null null Saler null Italy


Buttini no
s.r.l.

120 Forts null null Ste- null Cana


d'rables Hyaci da
nthe

130 Refresco null null So null Brazi


s Paulo l
America
nas
LTDA

135 Norske null null Sand null Norw


Meierier vika ay

137 Svensk null null Stock null Swed


Sjfda holm en
AB

140 Leka null null Singa null Sing


Trading pore apor
e

144 G'day, null null Sydn null Austr


Mate ey alia

146 Pasta null null Saler null Italy

350
Buttini no
s.r.l.

149 Forts null null Ste- null Cana


d'rables Hyaci da
nthe

159 Refresco null null So null Brazi


s Paulo l
America
nas
LTDA

164 Norske null null Sand null Norw


Meierier vika ay

166 Svensk null null Stock null Swed


Sjfda holm en
AB

169 Leka null null Singa null Sing


Trading pore apor
e

173 G'day, null null Sydn null Austr


Mate ey alia

175 Pasta null null Saler null Italy


Buttini no
s.r.l.

178 Forts null null Ste- null Cana


d'rables Hyaci da
nthe

188 Refresco Carlos Av. das So 5442 Brazi


s Diaz Americ Paulo l
America anas
nas 12.890
LTDA

193 Norske Beate Hatleve Sand 1320 Norw


Meierier Vileid gen 5 vika ay

195 Svensk Michael Brovall Stock S-123 Swed


Sjfda Bjrn avgen holm 45 en
AB 231

198 Leka Chandr 471 Singa 0512 Sing

351
Trading a Leka Serang pore apor
oon e
Loop,
Suite
#402

202 G'day, Wendy 170 Sydn 2042 Austr


Mate Macken Prince ey alia
zie Edward
Parade
Hunter'
s Hill

204 Pasta Giovan Via dei Saler 84100 Italy


Buttini ni Gelsom no
s.r.l. Giudici ini, 153

207 Forts Chantal 148 Ste- J2S Cana


d'rables Goulet rue Hyaci 7S8 da
Chasse nthe
ur

223 Refresco null null So null Brazi


s Paulo l
America
nas
LTDA

228 Norske null null Sand null Norw


Meierier vika ay

230 Svensk null null Stock null Swed


Sjfda holm en
AB

233 Leka null null Singa null Sing


Trading pore apor
e

237 G'day, null null Sydn null Austr


Mate ey alia

239 Pasta null null Saler null Italy


Buttini no
s.r.l.

242 Forts null null Ste- null Cana


d'rables Hyaci da
nthe

352
252 Refresco Carlos Av. das So 5442 Brazi
s Diaz Americ Paulo l
America anas
nas 12.890
LTDA

257 Norske Beate Hatleve Sand 1320 Norw


Meierier Vileid gen 5 vika ay

259 Svensk Michael Brovall Stock S-123 Swed


Sjfda Bjrn avgen holm 45 en
AB 231

262 Leka Chandr 471 Singa 0512 Sing


Trading a Leka Serang pore apor
oon e
Loop,
Suite
#402

266 G'day, Wendy 170 Sydn 2042 Austr


Mate Macken Prince ey alia
zie Edward
Parade
Hunter'
s Hill

268 Pasta Giovan Via dei Saler 84100 Italy


Buttini ni Gelsom no
s.r.l. Giudici ini, 153

271 Forts Chantal 148 Ste- J2S Cana


d'rables Goulet rue Hyaci 7S8 da
Chasse nthe
ur

Cust Customer Conta Addre City Post Cou


NOT Rever omer Name ctNam ss alCo ntry
ses ID e de
the
value 1 Alfreds Maria Obere Berlin 1220 Germ
of Futterkiste Anders Str. 57 9 any
any 2 Ana Ana Avda. Mxic 0502 Mexi
other Trujillo Trujillo de la o D.F. 1 co
opera Empareda Constit
tor dos y ucin
helados 2222

353
3 Antonio Antoni Matade Mxic 0502 Mexi
Moreno o ros o D.F. 3 co
Taquera Moren 2312
o

4 Around the Thoma 120 Londo WA1 UK


Horn s Hanove n 1DP
Hardy r Sq.

5 Berglunds Christi Berguv Lule S- Swed


snabbkp na svgen 958 en
Berglu 8 22
nd

6 Blauer See Hanna Forster Mann 6830 Germ


Delikatess Moos str. 57 heim 6 any
en

8 Blido Martn C/ Madri 2802 Spai


Comidas Somm Araquil d 3 n
preparadas er , 67

9 Bon app' Lauren 12, rue Marse 1300 Franc


ce des ille 8 e
Lebiha Bouche
ns rs

10 Bottom- Elizabe 23 Tsawa T2F Cana


Dollar th Tsawas ssen 8M4 da
Marketse Lincoln sen
Blvd.

11 B's Victori Fauntle Londo EC2 UK


Beverages a roy n 5NT
Ashwo Circus
rth

12 Cactus Patrici Cerrito Bueno 1010 Arge


Comidas o 333 s ntina
para llevar Simps Aires
on

13 Centro Francis Sierras Mxic 0502 Mexi


comercial co de o D.F. 2 co
Moctezum Chang Granad
a a 9993

14 Chop-suey Yang Haupts Bern 3012 Switz


Chinese Wang tr. 29 erlan

354
d

16 Consolidat Elizabe Berkele Londo WX1 UK


ed th y n 6LT
Holdings Brown Garden
s 12
Brewer
y

17 Drachenbl Sven Walser Aache 5206 Germ


ut Ottlieb weg 21 n 6 any
Delikatess
end

18 Du monde Janine 67, rue Nante 4400 Franc


entier Labrun des s 0 e
e Cinqua
nte
Otages

19 Eastern Ann 35 Londo WX3 UK


Connection Devon King n 6FW
George

20 Ernst Roland Kirchga Graz 8010 Austr


Handel Mendel sse 6 ia

22 FISSA Diego C/ Madri 2803 Spai


Fabrica Roel Moralz d 4 n
Inter. arzal,
Salchichas 86
S.A.

23 Folies Martin 184, Lille 5900 Franc


gourmand e chauss 0 e
es Ranc e de
Tournai

24 Folk och f Maria kerga Brck S- Swed


HB Larsso tan 24 e 844 en
n 67

25 Frankenve Peter Berline Mnc 8080 Germ


rsand Franke r Platz hen 5 any
n 43

26 France Carine 54, rue Nante 4400 Franc


restauratio Schmit Royale s 0 e
n t

355
27 Franchi Paolo Via Torino 1010 Italy
S.p.A. Accorti Monte 0
Bianco
34

28 Furia Lino Jardim Lisbo 1675 Portu


Bacalhau e Rodrig das a gal
Frutos do uez rosas
Mar n. 32

29 Galera del Eduard Rambla Barcel 0802 Spai


gastrnom o de ona 2 n
o Saave Catalu
dra a, 23

31 Gourmet Andr Av. Campi 0487 Brazi


Lanchonet Fonsec Brasil, nas 6- l
es a 442 786

32 Great Howar 2732 Eugen 9740 USA


Lakes Food d Baker e 3
Market Snyder Blvd.

33 GROSELLA Manuel 5 Ave. Carac 1081 Vene


- Pereira Los as zuela
Restaurant Palos
e Grande
s

34 Hanari Mario Rua do Rio de 0545 Brazi


Carnes Pontes Pao, Janeir 4- l
67 o 876

36 Hungry Yoshi City Elgin 9782 USA


Coyote Latime Center 7
Import r Plaza
Store 516
Main
St.

37 Hungry Patrici 8 Cork Irela


Owl All- a Johnst nd
Night McKen own
Grocers na Road

38 Island Helen Garden Cowe PO31 UK


Trading Bennet House s 7PJ
t Crowth
er Way

356
39 Kniglich Philip Maubel Brand 1477 Germ
Essen Crame str. 90 enbur 6 any
r g

40 La corne Daniel 67, Versai 7800 Franc


d'abondan Tonini avenue lles 0 e
ce de
l'Europ
e

41 La maison Annett 1 rue Toulo 3100 Franc


d'Asie e Alsace- use 0 e
Roulet Lorrain
e

42 Laughing Yoshi 1900 Vanco V3F Cana


Bacchus Tanna Oak St. uver 2K1 da
Wine muri
Cellars

43 Lazy K John 12 Walla 9936 USA


Kountry Steel Orches Walla 2
Store tra
Terrace

44 Lehmanns Renate Magazi Frank 6052 Germ


Marktstand Messn nweg 7 furt 8 any
er a.M.

46 LILA- Carlos Carrera Barqu 3508 Vene


Supermerc Gonzl 52 con isimet zuela
ado ez Ave. o
Bolvar
#65-98
Llano
Largo

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


Delicatese Izquier de Marga zuela
s do Mayo rita
Porlam
ar

48 Lonesome Fran 89 Portla 9721 USA


Pine Wilson Chiaros nd 9
Restaurant curo
Rd.

49 Magazzini Giovan Via Berga 2410 Italy

357
Alimentari ni Ludovic mo 0
Riuniti Rovelli o il
Moro
22

50 Maison Catheri Rue Bruxe B- Belgi


Dewey ne Joseph lles 1180 um
Dewey -Bens
532

51 Mre Jean 43 rue Montr H1J Cana


Paillarde Fresni St. al 1C3 da
re Laurent

52 Morgenste Alexan Heerstr Leipzi 0417 Germ


rn der . 22 g 9 any
Gesundkos Feuer
t

53 North/Sout Simon South Londo SW7 UK


h Crowth House n 1RZ
er 300
Queens
bridge

54 Ocano Yvonne Ing. Bueno 1010 Arge


Atlntico Monca Gustav s ntina
Ltda. da o Aires
Moncad
a 8585
Piso
20-A

55 Old World Rene 2743 Ancho 9950 USA


Delicatess Phillips Bering rage 8
en St.

56 Ottilies Henriet Mehrhe Kln 5073 Germ


Kseladen te imerstr 9 any
Pfalzhe . 369
im

57 Paris Marie 265, Paris 7501 Franc


spcialits Bertra boulev 2 e
nd ard
Charon
ne

58 Pericles Guiller Calle Mxic 0503 Mexi

358
Comidas mo Dr. o D.F. 3 co
clsicas Fernn Jorge
dez Cash
321

60 Princesa Isabel Estrada Lisbo 1756 Portu


Isabel de da a gal
Vinhoss Castro sade
n. 58

61 Que Bernar Rua da Rio de 0238 Brazi


Delcia do Panific Janeir 9- l
Batista adora, o 673
12

63 QUICK- Horst Tauche Cune 0130 Germ


Stop Kloss rstrae walde 7 any
10

64 Rancho Sergio Av. del Bueno 1010 Arge


grande Gutirr Liberta s ntina
ez dor Aires
900

65 Rattlesnak Paula 2817 Albuq 8711 USA


e Canyon Wilson Milton uerqu 0
Grocery Dr. e

66 Reggiani Maurizi Strada Reggi 4210 Italy


Caseifici o Provinc o 0
Moroni iale Emilia
124

67 Ricardo Janete Av. Rio de 0238 Brazi


Adocicados Limeir Copaca Janeir 9- l
a bana, o 890
267

68 Richter Michae Grenza Gen 1203 Switz


Supermark l Holz cherwe ve erlan
t g 237 d

69 Romero y Alejan Gran Madri 2800 Spai


tomillo dra Va, 1 d 1 n
Camin
o

71 Save-a-lot Jose 187 Boise 8372 USA


Markets Pavaro Suffolk 0

359
tti Ln.

72 Seven Hari 90 Londo OX15 UK


Seas Kumar Wadhu n 4NB
Imports rst Rd.

73 Simons Jytte Vinblt Kben 1734 Den


bistro Peters et 34 havn mark
en

74 Spcialits Domini 25, rue Paris 7501 Franc


du monde que Laurist 6 e
Perrier on

75 Split Rail Art P.O. Lande 8252 USA


Beer & Ale Brauns Box r 0
chweig 555
er

76 Suprmes Pascal Boulev Charl B- Belgi


dlices e ard eroi 6000 um
Cartrai Tirou,
n 255

77 The Big Liz 89 Portla 9720 USA


Cheese Nixon Jeffers nd 1
on Way
Suite 2

78 The Liu 55 Butte 5980 USA


Cracker Wong Grizzly 1
Box Peak
Rd.

79 Toms Karin Luisens Mnst 4408 Germ


Spezialitt Joseph tr. 48 er 7 any
en s

80 Tortuga Miguel Avda. Mxic 0503 Mexi


Restaurant Angel Azteca o D.F. 3 co
e Paolino 123

82 Trail's Helveti 722 Kirkla 9803 USA


Head us DaVinci nd 4
Gourmet Nagy Blvd.
Provisioner
s

83 Vaffeljerne Palle Smagsl rhus 8200 Den

360
t Ibsen get 45 mark

84 Victuailles Mary 2, rue Lyon 6900 Franc


en stock Savele du 4 e
y Comm
erce

85 Vins et Paul 59 rue Reims 5110 Franc


alcools Henrio de 0 e
Chevalier t l'Abbay
e

87 Wartian Pirkko Torikat Oulu 9011 Finla


Herkku Koskit u 38 0 nd
alo

88 Wellington Paula Rua do Resen 0873 Brazi


Importado Parent Mercad de 7- l
ra e o, 12 363

90 Wilman Matti Keskus Helsin 2124 Finla


Kala Karttu katu 45 ki 0 nd
nen

91 Wolski Zbysze ul. Walla 01- Polan


k Filtrow 012 d
a 68

92 Exotic null null Londo null UK


Liquid na

93 New null null New null USA


Orleans Orlea
Cajun ns
Delights

94 Grandma null null Ann null USA


Kelly's Arbor
Homestea
d

95 Tokyo null null Tokyo null Japa


Traders n

96 Cooperativ null null Ovied null Spai


a de o n
Quesos
'Las
Cabras'

361
97 Mayumi's null null Osaka null Japa
n

98 Pavlova, null null Melbo null Austr


Ltd. urne alia

99 Specialty null null Manc null UK


Biscuits, hester
Ltd.

100 PB null null Gteb null Swed


Knckebr org en
d AB

102 Heli null null Berlin null Germ


Swaren any
GmbH &
Co. KG

103 Plutzer null null Frank null Germ


Lebensmitt furt any
elgromr
kte AG

104 Nord-Ost- null null Cuxha null Germ


Fisch ven any
Handelsge
sellschaft
mbH

105 Formaggi null null Raven null Italy


Fortini na
s.r.l.

107 Bigfoot null null Bend null USA


Breweries

109 Aux joyeux null null Paris null Franc


ecclsiasti e
ques

110 New null null Bosto null USA


England n
Seafood
Cannery

112 Lyngbysild null null Lyngb null Den


y mark

362
113 Zaanse null null Zaand null Neth
Snoepfabri am erlan
ek ds

114 Karkki Oy null null Lappe null Finla


enran nd
ta

116 Ma Maison null null Montr null Cana


al da

118 Escargots null null Montc null Franc


Nouveaux eau e

119 Gai null null Annec null Franc


pturage y e

121 Exotic null null Londo null UK


Liquid na

122 New null null New null USA


Orleans Orlea
Cajun ns
Delights

123 Grandma null null Ann null USA


Kelly's Arbor
Homestea
d

124 Tokyo null null Tokyo null Japa


Traders n

125 Cooperativ null null Ovied null Spai


a de o n
Quesos
'Las
Cabras'

126 Mayumi's null null Osaka null Japa


n

127 Pavlova, null null Melbo null Austr


Ltd. urne alia

128 Specialty null null Manc null UK


Biscuits, hester
Ltd.

363
129 PB null null Gteb null Swed
Knckebr org en
d AB

131 Heli null null Berlin null Germ


Swaren any
GmbH &
Co. KG

132 Plutzer null null Frank null Germ


Lebensmitt furt any
elgromr
kte AG

133 Nord-Ost- null null Cuxha null Germ


Fisch ven any
Handelsge
sellschaft
mbH

134 Formaggi null null Raven null Italy


Fortini na
s.r.l.

136 Bigfoot null null Bend null USA


Breweries

138 Aux joyeux null null Paris null Franc


ecclsiasti e
ques

139 New null null Bosto null USA


England n
Seafood
Cannery

141 Lyngbysild null null Lyngb null Den


y mark

142 Zaanse null null Zaand null Neth


Snoepfabri am erlan
ek ds

143 Karkki Oy null null Lappe null Finla


enran nd
ta

145 Ma Maison null null Montr null Cana


al da

364
147 Escargots null null Montc null Franc
Nouveaux eau e

148 Gai null null Annec null Franc


pturage y e

150 Exotic null null Londo null UK


Liquid na

151 New null null New null USA


Orleans Orlea
Cajun ns
Delights

152 Grandma null null Ann null USA


Kelly's Arbor
Homestea
d

153 Tokyo null null Tokyo null Japa


Traders n

154 Cooperativ null null Ovied null Spai


a de o n
Quesos
'Las
Cabras'

155 Mayumi's null null Osaka null Japa


n

156 Pavlova, null null Melbo null Austr


Ltd. urne alia

157 Specialty null null Manc null UK


Biscuits, hester
Ltd.

158 PB null null Gteb null Swed


Knckebr org en
d AB

160 Heli null null Berlin null Germ


Swaren any
GmbH &
Co. KG

161 Plutzer null null Frank null Germ


Lebensmitt furt any

365
elgromr
kte AG

162 Nord-Ost- null null Cuxha null Germ


Fisch ven any
Handelsge
sellschaft
mbH

163 Formaggi null null Raven null Italy


Fortini na
s.r.l.

165 Bigfoot null null Bend null USA


Breweries

167 Aux joyeux null null Paris null Franc


ecclsiasti e
ques

168 New null null Bosto null USA


England n
Seafood
Cannery

170 Lyngbysild null null Lyngb null Den


y mark

171 Zaanse null null Zaand null Neth


Snoepfabri am erlan
ek ds

172 Karkki Oy null null Lappe null Finla


enran nd
ta

174 Ma Maison null null Montr null Cana


al da

176 Escargots null null Montc null Franc


Nouveaux eau e

177 Gai null null Annec null Franc


pturage y e

179 Exotic Charlot 49 Londo EC1 UK


Liquid te Gilbert na 4SD
Cooper St.

366
180 New Shelley P.O. New 7011 USA
Orleans Burke Box Orlea 7
Cajun 78934 ns
Delights

181 Grandma Regina 707 Ann 4810 USA


Kelly's Murph Oxford Arbor 4
Homestea y Rd.
d

182 Tokyo Yoshi 9-8 Tokyo 100 Japa


Traders Nagas Sekima n
e i
Musash
ino-shi

183 Cooperativ Antoni Calle Ovied 3300 Spai


a de o del del o 7 n
Quesos Valle Rosal 4
'Las Saave
Cabras' dra

184 Mayumi's Mayum 92 Osaka 545 Japa


i Ohno Setsuk n
o
Chuo-
ku

185 Pavlova, Ian 74 Melbo 3058 Austr


Ltd. Devlin Rose urne alia
g St.
Moonie
Ponds

186 Specialty Peter 29 Manc M14 UK


Biscuits, Wilson King's hester GSD
Ltd. Way

187 PB Lars Kaload Gteb S- Swed


Knckebr Peters agatan org 345 en
d AB on 13 67

189 Heli Petra Tiergar Berlin 1078 Germ


Swaren Winkle tenstra 5 any
GmbH & r e 5
Co. KG

190 Plutzer Martin Bogena Frank 6043 Germ


Lebensmitt Bein llee 51 furt 9 any

367
elgromr
kte AG

191 Nord-Ost- Sven Frahmr Cuxha 2747 Germ


Fisch Peters edder ven 8 any
Handelsge en 112a
sellschaft
mbH

192 Formaggi Elio Viale Raven 4810 Italy


Fortini Rossi Dante, na 0
s.r.l. 75

194 Bigfoot Cheryl 3400 - Bend 9710 USA


Breweries Saylor 8th 1
Avenue
Suite
210

196 Aux joyeux Guyln 203, Paris 7500 Franc


ecclsiasti e Rue 4 e
ques Nodier des
Francs-
Bourge
ois

197 New Robb Order Bosto 0213 USA


England Mercha Process n 4
Seafood nt ing
Cannery Dept.
2100
Paul
Revere
Blvd.

199 Lyngbysild Niels Lyngby Lyngb 2800 Den


Peters sild y mark
en Fiskeba
kken
10

200 Zaanse Dirk Verkoo Zaand 9999 Neth


Snoepfabri Luchte p am ZZ erlan
ek Rijnwe ds
g 22

201 Karkki Oy Anne Valtaka Lappe 5312 Finla


Heikko tu 12 enran 0 nd
nen ta

368
203 Ma Maison Jean- 2960 Montr H1J Cana
Guy Rue St. al 1C3 da
Lauzon Laurent

205 Escargots Marie 22, rue Montc 7130 Franc


Nouveaux Delam H. eau 0 e
are Voiron

206 Gai Eliane Bat. B Annec 7400 Franc


pturage Noz 3, rue y 0 e
des
Alpes

208 Heli null null Berlin null Germ


Swaren any
GmbH &
Co. KG

209 Plutzer null null Frank null Germ


Lebensmitt furt any
elgromr
kte AG

210 Nord-Ost- null null Cuxha null Germ


Fisch ven any
Handelsge
sellschaft
mbH

211 Heli null null Berlin null Germ


Swaren any
GmbH &
Co. KG

212 Plutzer null null Frank null Germ


Lebensmitt furt any
elgromr
kte AG

213 Nord-Ost- null null Cuxha null Germ


Fisch ven any
Handelsge
sellschaft
mbH

214 Exotic null null Londo null UK


Liquid na

215 New null null New null USA

369
Orleans Orlea
Cajun ns
Delights

216 Grandma null null Ann null USA


Kelly's Arbor
Homestea
d

217 Tokyo null null Tokyo null Japa


Traders n

218 Cooperativ null null Ovied null Spai


a de o n
Quesos
'Las
Cabras'

219 Mayumi's null null Osaka null Japa


n

220 Pavlova, null null Melbo null Austr


Ltd. urne alia

221 Specialty null null Manc null UK


Biscuits, hester
Ltd.

222 PB null null Gteb null Swed


Knckebr org en
d AB

224 Heli null null Berlin null Germ


Swaren any
GmbH &
Co. KG

225 Plutzer null null Frank null Germ


Lebensmitt furt any
elgromr
kte AG

226 Nord-Ost- null null Cuxha null Germ


Fisch ven any
Handelsge
sellschaft
mbH

227 Formaggi null null Raven null Italy

370
Fortini na
s.r.l.

229 Bigfoot null null Bend null USA


Breweries

231 Aux joyeux null null Paris null Franc


ecclsiasti e
ques

232 New null null Bosto null USA


England n
Seafood
Cannery

234 Lyngbysild null null Lyngb null Den


y mark

235 Zaanse null null Zaand null Neth


Snoepfabri am erlan
ek ds

236 Karkki Oy null null Lappe null Finla


enran nd
ta

238 Ma Maison null null Montr null Cana


al da

240 Escargots null null Montc null Franc


Nouveaux eau e

241 Gai null null Annec null Franc


pturage y e

243 Exotic Charlot 49 Londo EC1 UK


Liquid te Gilbert na 4SD
Cooper St.

244 New Shelley P.O. New 7011 USA


Orleans Burke Box Orlea 7
Cajun 78934 ns
Delights

245 Grandma Regina 707 Ann 4810 USA


Kelly's Murph Oxford Arbor 4
Homestea y Rd.
d

371
246 Tokyo Yoshi 9-8 Tokyo 100 Japa
Traders Nagas Sekima n
e i
Musash
ino-shi

247 Cooperativ Antoni Calle Ovied 3300 Spai


a de o del del o 7 n
Quesos Valle Rosal 4
'Las Saave
Cabras' dra

248 Mayumi's Mayum 92 Osaka 545 Japa


i Ohno Setsuk n
o
Chuo-
ku

249 Pavlova, Ian 74 Melbo 3058 Austr


Ltd. Devlin Rose urne alia
g St.
Moonie
Ponds

250 Specialty Peter 29 Manc M14 UK


Biscuits, Wilson King's hester GSD
Ltd. Way

251 PB Lars Kaload Gteb S- Swed


Knckebr Peters agatan org 345 en
d AB on 13 67

253 Heli Petra Tiergar Berlin 1078 Germ


Swaren Winkle tenstra 5 any
GmbH & r e 5
Co. KG

254 Plutzer Martin Bogena Frank 6043 Germ


Lebensmitt Bein llee 51 furt 9 any
elgromr
kte AG

255 Nord-Ost- Sven Frahmr Cuxha 2747 Germ


Fisch Peters edder ven 8 any
Handelsge en 112a
sellschaft
mbH

256 Formaggi Elio Viale Raven 4810 Italy

372
Fortini Rossi Dante, na 0
s.r.l. 75

258 Bigfoot Cheryl 3400 - Bend 9710 USA


Breweries Saylor 8th 1
Avenue
Suite
210

260 Aux joyeux Guyln 203, Paris 7500 Franc


ecclsiasti e Rue 4 e
ques Nodier des
Francs-
Bourge
ois

261 New Robb Order Bosto 0213 USA


England Mercha Process n 4
Seafood nt ing
Cannery Dept.
2100
Paul
Revere
Blvd.

263 Lyngbysild Niels Lyngby Lyngb 2800 Den


Peters sild y mark
en Fiskeba
kken
10

264 Zaanse Dirk Verkoo Zaand 9999 Neth


Snoepfabri Luchte p am ZZ erlan
ek Rijnwe ds
g 22

265 Karkki Oy Anne Valtaka Lappe 5312 Finla


Heikko tu 12 enran 0 nd
nen ta

267 Ma Maison Jean- 2960 Montr H1J Cana


Guy Rue St. al 1C3 da
Lauzon Laurent

269 Escargots Marie 22, rue Montc 7130 Franc


Nouveaux Delam H. eau 0 e
are Voiron

270 Gai Eliane Bat. B Annec 7400 Franc

373
pturage Noz 3, rue y 0 e
des
Alpes

272 Heli null null Berlin null Germ


Swaren any
GmbH &
Co. KG

273 Plutzer null null Frank null Germ


Lebensmitt furt any
elgromr
kte AG

274 Nord-Ost- null null Cuxha null Germ


Fisch ven any
Handelsge
sellschaft
mbH

Custo Custom Contac Addre City Posta Cou


OR TRUE merID erName tName ss lCode ntry
if
either 4 Around Thomas 120 Londo WA1 UK
expre the Horn Hardy Hanov n 1DP
ssion er Sq.
is 11 B's Victoria Fauntle Londo EC2 UK
TRUE Beverag Ashwort roy n 5NT
es h Circus

16 Consolid Elizabet Berkel Londo WX1 UK


ated h ey n 6LT
Holdings Brown Garden
s 12
Brewer
y

19 Eastern Ann 35 Londo WX3 UK


Connecti Devon King n 6FW
on George

38 Island Helen Garden Cowe PO31 UK


Trading Bennett House s 7PJ
Crowth
er Way

53 North/So Simon South Londo SW7 UK

374
uth Crowth House n 1RZ
er 300
Queen
sbridge

72 Seven Hari 90 Londo OX15 UK


Seas Kumar Wadhu n 4NB
Imports rst Rd.

92 Exotic null null Londo null UK


Liquid na

99 Specialty null null Manc null UK


Biscuits, heste
Ltd. r

121 Exotic null null Londo null UK


Liquid na

128 Specialty null null Manc null UK


Biscuits, heste
Ltd. r

150 Exotic null null Londo null UK


Liquid na

157 Specialty null null Manc null UK


Biscuits, heste
Ltd. r

179 Exotic Charlott 49 Londo EC1 UK


Liquid e Gilbert na 4SD
Cooper St.

186 Specialty Peter 29 Manc M14 UK


Biscuits, Wilson King's heste GSD
Ltd. Way r

214 Exotic null null Londo null UK


Liquid na

221 Specialty null null Manc null UK


Biscuits, heste
Ltd. r

243 Exotic Charlott 49 Londo EC1 UK


Liquid e Gilbert na 4SD
Cooper St.

375
250 Specialty Peter 29 Manc M14 UK
Biscuits, Wilson King's heste GSD
Ltd. Way r

SO TRUE
Error
ME if
some
of a
set of
comp
ariso
ns
are
TRUE

SQL General Data Types

A data type defines what kind of value a column can contain


SQL General Data Types

Each column in a database table is required to have a name and a data


type.

SQL developers have to decide what types of data will be stored inside
each and every table column when creating a SQL table. The data type
is a label and 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.

The following table lists the general data types in SQL:

Data type Description

CHARACTER(n) Character string. Fixed-length n

376
VARCHAR(n) or Character string. Variable length. Maximum length
CHARACTER n
VARYING(n)

BINARY(n) Binary string. Fixed-length n

BOOLEAN Stores TRUE or FALSE values

VARBINARY(n) or Binary string. Variable length. Maximum length n


BINARY
VARYING(n)

INTEGER(p) Integer numerical (no decimal). Precision p

SMALLINT Integer numerical (no decimal). Precision 5

INTEGER Integer numerical (no decimal). Precision 10

BIGINT Integer numerical (no decimal). Precision 19

DECIMAL(p,s) Exact numerical, precision p, scale s. Example:


decimal(5,2) is a number that has 3 digits before
the decimal and 2 digits after the decimal

377
NUMERIC(p,s) Exact numerical, precision p, scale s. (Same as
DECIMAL)

FLOAT(p) Approximate numerical, mantissa precision p. A


floating number in base 10 exponential notation.
The size argument for this type consists of a single
number specifying the minimum precision

REAL Approximate numerical, mantissa precision 7

FLOAT Approximate numerical, mantissa precision 16

DOUBLE Approximate numerical, mantissa precision 16


PRECISION

DATE Stores year, month, and day values

TIME Stores hour, minute, and second values

TIMESTAMP Stores year, month, day, hour, minute, and


second values

INTERVAL Composed of a number of integer fields,


representing a period of time, depending on the
type of interval

378
ARRAY A set-length and ordered collection of elements

MULTISET A variable-length and unordered collection of


elements

XML Stores XML data

SQL Data Type Quick Reference

However, different databases offer different choices for the data type
definition.

The following table shows some of the common names of data types
between the various database platforms:

Data type Access SQLServer Oracle MySQL PostgreSQL

boolean Yes/No Bit Byte N/A Boolean

integer Number Int Number Int Int


(integer) Integer Integer

float Number Float Number Float Numeric


(single) Real

379
currency Currency Money N/A N/A Money

string N/A Char Char Char Char


(fixed)

string Text (<256) Varchar Varchar Varchar Varchar


(variable) Memo (65k+) Varchar2

binary OLE Object Binary (fixed up Long Blob Binary


object Memo to 8K) Raw Text Varbinary
Varbinary (<8K)
Image (<2GB)

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!

SQL Data Types for Various DBs

Data types and ranges for Microsoft Access, MySQL and SQL Server.

Microsoft Access Data Types

Data type Description Storage

Text Use for text or combinations of text and numbers. 255


characters maximum

380
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

Integer Allows whole numbers between -32,768 and 32,767 2 bytes

Long Allows whole numbers between -2,147,483,648 and 4 bytes


2,147,483,647

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 8 bytes
decimal places. Tip: You can choose which country's currency
to use

AutoNumber AutoNumber fields automatically give each record its own 4 bytes
number, 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 1 bit


On/Off. In code, use the constants True and False (equivalent

381
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 up to
Large OBjects) 1GB

Hyperlink Contain links to other files, including web pages

Lookup Let you type a list of options, which can then be chosen from a 4 bytes
Wizard drop-down list

MySQL Data Types

In MySQL there are three main data types : text, number, and
Date/Time types.

Text types:

Data type Description

CHAR(size) Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to
255 characters

VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special
characters). The maximum size is specified in parenthesis. Can store
up to 255 characters. Note: If you put a greater value than 255 it will
be converted to a TEXT type

TINYTEXT Holds a string with a maximum length of 255 characters

382
TEXT Holds a string with a maximum length of 65,535 characters

BLOB 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

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(x,y,z,etc.) Let you enter 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.

Note: The values are sorted in the order you enter them.

You enter the possible values in this format: ENUM('X','Y','Z')

SET Similar to ENUM except that SET may contain up to 64 list items and
can store more than one choice

Number types:

Data type Description

383
TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number
of digits may be specified in parenthesis

SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum


number of digits may be specified in parenthesis

MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The


maximum number of digits may be specified in parenthesis

INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295


UNSIGNED*. The maximum number of digits may be specified in
parenthesis

BIGINT(size) -9223372036854775808 to 9223372036854775807 normal. 0 to


18446744073709551615 UNSIGNED*. The maximum number of
digits may be specified in parenthesis

FLOAT(size,d) A small number with a floating decimal point. The maximum


number of digits may be specified in the size parameter. The
maximum number of digits to the right of the decimal point is
specified in the d parameter

DOUBLE(size,d) A large number with a floating decimal point. The maximum number
of digits may be specified in the size parameter. The maximum
number of digits to the right of the decimal point is specified in the d
parameter

DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point.


The maximum number of digits may be specified in the size
parameter. The maximum number of digits to the right of the

384
decimal point is specified in the d parameter

*The integer types have an extra option called UNSIGNED. Normally,


the integer goes from an negative to positive value. Adding the
UNSIGNED attribute will move that range up so it starts at zero instead
of a negative number.

Date types:

Data type Description

DATE() A date. Format: YYYY-MM-DD

Note: The supported range is from '1000-01-01' to


'9999-12-31'

DATETIME() *A date and time combination. Format: YYYY-MM-DD


HH:MI:SS

Note: The supported range is from '1000-01-01


00:00:00' to '9999-12-31 23:59:59'

TIMESTAMP() *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:MI:SS

Note: The supported range is from '1970-01-01


00:00:01' UTC to '2038-01-09 03:14:07' UTC

TIME() A time. Format: HH:MI:SS

Note: The supported range is from '-838:59:59' to


'838:59:59'

YEAR() A year in two-digit or four-digit format.

Note: Values allowed in four-digit format: 1901 to 2155.


Values allowed in two-digit format: 70 to 69,
representing years from 1970 to 2069

385
*Even if DATETIME and TIMESTAMP return the same format, they work
very differently. In an INSERT or UPDATE query, the TIMESTAMP
automatically set itself to the current date and time. TIMESTAMP also
accepts various formats, like YYYYMMDDHHMISS, YYMMDDHHMISS,
YYYYMMDD, or YYMMDD.

SQL Server Data Types


String types:

Data type Description Storage

char(n) Fixed width character string. Maximum 8,000 Defined width


characters

varchar(n) Variable width character string. Maximum 8,000 2 bytes + number


characters of chars

varchar(max) Variable width character string. Maximum 2 bytes + number


1,073,741,824 characters of chars

text Variable width character string. Maximum 2GB of 4 bytes + number


text data of chars

nchar Fixed width Unicode string. Maximum 4,000 Defined width x 2


characters

nvarchar Variable width Unicode string. Maximum 4,000


characters

386
nvarchar(max) Variable width Unicode string. Maximum
536,870,912 characters

ntext Variable width Unicode string. Maximum 2GB of


text data

bit Allows 0, 1, or NULL

binary(n) Fixed width binary string. Maximum 8,000 bytes

varbinary Variable width binary string. Maximum 8,000


bytes

varbinary(max) Variable width binary string. Maximum 2GB

image Variable width binary string. Maximum 2GB

Number types:

Data type Description Storage

tinyint Allows whole numbers from 0 to 255 1 byte

smallint Allows whole numbers between -32,768 and 32,767 2 bytes

387
int Allows whole numbers between -2,147,483,648 and 4 bytes
2,147,483,647

bigint Allows whole numbers between -9,223,372,036,854,775,808 8 bytes


and 9,223,372,036,854,775,807

5-17
decimal(p,s) Fixed precision and scale numbers. bytes

Allows numbers from -10^38 +1 to 10^38 1.

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


bytes
Allows numbers from -10^38 +1 to 10^38 1.

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 + 4 or 8


308. bytes

The n parameter indicates whether the field should hold 4 or 8


bytes. float(24) holds a 4-byte field and float(53) holds an 8-
byte field. Default value of n is 53.

388
real Floating precision number data from -3.40E + 38 to 3.40E + 4 bytes
38

Date types:

Data type Description Storag

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 byt
nanoseconds

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 byt

datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10 by

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:

389
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

SQL Quick Reference From W3Schools

SQL Statement Syntax

AND / OR SELECT column_name(s)


FROM table_name
WHERE condition
AND|OR condition

ALTER TABLE ALTER TABLE table_name


ADD column_name datatype

390
or

ALTER TABLE table_name


DROP COLUMN column_name

AS (alias) SELECT column_name AS column_alias


FROM table_name

or

SELECT column_name
FROM table_name AS table_alias

BETWEEN SELECT column_name(s)


FROM table_name
WHERE column_name
BETWEEN value1 AND value2

CREATE CREATE DATABASE database_name


DATABASE

CREATE TABLE CREATE TABLE table_name


(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
...
)

CREATE INDEX CREATE INDEX index_name


ON table_name (column_name)

or

CREATE UNIQUE INDEX index_name


ON table_name (column_name)

CREATE VIEW CREATE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition

DELETE DELETE FROM table_name


WHERE some_column=some_value

391
or

DELETE FROM table_name


(Note: Deletes the entire table!!)

DELETE * FROM table_name


(Note: Deletes the entire table!!)

DROP DATABASE DROP DATABASE database_name

DROP INDEX DROP INDEX table_name.index_name (SQL Server)


DROP INDEX index_name ON table_name (MS Access)
DROP INDEX index_name (DB2/Oracle)
ALTER TABLE table_name
DROP INDEX index_name (MySQL)

DROP TABLE DROP TABLE table_name

EXISTS IF EXISTS (SELECT * FROM table_name WHERE id = ?)


BEGIN
--do what needs to be done if exists
END
ELSE
BEGIN
--do what needs to be done if not
END

GROUP BY SELECT column_name, aggregate_function(column_name)


FROM table_name
WHERE column_name operator value
GROUP BY column_name

HAVING SELECT column_name, aggregate_function(column_name)


FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value

IN SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)

INSERT INTO INSERT INTO table_name


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

392
or

INSERT INTO table_name


(column1, column2, column3,...)
VALUES (value1, value2, value3,....)

INNER JOIN SELECT column_name(s)


FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name

LEFT JOIN SELECT column_name(s)


FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name

RIGHT JOIN SELECT column_name(s)


FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name

FULL JOIN SELECT column_name(s)


FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name

LIKE SELECT column_name(s)


FROM table_name
WHERE column_name LIKE pattern

ORDER BY SELECT column_name(s)


FROM table_name
ORDER BY column_name [ASC|DESC]

SELECT SELECT column_name(s)


FROM table_name

SELECT * SELECT *
FROM table_name

SELECT DISTINCT SELECT DISTINCT column_name(s)


FROM table_name

SELECT INTO SELECT *


INTO new_table_name [IN externaldatabase]
FROM old_table_name

393
or

SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name

SELECT TOP SELECT TOP number|percent column_name(s)


FROM table_name

TRUNCATE TABLE TRUNCATE TABLE table_name

UNION SELECT column_name(s) FROM table_name1


UNION
SELECT column_name(s) FROM table_name2

UNION ALL SELECT column_name(s) FROM table_name1


UNION ALL
SELECT column_name(s) FROM table_name2

UPDATE UPDATE table_name


SET column1=value, column2=value,...
WHERE some_column=some_value

WHERE SELECT column_name(s)


FROM table_name
WHERE column_name operator value

Source : https://www.w3schools.com/sql/sql_quickref.asp

SQL Quiz

You can test your SQL skills with W3Schools' Quiz.

The Test

The test contains 25 questions and there is no time limit.

The test is not official, it's just a nice way to see how much you know, or
don't know, about SQL.

394
Count Your Score

You will get 1 point for each correct answer. At the end of the Quiz, your
total score will be displayed. Maximum score is 25 points.

Start the Quiz

Good luck!

Start the Quiz

W3Schools' Online Certification

The perfect solution for professionals who need to balance work, family,
and career building.

More than 10 000 certificates already issued!

Get Your Certificate

The HTML Certificate documents your knowledge of HTML.

The CSS Certificate documents your knowledge of advanced CSS.

The JavaScript Certificate documents your knowledge of JavaScript and


HTML DOM.

The jQuery Certificate documents your knowledge of jQuery.

The PHP Certificate documents your knowledge of PHP and SQL


(MySQL).

The XML Certificate documents your knowledge of XML, XML DOM and
XSLT.

The Bootstrap Certificate documents your knowledge of the Bootstrap


framework.

395

Вам также может понравиться