Where: SQL Clause
Where: SQL Clause
Previous
Next Chapter
The WHERE clause is used to filter records.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerI CustomerNam ContactNam Address
D
e
e
City
PostalCod Country
e
Alfreds
Futterkiste
Berlin
12209
German
y
Ana Trujillo
Ana Trujillo
Emparedados y
helados
Avda. de la
Constitucin
2222
Mxic
o D.F.
05021
Mexico
Antonio
Moreno
Taquera
Antonio
Moreno
Mataderos
2312
Mxic
o D.F.
05023
Mexico
Around the
Horn
Thomas
Hardy
WA1 1DP
UK
Berglunds
snabbkp
Christina
Berglund
Berguvsvge Lule
n8
S-958 22
Sweden
The following SQL statement selects all the customers from the country "Mexico", in
the "Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Mexico';
Try it yourself
Example
SELECT * FROM Customers
WHERE CustomerID=1;
Try it yourself
Description
Equal
<>
>
Greater than
<
Less than
>=
<=
BETWEEN
LIKE
IN
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerI
D
City
PostalCod Country
e
Alfreds
Futterkiste
Maria Anders
Ana Trujillo
Emparedados y
helados
Ana Trujillo
Avda. de la
Constitucin
2222
Mxico 05021
D.F.
Mexico
Mataderos
2312
Mxico 05023
D.F.
Mexico
Around the
Horn
Thomas
Hardy
120 Hanover
Sq.
Londo
n
WA1 1DP
UK
Berglunds
snabbkp
Christina
Berglund
Berguvsvge
n8
Lule
S-958 22
Sweden
12209
Example
SELECT * FROM Customers
WHERE Country='Germany'
AND City='Berlin';
Try it yourself
OR Operator Example
German
y
The following SQL statement selects all customers from the city "Berlin" OR
"Mnchen", in the "Customers" table:
Example
SELECT * FROM Customers
WHERE City='Berlin'
OR City='Mnchen';
Try it yourself
Example
SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='Mnchen');
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerI CustomerNa
D
me
ContactNa
me
Address
City
PostalCo
de
Countr
y
Alfreds
Futterkiste
Maria
Anders
Obere Str.
57
Berlin
12209
German
y
Ana Trujillo
Ana Trujillo
Avda. de la
Mxic
05021
Mexico
Emparedados
y helados
Constitucin o D.F.
2222
Antonio
Moreno
Taquera
Antonio
Moreno
Mataderos
2312
Mxic 05023
o D.F.
Around the
Horn
Thomas
Hardy
120
Londo WA1 1DP
Hanover Sq. n
UK
Berglunds
snabbkp
Christina
Berglund
Berguvsvg
en 8
Sweden
Lule
S-958 22
Mexico
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;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerI
D
CustomerNam ContactNam
e
e
Address
87
Wartian Herkku
Pirkko
Koskitalo
88
Wellington
Importadora
Paula Parente
89
White Clover
Markets
90
91
City
PostalCod
e
Countr
y
Torikatu 38 Oulu
90110
Finland
Rua do
Mercado,
12
Resend
e
08737-363
Brazil
Seattle
98128
USA
Wilman Kala
Matti
Karttunen
Keskuskat
u 45
Helsinki
21240
Finland
Wolski
Zbyszek
01-012
Poland
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode,
Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerI
CustomerName
ContactName
Address
City
Posta
D
1
Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin
12209
Avda. de la
Constitucin 2222
Mxico
D.F.
05021
Antonio Moreno
Mataderos 2312
Mxico
D.F.
05023
Thomas Hardy
London
WA1 1
Berglunds snabbkp
Christina
Berglund
Berguvsvgen 8
Lule
S-958
Example
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';
Try it yourself
The selection from the "Customers" table will now look like this:
CustomerI
D
CustomerName
ContactName
Address
City
Posta
Alfreds Futterkiste
Alfred Schmidt
Obere Str. 57
Hamburg
12209
Ana Trujillo
Emparedados y helados
Ana Trujillo
Avda. de la
Constitucin 2222
Mxico
D.F.
05021
Mxico
D.F.
05023
Thomas Hardy
London
WA1 1
Berglunds snabbkp
Christina
Berglund
Berguvsvgen 8
Lule
S-958
Update Warning!
Be careful when updating records. If we had omitted the WHERE clause, in the
example above, like this:
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg';
The "Customers" table would have looked like this:
CustomerI CustomerNam ContactNam Address
D
e
e
1
Alfreds
Futterkiste
Alfred
Schmidt
City
PostalCod Country
e
12209
German
y
Ana Trujillo
Alfred
Emparedados y Schmidt
helados
Avda. de la
Constitucin
2222
Hambur
g
05021
Mexico
Mataderos
2312
Hambur
g
05023
Mexico
Around the
Horn
Alfred
Schmidt
120 Hanover
Sq.
Hambur
g
WA1 1DP
UK
Berglunds
snabbkp
Alfred
Schmidt
Berguvsvge
n8
Hambur
g
S-958 22
Sweden
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerI
D
CustomerName
ContactName
Address
City
Posta
Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin
12209
Avda. de la
Constitucin 2222
Mxico
D.F.
05021
Antonio Moreno
Mataderos 2312
Mxico
D.F.
05023
Thomas Hardy
London
WA1 1
Berglunds snabbkp
Christina
Berglund
Berguvsvgen 8
Lule
S-958
Example
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste' AND ContactName='Maria Anders';
CustomerName
ContactName
Address
City
Posta
Avda. de la
Constitucin 2222
Mxico
D.F.
0502
Antonio Moreno
Mataderos 2312
Mxico
D.F.
0502
Thomas Hardy
London
WA1
Berglunds snabbkp
Christina
Berglund
Berguvsvgen 8
Lule
S-958
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerI
D
CustomerName
ContactName
Address
City
Posta
Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin
12209
Avda. de la
Constitucin 2222
Mxico
D.F.
05021
Antonio Moreno
Mataderos 2312
Mxico
D.F.
05023
Thomas Hardy
London
WA1 1
Berglunds snabbkp
Christina
Berglund
Berguvsvgen 8
Lule
S-958
Example
Example
SELECT * FROM Customers
WHERE City LIKE '%s';
Try it yourself
The following SQL statement selects all customers with a Country containing the
pattern "land":
Example
SELECT * FROM Customers
WHERE Country LIKE '%land%';
Try it yourself
Using the NOT keyword allows you to select records that does NOT match the
pattern.
The following SQL statement selects all customers with a Country NOT containing
the pattern "land":
Example
SELECT * FROM Customers
WHERE Country NOT LIKE '%land%';
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
In this tutorial we will use the well-known Northwind sample database.
CustomerName
ContactName
Address
City
Posta
Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin
12209
Avda. de la
Constitucin 2222
Mxico
D.F.
05021
Antonio Moreno
Mataderos 2312
Mxico
D.F.
05023
Thomas Hardy
London
WA1 1
Berglunds snabbkp
Christina
Berglund
Berguvsvgen 8
Lule
S-958
IN Operator Example
The following SQL statement selects all customers with a City of "Paris" or "London":
Example
SELECT * FROM Customers
WHERE City IN ('Paris','London');
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Products" table:
ProductID
ProductName
SupplierID
CategoryID
Unit
Chais
10 boxes x 20 b
Chang
24 - 12 oz bottl
Aniseed Syrup
12 - 550 ml bot
48 - 6 oz jars
36 boxes
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
Try it yourself
Example
SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3);
Try it yourself
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'C' AND 'M';
Try it yourself
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'C' AND 'M';
Try it yourself
Sample Table
Below is a selection from the "Orders" table:
OrderID
CustomerID
EmployeeID
OrderDate
Ship
10248
90
7/4/1996
10249
81
7/5/1996
10250
34
7/8/1996
10251
84
7/9/1996
10252
76
7/10/1996
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#;
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.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerI
D
CustomerName
ContactName Address
City
Posta
e
Ana Trujillo
Avda. de la
Constitucin 2222
Mxico
D.F.
0502
Antonio
Moreno
Mataderos 2312
Mxico
D.F.
0502
Thomas Hardy
London
WA1
CustomerID
EmployeeID
OrderDate
Ship
10354
58
1996-11-14
10355
1996-11-15
10356
86
1996-11-18
Example
SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;
Try it yourself
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;
Try it yourself
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;
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;
Try it yourself
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName="Around the Horn" AND
Customers.CustomerID=Orders.CustomerID;
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 return 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
1996-09-18
10309
37
1996-09-19
10310
77
1996-09-20
CustomerName
ContactName
Alfreds Futterkiste
Maria Anders
Ana Trujillo
Antonio Moreno
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;
Try it yourself
CustomerName
10308
10365
10383
10355
10278
Berglunds snabbkp
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.
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
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
CustomerID
CustomerName
ContactName Address
City
Posta
Alfreds Futterkiste
Maria Anders
Berlin
12209
Obere Str. 57
Avda. de la
Constitucin 2222
Mxico
D.F.
05021
Mataderos 2312
Mxico
D.F.
05023
Antonio
Moreno
OrderID
CustomerID
EmployeeID
OrderDate
Ship
10308
1996-09-18
10309
37
1996-09-19
10310
77
1996-09-20
The following SQL statement will return all customers with orders:
Example
The LEFT JOIN keyword returns all rows from the left table (table1), with the
matching rows in the right table (table2). The result is NULL in the right side
when there is no match.
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
or:
SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;
PS! In some databases LEFT JOIN is called LEFT OUTER JOIN.
Demo Database
CustomerID
CustomerName
ContactName Address
City
Posta
Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin
12209
Avda. de la
Constitucin 2222
Mxico
D.F.
05021
Mataderos 2312
Mxico
D.F.
05023
Antonio
Moreno
OrderID
CustomerID
EmployeeID
OrderDate
Ship
10308
1996-09-18
10309
37
1996-09-19
10310
77
1996-09-20
The following SQL statement will return all customers, and any orders they
might have:
Example
Note: The LEFT JOIN keyword returns all the rows 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.
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.
Demo Database
OrderID
CustomerID
EmployeeID
OrderDate
Ship
10308
1996-09-18
10309
37
1996-09-19
10310
77
1996-09-20
Photo
Notes
Davolio
Nancy
12/8/1968
EmpID1.pic
Fuller
Andrew
2/19/1952
EmpID2.pic
Leverling
Janet
8/30/1963
EmpID3.pic
The following SQL statement will return all employees, and any orders they
have placed:
Example
SELECT Orders.OrderID, Employees.FirstName
FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID;
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.
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
Demo Database
CustomerID
CustomerName
ContactName Address
City
Posta
Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin
12209
Avda. de la
Constitucin 2222
Mxico
D.F.
05021
Mataderos 2312
Mxico
D.F.
05023
Antonio
Moreno
OrderID
CustomerID
EmployeeID
OrderDate
Ship
10308
1996-09-18
10309
37
1996-09-19
10310
77
1996-09-20
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
OrderI
Alfreds Futterkiste
Ana Trujillo Emparedados y helados
10308
10365
10382
10351
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID
CustomerName
ContactName Address
City
Posta
Alfreds Futterkiste
2
3
Maria Anders
Obere Str. 57
Berlin
12209
Avda. de la
Constitucin 2222
Mxico
D.F.
05021
Mataderos 2312
Mxico
D.F.
05023
Antonio
Moreno
SupplierName
ContactName
Address
City
Posta
e
Exotic Liquid
Charlotte
Cooper
49 Gilbert St.
Londona
EC1 4
Shelley Burke
P.O. Box
78934
New
Orleans
7011
Grandma Kelly's
Homestead
Regina Murphy
707 Oxford
Rd.
Ann Arbor
4810
Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
Try it yourself
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!
Example
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
SELECT *
INTO CustomersBackup2013
FROM Customers;
Use the IN clause to copy the table into another database:
SELECT *
INTO CustomersBackup2013 IN 'Backup.mdb'
FROM Customers;
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;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID
CustomerName
ContactName Address
City
Posta
Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin
12209
Avda. de la
Constitucin 2222
Mxico
D.F.
05021
Mataderos 2312
Mxico
D.F.
05023
Antonio
Moreno
SupplierName
ContactName
Address
City
Postal
Code
Coun
Exotic Liquid
Charlotte
Cooper
49 Gilbert
St.
Londona
EC1 4SD
UK
Shelley Burke
P.O. Box
78934
New
Orleans
70117
USA
Grandma Kelly's
Homestead
Regina Murphy
707 Oxford
Rd.
Ann Arbor
48104
USA
Example
INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers;
Try it yourself
Example
INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers
WHERE Country='Germany';
SQL Views
Previous
Next Chapter
A view is a virtual table.
This chapter shows how to create, update, and delete a view.
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. Now we want to see the total sale only for
the category "Beverages":
SELECT * FROM [Category Sales For 1997]
WHERE CategoryName='Beverages'
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action, the action is
aborted by the constraint.
Constraints can be specified when the table is created (inside the CREATE TABLE
statement) or after the table is created (inside the ALTER TABLE statement).
UNIQUE - Ensures that each row for a column must have a unique value
FOREIGN KEY - Ensure the referential integrity of the data in one table to
match values in another table
DEFAULT - Specifies a default value when specified none for this column
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandn
Svendson
Tove
Borgvn 23
Sandn
Pettersen
Kari
Storgt 20
Stavan
O_Id
OrderNo P_Id
77895
44678
22456
24562
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column
in the "Persons" table.
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
The FOREIGN KEY constraint is used to prevent actions that would destroy
links between tables.
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.
The following SQL creates a FOREIGN KEY on the "P_Id" column when the
"Orders" table is created:
MySQL:
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)
SQL Server / Oracle / MS Access:
CREATE TABLE Orders
(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders"
table is already created, use the following SQL:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
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_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
Indexes allow the database application to find data fast; without reading the whole
table.
Indexes
An index can be created in a table to find data more quickly and efficiently.
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 you should only create indexes on
columns (and tables) that will be frequently searched against.
Previous
Next Chapter
Auto-increment allows a unique number to be generated when a new record is
inserted into a table.