Академический Документы
Профессиональный Документы
Культура Документы
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 References
SQL Quiz
2
SQL Tutorial
Our SQL tutorial will teach you how to use SQL in: MySQL, SQL Server,
MS Access, Oracle, Sybase, Informix, Postgres, and other database
systems.
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
3
8 Blido Martn C/ Araquil, Madrid 28023 Spain
Comidas Sommer 67
preparadas
4
21 Familia Aria Cruz Rua Ors, So 05442- Brazil
Arquibaldo 92 Paulo 030
5
34 Hanari Mario Rua do Rio de 05454- Brazil
Carnes Pontes Pao, 67 Janeiro 876
6
46 LILA- Carlos Carrera 52 Barquisi 3508 Venezu
Supermerca Gonzlez con Ave. meto ela
do Bolvar
#65-98
Llano
Largo
7
Charonne
8
71 Save-a-lot Jose 187 Boise 83720 USA
Markets Pavarotti Suffolk Ln.
9
85 Vins et Paul 59 rue de Reims 51100 France
alcools Henriot l'Abbaye
Chevalier
Data types and ranges for Microsoft Access, MySQL and SQL Server.
10
SQL Data Types
The XML Certificate documents your knowledge of XML, XML DOM and
XSLT.
Introduction to SQL
What is SQL?
11
SQL is a Standard - BUT....
Note: Most of the SQL database programs also have their own
proprietary extensions in addition to the SQL standard!
To build a web site that shows data from a database, you will need:
RDBMS
RDBMS is the basis for SQL, and for all modern database systems such
as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
Example
SELECT * FROM Customers;
Number of Records: 91
12
2 Ana Trujillo Ana Avda. de Mxico 05021 Mexico
Emparedad Trujillo la D.F.
os y Constituci
helados n 2222
13
Mineiro Afonso Lusadas, Paulo 043
23
14
28 Furia Lino Jardim das Lisboa 1675 Portuga
Bacalhau e Rodriguez rosas n. l
Frutos do 32
Mar
15
40 La corne Daniel 67, Versaille 78000 France
d'abondanc Tonini avenue de s
e l'Europe
16
52 Morgenster Alexander Heerstr. Leipzig 04179 German
n Feuer 22 y
Gesundkost
17
grande Gutirrez Libertador Aires na
900
18
78 The Cracker Liu Wong 55 Grizzly Butte 59801 USA
Box Peak Rd.
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.
SQL Syntax
Database Tables
20
y helados n 2222
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
21
Emparedad Trujillo la D.F.
os y Constituci
helados n 2222
22
23
23
Bacalhau e Rodriguez rosas n. l
Frutos do 32
Mar
24
40 La corne Daniel 67, Versaille 78000 France
d'abondanc Tonini avenue de s
e l'Europe
25
52 Morgenster Alexander Heerstr. Leipzig 04179 German
n Feuer 22 y
Gesundkost
26
grande Gutirrez Libertador Aires na
900
27
78 The Cracker Liu Wong 55 Grizzly Butte 59801 USA
Box Peak Rd.
28
In this tutorial we will teach you all about the different SQL statements.
In this tutorial, we will use semicolon at the end of each SQL statement.
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:
Demo Database
30
5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden
snabbkp Berglund en 8
SQL Statement:
Example
CustomerName City
31
Comrcio Mineiro So Paulo
Frankenversand Mnchen
GROSELLA-Restaurante Caracas
32
La maison d'Asie Toulouse
LILA-Supermercado Barquisimeto
LINO-Delicateses I. de Margarita
North/South London
QUICK-Stop Cunewalde
33
Ricardo Adocicados Rio de Janeiro
Vaffeljernet rhus
Wolski Walla
34
SELECT * Example
The following SQL statement selects all the columns from the
"Customers" table:
Example
Edit the SQL Statement, and click "Run SQL" to see the result.
Run SQL
Result:
Number of Records: 91
35
Lebihans Bouchers
36
Inter. , 86
Salchichas
S.A.
37
Abastos Hernndez con Ave. Cristbal la
Carlos
Soublette
#8-35
38
Llano
Largo
39
Comidas Fernndez Jorge Cash D.F.
clsicas 321
40
71 Save-a-lot Jose 187 Suffolk Boise 83720 USA
Markets Pavarotti Ln.
41
en stock Saveley Commerce
42
Demo Database
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.
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
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;
Demo Database
51
helados 2222 D.F.
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
52
comercial Chang Granada D.F.
Moctezuma 9993
SQL requires single quotes around text values (most database systems
will also allow double 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
Operator Description
53
= Equal
<> Not equal. Note: In some versions of SQL this operator may
be written as !=
The AND and OR operators are used to filter records based on more
than one condition.
54
AND Operator Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Operator Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
Demo Database
55
5 Berglunds Christina Berguvsvgen Lule S-958 22 Sweden
snabbkp Berglund 8
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
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
56
1 Alfreds Maria Anders Obere Berlin 12209 Germany
Futterkiste Str. 57
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
ORDER BY Syntax
57
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Demo Database
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
59
Arquibaldo 92 030
60
87 Wartian Pirkko Torikatu 38 Oulu 90110 Finland
Herkku Koskitalo
61
6 Blauer See Hanna Forsterstr. Mannhei 68306 German
Delikatessen Moos 57 m y
62
2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico
Emparedado Constituci D.F.
s y helados n 2222
63
gastrnomo Saavedra Catalua,
23
64
Imports Wadhurst 4NB
Rd.
65
89 White Karl 305 - 14th Seattle 98128 USA
Clover Jablonski Ave. S.
Markets Suite 3B
ORDER BY Example
The following SQL statement selects all customers from the "Customers"
table, sorted by the "Country" column:
Example
Number of Records: 91
66
35 HILARIN- Carlos Carrera 22 San 5022 Venezue
Abastos Hernndez con Ave. Cristbal la
Carlos
Soublette
#8-35
67
55 Old World Rene 2743 Bering Anchorag 99508 USA
Delicatessen Phillips St. e
68
16 Consolidate Elizabeth Berkeley London WX1 6LT UK
d Holdings Brown Gardens 12
Brewery
69
preparadas Sommer 67
70
2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico
Emparedad Constituci D.F.
os y helados n 2222
71
1 Alfreds Maria Obere Str. Berlin 12209 German
Futterkiste Anders 57 y
72
86 Die Rita Mller Adenauerall Stuttgart 70563 German
Wandernde ee 900 y
Kuh
73
du monde Perrier Lauriston
74
21 Familia Aria Cruz Rua Ors, So Paulo 05442- Brazil
Arquibaldo 92 030
75
76 Suprmes Pascale Boulevard Charleroi B-6000 Belgium
dlices Cartrain Tirou, 255
The following SQL statement selects all customers from the "Customers"
table, sorted DESCENDING by the "Country" column:
Example
76
Comidas Simpson Aires a
para llevar
77
34 Hanari Mario Rua do Rio de 05454- Brazil
Carnes Pontes Pao, 67 Janeiro 876
78
73 Simons Jytte Vinbltet Kbenhav 1734 Denmark
bistro Petersen 34 n
79
d'Asie Roulet Alsace-
Lorraine
80
39 Kniglich Philip Maubelstr. Brandenb 14776 German
Essen Cramer 90 urg y
81
2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico
Emparedad Constituci D.F.
os y helados n 2222
82
Vinhoss
83
4 Around the Thomas 120 London WA1 UK
Horn Hardy Hanover Sq. 1DP
84
Store
85
Gourmet Nagy Blvd.
Provisioners
The following SQL statement selects all customers from the "Customers"
table, sorted by the "Country" and the "CustomerName" column:
86
Example
87
62 Queen Lcia Alameda So Paulo 05487- Brazil
Cozinha Carvalho dos 020
Canrios,
891
88
alcools Henriot l'Abbaye
Chevalier
89
Gesundkost Feuer y
90
13 Centro Francisco Sierras de Mxico 05022 Mexico
comercial Chang Granada D.F.
Moctezuma 9993
91
preparadas
92
Gourmet Nagy DaVinci
Provisioners Blvd.
93
46 LILA- Carlos Carrera 52 Barquisim 3508 Venezue
Supermerca Gonzlez con Ave. eto la
do Bolvar
#65-98
Llano
Largo
The first way specifies both the column names and the values to be
inserted:
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:
Demo Database
94
Below is a selection from the "Customers" table in the Northwind sample
database:
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
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.
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:
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!
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;
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
Demo Database
98
4 Smith John 110 Bishopsgate London
The following SQL statement uses the IS NULL operator to list all
persons that have no address:
Bloggs Joe
Roe Jane
The following SQL statement uses the IS NOT NULL operator to list all
persons that do have an address:
99
LastName FirstName Address
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Demo Database
100
2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico
Emparedados y Constitucin D.F.
helados 2222
UPDATE Table
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
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:
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
DELETE Syntax
DELETE FROM table_name
WHERE condition;
104
record(s) that should be deleted. If you omit the WHERE clause, all
records in the table will be deleted!
Demo Database
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
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
106
3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico
Taquera Moreno 2312 D.F.
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:
or:
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.
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
108
helados 2222
The following SQL statement selects the two first records from the
"Customers" table:
Example
The following SQL statement selects the first 50% of the records from
the "Customers" table:
Example
Number of Records: 46
109
1 Alfreds Maria Obere Berlin 12209 Germa
Futterkist Anders Str. 57 ny
e
110
11 B's Victoria Fauntler London EC2 UK
Beverages Ashwort oy 5NT
h Circus
111
21 Familia Aria Rua So 05442- Brazil
Arquibaldo Cruz Ors, Paulo 030
92
112
Lanchonet Fonseca Brasil, as 786
es 442
113
40 La corne Daniel 67, Versaille 78000 France
d'abondan Tonini avenue s
ce de
l'Europe
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
1 Chais 1 1 10 boxes x 20 18
bags
2 Chang 1 1 24 - 12 oz 19
bottles
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
Number of Records: 1
SmallestPrice
2.5
MAX() Example
The following SQL statement finds the price of the most expensive
product:
Example
Number of Records: 1
LargestPrice
263.5
116
SQL COUNT(), AVG() and SUM() Functions
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
1 Chais 1 1 10 boxes x 20 18
bags
117
2 Chang 1 1 24 - 12 oz 19
bottles
COUNT() Example
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
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
There are two wildcards used in conjunction with the LIKE operator:
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:
120
LIKE 'a%'
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
121
2 Ana Trujillo Ana Trujillo Avda. de la Mxico 05021 Mexico
Emparedados y Constitucin D.F.
helados 2222
Example
Number of Records: 4
122
Moreno Moreno s 2312 o
Taquera D.F.
Example
Number of Records: 7
123
The following SQL statement selects all customers with a
CustomerName that have "or" in any position:
Example
Number of Records: 11
124
80 Tortuga Miguel Avda. Mxico 05033 Mexico
Restaurante Angel Azteca D.F.
Paolino 123
Example
Number of Records: 11
125
Restaurante Pereira Los s ela
Palos
Grandes
Example
Number of Records: 4
126
The following SQL statement selects all customers with a
CustomerName that starts with "a" and ends with "o":
Example
Number of Records: 3
Example
Number of Records: 87
127
8 Blido Martn C/ Araquil, Madrid 28023 Spain
Comidas Sommer 67
preparadas
128
21 Familia Aria Cruz Rua Ors, So 05442- Brazil
Arquibaldo 92 Paulo 030
129
34 Hanari Mario Rua do Rio de 05454- Brazil
Carnes Pontes Pao, 67 Janeiro 876
130
46 LILA- Carlos Carrera 52 Barquisi 3508 Venezu
Supermerca Gonzlez con Ave. meto ela
do Bolvar
#65-98
Llano
Largo
131
Charonne
132
71 Save-a-lot Jose 187 Boise 83720 USA
Markets Pavarotti Suffolk Ln.
133
85 Vins et Paul 59 rue de Reims 51100 France
alcools Henriot l'Abbaye
Chevalier
SQL Wildcards
In SQL, wildcard characters are used with the SQL LIKE operator.
134
Wildcard Description
Demo Database
135
3 Antonio Moreno Antonio Mataderos Mxico 05023 Mexico
Taquera Moreno 2312 D.F.
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
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
137
54 Ocano Yvonne Ing. Buenos 1010 Argenti
Atlntico Moncada Gustavo Aires na
Ltda. Moncad
a 8585
Piso 20-
A
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
The two following SQL statements selects all customers with a City NOT
starting with "b", "s", or "p":
Example
Number of Records: 62
139
4 Around the Thomas 120 London WA1 UK
Horn Hardy Hanover 1DP
Sq.
140
22 FISSA Diego Roel C/ Madrid 28034 Spain
Fabrica Moralzarza
Inter. l, 86
Salchichas
S.A.
141
38 Island Helen Garden Cowes PO31 UK
Trading Bennett House 7PJ
Crowther
Way
142
58 Pericles Guillermo Calle Dr. Mxico 05033 Mexico
Comidas Fernndez Jorge Cash D.F.
clsicas 321
143
79 Toms Karin Luisenstr. Mnster 44087 Germany
Spezialitte Josephs 48
n
144
Or:
Example
Number of Records: 62
145
Brewery
146
33 GROSELL Manuel 5 Ave. Los Caracas 1081 Venezuel
A- Pereira Palos a
Restaurante Grandes
147
52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 Germany
Gesundkost Feuer
148
72 Seven Seas Hari Kumar 90 London OX15 UK
Imports Wadhurst 4NB
Rd.
149
91 Wolski Zbyszek ul. Walla 01-
Filtrowa 012
68
SQL IN Operator
The IN Operator
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
Demo Database
150
4 Around the Thomas 120 Londo WA1 1DP UK
Horn Hardy Hanover n
Sq.
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
151
53 North/South Simon South Londo SW7 1RZ UK
Crowther House 300 n
Queensbrid
ge
The BETWEEN operator selects values within a range. The values can be
numbers, text, or dates.
Demo Database
1 Chais 1 1 10 boxes x 18
20 bags
152
2 Chang 1 1 24 - 12 oz 19
bottles
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
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
34 Sasquatch Ale 16 1 24 - 12 oz 14
bottles
35 Steeleye Stout 16 1 24 - 12 oz 18
bottles
42 Singaporean Hokkien 20 5 32 - 1 kg 14
Fried Mee pkgs.
46 Spegesild 21 8 4 - 450 g 12
glasses
49 Maxilaku 23 3 24 - 50 g 20
pkgs.
154
57 Ravioli Angelo 26 5 24 - 250 g 19.5
pkgs.
67 Laughing Lumberjack 16 1 24 - 12 oz 14
Lager bottles
73 Rd Kaviar 17 8 24 - 150 g 15
jars
76 Lakkalikri 23 1 500 ml 18
To display the products outside the range of the previous example, use
NOT BETWEEN:
Example
SQL Statement:
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
6 Grandma's Boysenberry 3 2 12 - 8 oz 25
Spread jars
8 Northwoods Cranberry 3 2 12 - 12 oz 40
Sauce jars
10 Ikura 4 8 12 - 200 ml 31
jars
13 Konbu 6 8 2 kg box 6
17 Alice Mutton 7 6 20 - 1 kg 39
tins
23 Tunnbrd 9 5 12 - 250 g 9
156
pkgs.
52 Filo Mix 24 5 16 - 2 kg 7
boxes
157
53 Perth Pasties 24 6 48 pieces 32.8
55 Pt chinois 25 6 24 boxes x 24
2 pies
69 Gudbrandsdalsost 15 4 10 kg pkg. 36
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
42 Singaporean Hokkien 20 5 32 - 1 kg 14
Fried Mee pkgs.
46 Spegesild 21 8 4 - 450 g 12
glasses
73 Rd Kaviar 17 8 24 - 150 g 15
jars
Sample Table
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
Example
Number of Records: 5
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.
SQL Aliases
SQL Aliases
Demo Database
161
Below is a selection from the "Customers" table:
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;
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:
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;
163
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName="Around the
Horn" ANDCustomers.CustomerID=Orders.CustomerID;
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.
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:
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.
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
165
10365 Antonio Moreno Taquera 11/27/1996
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
The INNER JOIN keyword selects all rows from both tables as long as
there is a match between the columns in both tables.
166
or:
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;
Demo Database
167
3 Antonio Antonio Mataderos Mxic 05023 Mexico
Moreno Moreno 2312 o D.F.
Taquera
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
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
169
Centro comercial Moctezuma 10259
170
Familia Arquibaldo 10386
Frankenversand 10267
Frankenversand 10337
Frankenversand 10342
Frankenversand 10396
GROSELLA-Restaurante 10268
HILARIN-Abastos 10257
HILARIN-Abastos 10395
171
Hungry Coyote Import Store 10415
LILA-Supermercado 10283
LILA-Supermercado 10296
LILA-Supermercado 10330
LILA-Supermercado 10357
LILA-Supermercado 10381
LINO-Delicateses 10405
172
Lehmanns Marktstand 10343
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
174
Ricardo Adocicados 10299
175
Toms Spezialitten 10438
Vaffeljernet 10367
Vaffeljernet 10399
176
Wolski 10374
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.
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
Demo Database
177
1 Alfreds Maria Obere Str. Berlin 12209 German
Futterkiste Anders 57 y
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
The following SQL statement will select all customers, and any orders
they might have:
178
Example
CustomerName OrderID
179
Bottom-Dollar Marketse 10431
180
Ernst Handel 10442
Frankenversand 10267
Frankenversand 10337
Frankenversand 10342
Frankenversand 10396
GROSELLA-Restaurante 10268
HILARIN-Abastos 10257
HILARIN-Abastos 10395
181
Hanari Carnes 10250
LILA-Supermercado 10283
LILA-Supermercado 10296
LILA-Supermercado 10330
LILA-Supermercado 10357
LILA-Supermercado 10381
LINO-Delicateses 10405
182
La maison d'Asie 10413
North/South null
183
Ottilies Kseladen 10407
QUICK-Stop 10273
QUICK-Stop 10285
QUICK-Stop 10286
QUICK-Stop 10313
QUICK-Stop 10345
QUICK-Stop 10361
QUICK-Stop 10418
184
Rattlesnake Canyon Grocery 10294
185
Split Rail Beer & Ale 10329
Vaffeljernet 10367
Vaffeljernet 10399
186
Wartian Herkku 10320
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).
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.
or:
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
188
2 Fuller Andrew 2/19/1952 EmpID2.pic Andrew received his
BTS commercial
and....
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
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.
189
Demo Database
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
The following SQL statement selects all customers, and all orders:
CustomerName OrderID
Alfreds Futterkiste
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.
A self JOIN is a regular join, but the table is joined with itself.
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
Demo Database
192
1 Alfreds Maria Obere Str. Berlin 12209 German
Futterkiste Anders 57 y
The following SQL statement matches customers that are from the same
city:
Example
Number of Records: 88
193
Ocano Atlntico Ltda. Rancho grande Buenos
Aires
194
Eastern Connection Seven Seas Imports London
195
helados
196
Janeiro
The SQL UNION operator combines the result 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.
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
198
3 Antonio Antonio Mataderos Mxic 05023 Mexico
Moreno Moreno 2312 o D.F.
Taquera
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!
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
The following SQL statement selects all the different German cities (only
distinct values) from "Customers" and "Suppliers":
208
Example
Number of Records: 13
City Country
Aachen Germany
Berlin Germany
Brandenburg Germany
Cunewalde Germany
Cuxhaven Germany
Frankfurt Germany
Kln Germany
Leipzig Germany
Mannheim Germany
Mnchen Germany
Mnster Germany
Stuttgart Germany
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
Kln Germany
Leipzig Germany
Mannheim Germany
Mnchen Germany
Mnster Germany
Stuttgart Germany
Example
210
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;
211
Customer Felipe Izquierdo I. de Margarita Venezuela
212
Customer Laurence Lebihans Marseille France
213
Customer Peter Franken Mnchen Germany
214
Supplier Eliane Noz Annecy France
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
216
5 Berglunds Christina Berguvsvg Lule S-958 22 Sweden
snabbkp Berglund en 8
Example
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
Example
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
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
219
ShipperID ShipperName
1 Speedy Express
2 United Package
3 Federal Shipping
The following SQL statement lists the number of orders sent by each
shipper:
Example
Number of Records: 3
ShipperName NumberOfOrders
Federal Shipping 68
Speedy Express 54
United Package 74
220
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
221
4 Around the Thomas 120 Londo WA1 1DP UK
Horn Hardy Hanover Sq. n
Example
Number of Records: 5
COUNT(CustomerID) Country
9 Brazil
11 France
11 Germany
7 UK
13 USA
Example
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
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
223
EmployeeID LastName FirstName BirthDate Photo Notes
The following SQL statement lists the employees that have registered
more than 10 orders:
Example
Number of Records: 8
LastName NumberOfOrders
Buchanan 11
Callahan 27
Davolio 29
Fuller 20
224
King 14
Leverling 31
Peacock 40
Suyama 18
Example
Number of Records: 1
LastName NumberOfOrders
Davolio 29
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
1 Chais 1 1 10 boxes x 20 18
bags
2 Chang 1 1 24 - 12 oz 19
bottles
226
1 Exotic Liquid Charlotte 49 Gilbert Londo EC1 4SD UK
Cooper St. n
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.
PB Knckebrd AB
Plutzer Lebensmittelgromrkte AG
Norske Meierier
Bigfoot Breweries
Svensk Sjfda AB
Leka Trading
Lyngbysild
Zaanse Snoepfabriek
Karkki Oy
G'day, Mate
Ma Maison
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
The ANY and ALL operators are used with a WHERE or HAVING clause.
The ANY operator returns true if any of the subquery values meet the
condition.
The ALL operator returns true if all of the subquery values meet the
condition.
ANY 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
1 Chais 1 1 10 boxes x 20 18
bags
2 Chang 1 1 24 - 12 oz 19
bottles
230
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
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
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
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
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 SELECT INTO statement selects data from one table and inserts it
into a 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.
SELECT *
INTO CustomersBackup2013
FROM Customers;
SELECT *
INTO CustomersBackup2013 IN 'Backup.mdb'
FROM Customers;
233
Copy only a few columns into the new table:
SELECT *
INTO CustomersBackup2013
FROM Customers
WHERE Country='Germany';
Copy data from more than one table into the new table:
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;
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 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:
Demo Database
235
And a selection from the "Suppliers" table:
Example
Result:
You have made changes to the database. Rows affected: 29
The following SQL statement copies "Suppliers" into "Customers" (fill all
columns):
236
Example
Result:
You have made changes to the database. Rows affected: 29
The following SQL statement copies only the German suppliers into
"Customers":
Example
Result:
You have made changes to the database. Rows affected: 3
SQL Comments
SQL Comments
Note: The examples in this chapter will not work in Firefox and
Microsoft Edge!
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;
238
12 Cactus Patricio Cerrito Buenos 1010 Argenti
Comidas para Simpson 333 Aires na
llevar
239
26 France Carine 54, rue Nantes 44000 France
restauration Schmitt Royale
240
Crowther
Way
241
Dewey Joseph- s m
Bens 532
242
63 QUICK-Stop Horst Taucherstr Cunewal 01307 Germa
Kloss ae 10 de ny
243
77 The Big Cheese Liz Nixon 89 Portland 97201 USA
Jefferson
Way Suite
2
244
91 Wolski Zbyszek ul. Walla 01-012 Poland
Filtrowa
68
245
a
246
Kelly's Arbor
Homestead
247
139 New England null null Boston null USA
Seafood
Cannery
248
156 Pavlova, Ltd. null null Melbour null Australi
ne a
249
171 Zaanse null null Zaanda null Netherl
Snoepfabriek m ands
250
186 Specialty Peter 29 King's Manches M14 UK
Biscuits, Ltd. Wilson Way ter GSD
251
Suite
#402
252
haft mbH
253
omrkte AG
254
242 Forts null null Ste- null Canada
d'rables Hyacinth
e
255
Handelsgesellsc Petersen der 112a n ny
haft mbH
256
Hill
Example
257
Emparedados y Trujillo la D.F.
helados Constituci
n 2222
258
Holdings Brown Gardens 6LT
12
Brewery
259
Tpica Pedro Romero,
Freyre 33
260
Bacchus Wine Tannamur St. er 2K1
Cellars i
261
Atlntico Ltda. Moncada Gustavo Aires na
Moncada
8585 Piso
20-A
262
67 Ricardo Janete Av. Rio de 02389- Brazil
Adocicados Limeira Copacaba Janeiro 890
na, 267
263
81 Tradio Anabela Av. Ins So 05634- Brazil
Hipermercados Domingue de Castro, Paulo 030
s 414
264
96 Cooperativa de null null Oviedo null Spain
Quesos 'Las
Cabras'
265
111 Leka Trading null null Singapo null Singap
re ore
266
Biscuits, Ltd. ter
267
ranta
268
GmbH & Co. ny
KG
269
176 Escargots null null Montcea null France
Nouveaux u
270
190 Plutzer Martin Bogenalle Frankfur 60439 Germa
Lebensmittelgr Bein e 51 t ny
omrkte AG
271
202 G'day, Mate Wendy 170 Prince Sydney 2042 Australi
Mackenzi Edward a
e Parade
Hunter's
Hill
272
215 New Orleans null null New null USA
Cajun Delights Orleans
273
AB m n
274
Musashino
-shi
275
260 Aux joyeux Guylne 203, Rue Paris 75004 France
ecclsiastiques Nodier des
Francs-
Bourgeois
276
271 Forts Chantal 148 rue Ste- J2S Canada
d'rables Goulet Chasseur Hyacinth 7S8
e
Example
Number of Records: 77
1 Chais 1 1 10 boxes 18
x 20
bags
2 Chang 1 1 24 - 12 19
oz
bottles
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
10 Ikura 4 8 12 - 200 31
ml jars
11 Queso Cabrales 5 4 1 kg 21
pkg.
13 Konbu 6 8 2 kg box 6
17 Alice Mutton 7 6 20 - 1 kg 39
tins
278
22 Gustaf's 9 5 24 - 500 21
Knckebrd g pkgs.
23 Tunnbrd 9 5 12 - 250 9
g pkgs.
34 Sasquatch Ale 16 1 24 - 12 14
oz
bottles
35 Steeleye Stout 16 1 24 - 12 18
oz
bottles
279
g pkgs.
42 Singaporean 20 5 32 - 1 kg 14
Hokkien Fried Mee pkgs.
46 Spegesild 21 8 4 - 450 g 12
glasses
49 Maxilaku 23 3 24 - 50 g 20
pkgs.
52 Filo Mix 24 5 16 - 2 kg 7
boxes
280
55 Pt chinois 25 6 24 boxes 24
x 2 pies
58 Escargots de 27 8 24 13.25
Bourgogne pieces
59 Raclette 28 4 5 kg 55
Courdavault pkg.
66 Louisiana Hot 2 2 24 - 8 oz 17
Spiced Okra jars
67 Laughing 16 1 24 - 12 14
Lumberjack Lager oz
bottles
69 Gudbrandsdalsost 15 4 10 kg 36
pkg.
281
bottles
73 Rd Kaviar 17 8 24 - 150 15
g jars
74 Longlife Tofu 4 7 5 kg 10
pkg.
76 Lakkalikri 23 1 500 ml 18
Syntax
CREATE DATABASE databasename;
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
Syntax
DROP DATABASE databasename;
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;
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.).
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)
);
Tip: The empty "Persons" table can now be filled with data with the
SQL INSERT INTO statement.
284
Create Table Using Another Table
The new table gets the same column definitions. All columns or specific
columns can be selected.
If you create a new table using an existing table, the new table will be
filled with the existing values from the old table.
Syntax
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
Syntax
DROP TABLE table_name;
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.
Syntax
TRUNCATE TABLE table_name;
The ALTER TABLE statement is also used to add and drop various
constraints on an existing table.
286
SQL Server / MS Access:
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.
Notice that the "DateOfBirth" column is now of type year and is going to
hold a year in a two- or four-digit format.
288
We use the following SQL statement:
SQL 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
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.
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.
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.
However, you can have many UNIQUE constraints per table, but only
one PRIMARY KEY constraint per table.
The following SQL creates a UNIQUE constraint on the "ID" column when
the "Persons" table is created:
291
FirstName varchar(255),
Age int
);
MySQL:
292
DROP a UNIQUE Constraint
MySQL:
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.
The following SQL creates a PRIMARY KEY on the "ID" column when the
"Persons" table is created:
MySQL:
293
SQL Server / Oracle / MS Access:
To create a PRIMARY KEY constraint on the "ID" column when the table
is already created, use the following SQL:
294
MySQL / SQL Server / Oracle / MS Access:
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).
MySQL:
"Persons" table:
295
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
"Orders" table:
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.
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.
MySQL:
297
SQL FOREIGN KEY on ALTER TABLE
MySQL:
The CHECK constraint is used to limit the value range that can be placed
in a 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.
MySQL:
299
To create a CHECK constraint on the "Age" column when the table is
already created, use the following SQL:
The default value will be added to all new records IF no other value is
specified.
The following SQL sets a DEFAULT value for the "City" column when the
"Persons" table is created:
MySQL:
Oracle:
MySQL:
301
SQL Server / Oracle / MS Access:
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.
Note: The syntax for creating indexes varies among different databases.
Therefore: Check the syntax for creating indexes in your database.
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:
MS Access:
SQL Server:
DB2/Oracle:
MySQL:
Often this is the primary key field that we would like to be created
automatically every time a new record is inserted.
303
CREATE TABLE Persons (
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
To let the AUTO_INCREMENT sequence start with another value, use the
following SQL statement:
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):
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".
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):
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".
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):
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".
You will have to create an auto-increment field with the sequence object
(this object generates a number sequence).
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):
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
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.
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:
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:
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":
We can also add a condition to the query. Let's see the total sale only
for the category "Beverages":
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 Injection
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 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.
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.
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?
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.
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"
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.
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;
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
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.
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.
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
txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserID);
command.ExecuteReader();
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();
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.
The most common SQL hosting databases are MS SQL Server, Oracle,
MySQL, and MS Access.
MS SQL Server
SQL Server is a very powerful, robust and full featured SQL database
system.
Oracle
Oracle is a very powerful, robust and full featured SQL database system.
MySQL
314
MySQL is a very powerful, robust and full featured SQL database
system.
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
Function Description
315
LAST() Returns the last value
Function Description
CONCAT()
LEFT()
316
LOWER() / Converts character data to lower case
LCASE()
LTRIM()
PATINDEX()
REPLACE()
RIGHT()
RTRIM()
The following table lists the most important built-in date functions in
MySQL:
317
Function Description
The following table lists the most important built-in date functions in
SQL Server:
318
Function Description
Function Description
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.
MySQL comes with the following data types for storing a date or a
date/time value in the database:
SQL Server comes with the following data types for storing a date or a
date/time value in the database:
Note: The date types are chosen for a column when you create a new
table in your database!
320
1 Geitost 2008-11-11
1 Geitost 2008-11-11
Now, assume that the "Orders" table looks like this (notice the time
component in the "OrderDate" column):
321
OrderId ProductName OrderDate
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!
322
1 Jarlsberg 10.45 16 15
2 Mascarpone 32.56 23
3 Gorgonzola 15.67 9 20
SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder)
FROM Products
In the example above, if any of the "UnitsOnOrder" values are NULL, the
result 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
SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))
FROM Products
SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0
))
FROM Products
SQL Operators
SQL Arithmetic Operators
30 +
+ Add 20
50
30 -
- Subtract 20
10
324
30 *
* Multiply 20
600
Number of
/ Divide Records: 1
30 /
10
17 %
% Modulo 5
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
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
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
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.
43 Ipoh Coffee 20 1 16 - 46
500 g
tins
51 Manjimup 24 7 50 - 53
Dried Apples 300 g
pkgs.
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
63 Vegie-spread 7 2 15 - 43.9
625 g
jars
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
11 Queso Cabrales
328
13 Konbu
14 Tofu
15 Genen Shouyu
16 Pavlova
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
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
68 Scottish Longbreads
70 Outback Lager
71 Fltemysost
73 Rd Kaviar
74 Longlife Tofu
75 Rhnbru Klosterbier
76 Lakkalikri
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
26 Gumbr Gummibrchen
27 Schoggi Schokolade
28 Rssle Sauerkraut
29 Thringer Rostbratwurst
32 Mascarpone Fabioli
38 Cte de Blaye
43 Ipoh Coffee
53 Perth Pasties
59 Raclette Courdavault
60 Camembert Pierrot
62 Tarte au sucre
63 Vegie-spread
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
11 Queso Cabrales
13 Konbu
14 Tofu
15 Genen Shouyu
16 Pavlova
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
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
68 Scottish Longbreads
70 Outback Lager
71 Fltemysost
73 Rd Kaviar
74 Longlife Tofu
75 Rhnbru Klosterbier
76 Lakkalikri
333
ProductID ProductName
< Not
> equ 2 Chang
al
to 3 Aniseed Syrup
10 Ikura
11 Queso Cabrales
13 Konbu
14 Tofu
15 Genen Shouyu
16 Pavlova
17 Alice Mutton
18 Carnarvon Tigers
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
43 Ipoh Coffee
44 Gula Malacca
45 Rgede sild
46 Spegesild
47 Zaanse koeken
48 Chocolade
49 Maxilaku
50 Valkoinen suklaa
52 Filo Mix
335
53 Perth Pasties
54 Tourtire
55 Pt chinois
57 Ravioli Angelo
58 Escargots de Bourgogne
59 Raclette Courdavault
60 Camembert Pierrot
61 Sirop d'rable
62 Tarte au sucre
63 Vegie-spread
68 Scottish Longbreads
69 Gudbrandsdalsost
70 Outback Lager
71 Fltemysost
72 Mozzarella di Giovanni
73 Rd Kaviar
74 Longlife Tofu
75 Rhnbru Klosterbier
336
SQL Compound Operators
Operator Description
+= Add equals
-= Subtract equals
*= Multiply equals
/= Divide equals
%= Modulo equals
337
SQL Logical Operators
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
338
Queens
bridge
Error
ANY TRUE
if any
one
of a
set of
comp
ariso
ns
are
TRUE
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
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
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.
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
42 Singaporean 20 5 32 - 14
Hokkien 1 kg
343
Fried Mee pkgs.
43 Ipoh Coffee 20 1 16 - 46
500
g tins
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
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
347
s du ue Laurist s ce
monde Perrier on
348
21 Familia Aria Rua So 05442 Brazi
Arquibal Cruz Ors, Paulo -030 l
do 92
349
101 Refresco null null So null Brazi
s Paulo l
America
nas
LTDA
350
Buttini no
s.r.l.
351
Trading a Leka Serang pore apor
oon e
Loop,
Suite
#402
352
252 Refresco Carlos Av. das So 5442 Brazi
s Diaz Americ Paulo l
America anas
nas 12.890
LTDA
353
3 Antonio Antoni Matade Mxic 0502 Mexi
Moreno o ros o D.F. 3 co
Taquera Moren 2312
o
354
d
355
27 Franchi Paolo Via Torino 1010 Italy
S.p.A. Accorti Monte 0
Bianco
34
356
39 Kniglich Philip Maubel Brand 1477 Germ
Essen Crame str. 90 enbur 6 any
r g
357
Alimentari ni Ludovic mo 0
Riuniti Rovelli o il
Moro
22
358
Comidas mo Dr. o D.F. 3 co
clsicas Fernn Jorge
dez Cash
321
359
tti Ln.
360
t Ibsen get 45 mark
361
97 Mayumi's null null Osaka null Japa
n
362
113 Zaanse null null Zaand null Neth
Snoepfabri am erlan
ek ds
363
129 PB null null Gteb null Swed
Knckebr org en
d AB
364
147 Escargots null null Montc null Franc
Nouveaux eau e
365
elgromr
kte AG
366
180 New Shelley P.O. New 7011 USA
Orleans Burke Box Orlea 7
Cajun 78934 ns
Delights
367
elgromr
kte AG
368
203 Ma Maison Jean- 2960 Montr H1J Cana
Guy Rue St. al 1C3 da
Lauzon Laurent
369
Orleans Orlea
Cajun ns
Delights
370
Fortini na
s.r.l.
371
246 Tokyo Yoshi 9-8 Tokyo 100 Japa
Traders Nagas Sekima n
e i
Musash
ino-shi
372
Fortini Rossi Dante, na 0
s.r.l. 75
373
pturage Noz 3, rue y 0 e
des
Alpes
374
uth Crowth House n 1RZ
er 300
Queen
sbridge
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 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.
376
VARCHAR(n) or Character string. Variable length. Maximum length
CHARACTER n
VARYING(n)
377
NUMERIC(p,s) Exact numerical, precision p, scale s. (Same as
DECIMAL)
378
ARRAY A set-length and ordered collection of elements
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:
379
currency Currency Money N/A N/A Money
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!
Data types and ranges for Microsoft Access, MySQL and SQL Server.
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
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
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
Lookup Let you type a list of options, which can then be chosen from a 4 bytes
Wizard drop-down list
In MySQL there are three main data types : text, number, and
Date/Time types.
Text types:
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
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
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.
SET Similar to ENUM except that SET may contain up to 64 list items and
can store more than one choice
Number types:
383
TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number
of digits may be specified in parenthesis
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
384
decimal point is specified in the d parameter
Date types:
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.
386
nvarchar(max) Variable width Unicode string. Maximum
536,870,912 characters
Number types:
387
int Allows whole numbers between -2,147,483,648 and 4 bytes
2,147,483,647
5-17
decimal(p,s) Fixed precision and scale numbers. bytes
388
real Floating precision number data from -3.40E + 38 to 3.40E + 4 bytes
38
Date types:
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
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
389
Data type Description
sql_variant Stores up to 8,000 bytes of data of various data types, except text,
ntext, and timestamp
390
or
or
SELECT column_name
FROM table_name AS table_alias
or
391
or
IN SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
392
or
SELECT * SELECT *
FROM table_name
393
or
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name
Source : https://www.w3schools.com/sql/sql_quickref.asp
SQL Quiz
The Test
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.
Good luck!
The perfect solution for professionals who need to balance work, family,
and career building.
The XML Certificate documents your knowledge of XML, XML DOM and
XSLT.
395