SQL BASICS
A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data.
In this tutorial we will use the well-known Northwind sample database (included in MS Access and MS SQL Server).
Below is a selection from the "Customers" table:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
The table above contains five records (one for each customer) and seven columns (CustomerID, CustomerName, ContactName, Address, City, PostalCode, and Country).
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:
SELECT * FROM Customers;
select
is the same as SELECT
In this tutorial we will write all SQL keywords in upper-case.
Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server.
In this tutorial, we will use semicolon at the end of each SQL statement.
SELECT
- extracts data from a databaseUPDATE
- updates data in a databaseDELETE
- deletes data from a databaseINSERT INTO
- inserts new data into a databaseCREATE DATABASE
- creates a new databaseALTER DATABASE
- modifies a databaseCREATE TABLE
- creates a new tableALTER TABLE
- modifies a tableDROP TABLE
- deletes a tableCREATE INDEX
- creates an index (search key)DROP INDEX
- deletes an indexThe SELECT
statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If you want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
The following SQL statement selects the "CustomerName" and "City" columns from the "Customers" table:
SELECT CustomerName, City FROM Customers;
The SELECT DISTINCT
statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
SELECT DISTINCT column1, column2, ...
FROM table_name;
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
The following SQL statement selects all (including the duplicates) values from the "Country" column in the "Customers" table:
SELECT Country FROM Customers;
Now, let us use the SELECT DISTINCT
statement and see the result.
SELECT DISTINCT Examples
The following SQL statement selects only the DISTINCT values from the "Country" column in the "Customers" table:
SELECT DISTINCT Country FROM Customers;
The following SQL statement lists the number of different (distinct) customer countries:
SELECT COUNT(DISTINCT Country) FROM Customers;
Note: The example above will not work in Firefox! Because COUNT(DISTINCT column_name) is not supported in Microsoft Access databases. Firefox is using Microsoft Access in our examples.
Here is the workaround for MS Access:
SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);
The WHERE
clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: The WHERE
clause is not only used in SELECT
statements, it is also used in UPDATE
, DELETE
, etc.!
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
The following SQL statement selects all the customers from the country "Mexico", in the "Customers" table:
SELECT * FROM Customers
WHERE Country='Mexico';
SQL requires single quotes around text values (most database systems will also allow double quotes).
However, numeric fields should not be enclosed in quotes:
SELECT * FROM Customers
WHERE CustomerID=1;
The following operators can be used in the WHERE
clause:
Operator | Description | Example |
---|---|---|
= | Equal | SELECT * FROM Products WHERE Price = 18; |
> | Greater than | SELECT * FROM Products WHERE Price > 30; |
< | Less than | SELECT * FROM Products WHERE Price < 30; |
>= | Greater than or equal | SELECT * FROM Products WHERE Price >= 30; |
<= | Less than or equal | SELECT * FROM Products WHERE Price <= 30; |
<> | Not equal. Note: In some versions of SQL this operator may be written as != | SELECT * FROM Products WHERE Price <> 18; |
BETWEEN | Between a certain range | SELECT * FROM Products WHERE Price BETWEEN 50 AND 60; |
LIKE | Search for a pattern | SELECT * FROM Customers WHERE City LIKE 's%'; |
IN | To specify multiple possible values for a column | SELECT * FROM Customers WHERE City IN ('Paris','London'); |
The WHERE
clause can be combined with AND
, OR
, and NOT
operators.
The AND
and OR
operators are used to filter records based on more than one condition:
AND
operator displays a record if all the conditions separated by AND
are TRUE.OR
operator displays a record if any of the conditions separated by OR
is TRUE.The NOT
operator displays a record if the condition(s) is NOT TRUE.
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
The table below shows the complete "Customers" table from the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
6 | Blauer See Delikatessen | Hanna Moos | Forsterstr. 57 | Mannheim | 68306 | Germany |
7 | Blondel père et fils | Frédérique Citeaux | 24, place Kléber | Strasbourg | 67000 | France |
8 | Bólido Comidas preparadas | Martín Sommer | C/ Araquil, 67 | Madrid | 28023 | Spain |
9 | Bon app' | Laurence Lebihans | 12, rue des Bouchers | Marseille | 13008 | France |
10 | Bottom-Dollar Marketse | Elizabeth Lincoln | 23 Tsawassen Blvd. | Tsawassen | T2F 8M4 | Canada |
11 | B's Beverages | Victoria Ashworth | Fauntleroy Circus | London | EC2 5NT | UK |
12 | Cactus Comidas para llevar | Patricio Simpson | Cerrito 333 | Buenos Aires | 1010 | Argentina |
13 | Centro comercial Moctezuma | Francisco Chang | Sierras de Granada 9993 | México D.F. | 05022 | Mexico |
14 | Chop-suey Chinese | Yang Wang | Hauptstr. 29 | Bern | 3012 | Switzerland |
15 | Comércio Mineiro | Pedro Afonso | Av. dos Lusíadas, 23 | São Paulo | 05432-043 | Brazil |
16 | Consolidated Holdings | Elizabeth Brown | Berkeley Gardens 12 Brewery | London | WX1 6LT | UK |
17 | Drachenblut Delikatessend | Sven Ottlieb | Walserweg 21 | Aachen | 52066 | Germany |
18 | Du monde entier | Janine Labrune | 67, rue des Cinquante Otages | Nantes | 44000 | France |
19 | Eastern Connection | Ann Devon | 35 King George | London | WX3 6FW | UK |
20 | Ernst Handel | Roland Mendel | Kirchgasse 6 | Graz | 8010 | Austria |
21 | Familia Arquibaldo | Aria Cruz | Rua Orós, 92 | São Paulo | 05442-030 | Brazil |
22 | FISSA Fabrica Inter. Salchichas S.A. | Diego Roel | C/ Moralzarzal, 86 | Madrid | 28034 | Spain |
23 | Folies gourmandes | Martine Rancé | 184, chaussée de Tournai | Lille | 59000 | France |
24 | Folk och fä HB | Maria Larsson | Åkergatan 24 | Bräcke | S-844 67 | Sweden |
25 | Frankenversand | Peter Franken | Berliner Platz 43 | München | 80805 | Germany |
26 | France restauration | Carine Schmitt | 54, rue Royale | Nantes | 44000 | France |
27 | Franchi S.p.A. | Paolo Accorti | Via Monte Bianco 34 | Torino | 10100 | Italy |
28 | Furia Bacalhau e Frutos do Mar | Lino Rodriguez | Jardim das rosas n. 32 | Lisboa | 1675 | Portugal |
29 | Galería del gastrónomo | Eduardo Saavedra | Rambla de Cataluña, 23 | Barcelona | 08022 | Spain |
30 | Godos Cocina Típica | José Pedro Freyre | C/ Romero, 33 | Sevilla | 41101 | Spain |
31 | Gourmet Lanchonetes | André Fonseca | Av. Brasil, 442 | Campinas | 04876-786 | Brazil |
32 | Great Lakes Food Market | Howard Snyder | 2732 Baker Blvd. | Eugene | 97403 | USA |
33 | GROSELLA-Restaurante | Manuel Pereira | 5ª Ave. Los Palos Grandes | Caracas | 1081 | Venezuela |
34 | Hanari Carnes | Mario Pontes | Rua do Paço, 67 | Rio de Janeiro | 05454-876 | Brazil |
35 | HILARIÓN-Abastos | Carlos Hernández | Carrera 22 con Ave. Carlos Soublette #8-35 | San Cristóbal | 5022 | Venezuela |
36 | Hungry Coyote Import Store | Yoshi Latimer | City Center Plaza 516 Main St. | Elgin | 97827 | USA |
37 | Hungry Owl All-Night Grocers | Patricia McKenna | 8 Johnstown Road | Cork | Ireland | |
38 | Island Trading | Helen Bennett | Garden House Crowther Way | Cowes | PO31 7PJ | UK |
39 | Königlich Essen | Philip Cramer | Maubelstr. 90 | Brandenburg | 14776 | Germany |
40 | La corne d'abondance | Daniel Tonini | 67, avenue de l'Europe | Versailles | 78000 | France |
41 | La maison d'Asie | Annette Roulet | 1 rue Alsace-Lorraine | Toulouse | 31000 | France |
42 | Laughing Bacchus Wine Cellars | Yoshi Tannamuri | 1900 Oak St. | Vancouver | V3F 2K1 | Canada |
43 | Lazy K Kountry Store | John Steel | 12 Orchestra Terrace | Walla Walla | 99362 | USA |
44 | Lehmanns Marktstand | Renate Messner | Magazinweg 7 | Frankfurt a.M. | 60528 | Germany |
45 | Let's Stop N Shop | Jaime Yorres | 87 Polk St. Suite 5 | San Francisco | 94117 | USA |
46 | LILA-Supermercado | Carlos González | Carrera 52 con Ave. Bolívar #65-98 Llano Largo | Barquisimeto | 3508 | Venezuela |
47 | LINO-Delicateses | Felipe Izquierdo | Ave. 5 de Mayo Porlamar | I. de Margarita | 4980 | Venezuela |
48 | Lonesome Pine Restaurant | Fran Wilson | 89 Chiaroscuro Rd. | Portland | 97219 | USA |
49 | Magazzini Alimentari Riuniti | Giovanni Rovelli | Via Ludovico il Moro 22 | Bergamo | 24100 | Italy |
50 | Maison Dewey | Catherine Dewey | Rue Joseph-Bens 532 | Bruxelles | B-1180 | Belgium |
51 | Mère Paillarde | Jean Fresnière | 43 rue St. Laurent | Montréal | H1J 1C3 | Canada |
52 | Morgenstern Gesundkost | Alexander Feuer | Heerstr. 22 | Leipzig | 04179 | Germany |
53 | North/South | Simon Crowther | South House 300 Queensbridge | London | SW7 1RZ | UK |
54 | Océano Atlántico Ltda. | Yvonne Moncada | Ing. Gustavo Moncada 8585 Piso 20-A | Buenos Aires | 1010 | Argentina |
55 | Old World Delicatessen | Rene Phillips | 2743 Bering St. | Anchorage | 99508 | USA |
56 | Ottilies Käseladen | Henriette Pfalzheim | Mehrheimerstr. 369 | Köln | 50739 | Germany |
57 | Paris spécialités | Marie Bertrand | 265, boulevard Charonne | Paris | 75012 | France |
58 | Pericles Comidas clásicas | Guillermo Fernández | Calle Dr. Jorge Cash 321 | México D.F. | 05033 | Mexico |
59 | Piccolo und mehr | Georg Pipps | Geislweg 14 | Salzburg | 5020 | Austria |
60 | Princesa Isabel Vinhoss | Isabel de Castro | Estrada da saúde n. 58 | Lisboa | 1756 | Portugal |
61 | Que Delícia | Bernardo Batista | Rua da Panificadora, 12 | Rio de Janeiro | 02389-673 | Brazil |
62 | Queen Cozinha | Lúcia Carvalho | Alameda dos Canàrios, 891 | São Paulo | 05487-020 | Brazil |
63 | QUICK-Stop | Horst Kloss | Taucherstraße 10 | Cunewalde | 01307 | Germany |
64 | Rancho grande | Sergio Gutiérrez | Av. del Libertador 900 | Buenos Aires | 1010 | Argentina |
65 | Rattlesnake Canyon Grocery | Paula Wilson | 2817 Milton Dr. | Albuquerque | 87110 | USA |
66 | Reggiani Caseifici | Maurizio Moroni | Strada Provinciale 124 | Reggio Emilia | 42100 | Italy |
67 | Ricardo Adocicados | Janete Limeira | Av. Copacabana, 267 | Rio de Janeiro | 02389-890 | Brazil |
68 | Richter Supermarkt | Michael Holz | Grenzacherweg 237 | Genève | 1203 | Switzerland |
69 | Romero y tomillo | Alejandra Camino | Gran Vía, 1 | Madrid | 28001 | Spain |
70 | Santé Gourmet | Jonas Bergulfsen | Erling Skakkes gate 78 | Stavern | 4110 | Norway |
71 | Save-a-lot Markets | Jose Pavarotti | 187 Suffolk Ln. | Boise | 83720 | USA |
72 | Seven Seas Imports | Hari Kumar | 90 Wadhurst Rd. | London | OX15 4NB | UK |
73 | Simons bistro | Jytte Petersen | Vinbæltet 34 | København | 1734 | Denmark |
74 | Spécialités du monde | Dominique Perrier | 25, rue Lauriston | Paris | 75016 | France |
75 | Split Rail Beer & Ale | Art Braunschweiger | P.O. Box 555 | Lander | 82520 | USA |
76 | Suprêmes délices | Pascale Cartrain | Boulevard Tirou, 255 | Charleroi | B-6000 | Belgium |
77 | The Big Cheese | Liz Nixon | 89 Jefferson Way Suite 2 | Portland | 97201 | USA |
78 | The Cracker Box | Liu Wong | 55 Grizzly Peak Rd. | Butte | 59801 | USA |
79 | Toms Spezialitäten | Karin Josephs | Luisenstr. 48 | Münster | 44087 | Germany |
80 | Tortuga Restaurante | Miguel Angel Paolino | Avda. Azteca 123 | México D.F. | 05033 | Mexico |
81 | Tradição Hipermercados | Anabela Domingues | Av. Inês de Castro, 414 | São Paulo | 05634-030 | Brazil |
82 | Trail's Head Gourmet Provisioners | Helvetius Nagy | 722 DaVinci Blvd. | Kirkland | 98034 | USA |
83 | Vaffeljernet | Palle Ibsen | Smagsløget 45 | Århus | 8200 | Denmark |
84 | Victuailles en stock | Mary Saveley | 2, rue du Commerce | Lyon | 69004 | France |
85 | Vins et alcools Chevalier | Paul Henriot | 59 rue de l'Abbaye | Reims | 51100 | France |
86 | Die Wandernde Kuh | Rita Müller | Adenauerallee 900 | Stuttgart | 70563 | Germany |
87 | Wartian Herkku | Pirkko Koskitalo | Torikatu 38 | Oulu | 90110 | Finland |
88 | Wellington Importadora | Paula Parente | Rua do Mercado, 12 | Resende | 08737-363 | Brazil |
89 | White Clover Markets | Karl Jablonski | 305 - 14th Ave. S. Suite 3B | Seattle | 98128 | USA |
90 | Wilman Kala | Matti Karttunen | Keskuskatu 45 | Helsinki | 21240 | Finland |
91 | Wolski | Zbyszek | ul. Filtrowa 68 | Walla | 01-012 | Poland |
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city is "Berlin":
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "München":
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
The following SQL statement selects all fields from "Customers" where country is "Germany" OR "Spain":
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';
The following SQL statement selects all fields from "Customers" where country is NOT "Germany":
SELECT * FROM Customers
WHERE NOT Country='Germany';
You can also combine the AND
, OR
and NOT
operators.
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city must be "Berlin" OR "München" (use parenthesis to form complex expressions):
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
The following SQL statement selects all fields from "Customers" where country is NOT "Germany" and NOT "USA":
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
The ORDER BY
keyword is used to sort the result-set in ascending or descending order.
The ORDER BY
keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC
keyword.
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" column:
SELECT * FROM Customers
ORDER BY Country;
The INSERT INTO
statement is used to insert new records in a table.
It is possible to write the INSERT INTO
statement in two ways:
1. Specify both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
2. 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. Here, the INSERT INTO
syntax would be as follows:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
89 | White Clover Markets | Karl Jablonski | 305 - 14th Ave. S. Suite 3B | Seattle | 98128 | USA |
90 |
Wilman Kala | Matti Karttunen | Keskuskatu 45 | Helsinki | 21240 | Finland |
91 |
Wolski | Zbyszek | ul. Filtrowa 68 | Walla | 01-012 | Poland |
The following SQL statement inserts a new record in the "Customers" table:
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:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
89 | White Clover Markets | Karl Jablonski | 305 - 14th Ave. S. Suite 3B | Seattle | 98128 | USA |
90 |
Wilman Kala | Matti Karttunen | Keskuskatu 45 | Helsinki | 21240 | Finland |
91 |
Wolski | Zbyszek | ul. Filtrowa 68 | Walla | 01-012 | Poland |
92 | Cardinal | Tom B. Erichsen | Skagen 21 | Stavanger | 4006 | Norway |
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.
It is also possible to only insert data in specific columns.
The following SQL statement will insert a new record, but only insert data in the "CustomerName", "City", and "Country" columns (CustomerID will be updated automatically):
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
The selection from the "Customers" table will now look like this:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
89 | White Clover Markets | Karl Jablonski | 305 - 14th Ave. S. Suite 3B | Seattle | 98128 | USA |
90 |
Wilman Kala | Matti Karttunen | Keskuskatu 45 | Helsinki | 21240 | Finland |
91 |
Wolski | Zbyszek | ul. Filtrowa 68 | Walla | 01-012 | Poland |
92 | Cardinal | null | null | Stavanger | null | Norway |
A field with a NULL value is a field with no value.
If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to this field. Then, the field will be saved with a NULL value.
Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is one that has been left blank during record creation!
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
We will have to use the IS NULL
and IS NOT NULL
operators instead.
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
The IS NULL
operator is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
Tip: Always use IS NULL to look for NULL values.
The IS NOT NULL
operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
The UPDATE
statement is used to modify the existing records in a table.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Note: Be careful when updating records in a table! Notice the WHERE
clause in the UPDATE
statement. The WHERE
clause specifies which record(s) that should be updated. If you omit the WHERE
clause, all records in the table will be updated!
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
The following SQL statement updates the first customer (CustomerID = 1) with a new contact person and a new city.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
The selection from the "Customers" table will now look like this:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Alfred Schmidt | Obere Str. 57 | Frankfurt | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
It is the WHERE
clause that determines how many records will be updated.
The following SQL statement will update the ContactName to "Juan" for all records where country is "Mexico":
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
The selection from the "Customers" table will now look like this:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Alfred Schmidt | Obere Str. 57 | Frankfurt | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Juan | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Juan | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
Be careful when updating records. If you omit the WHERE
clause, ALL records will be updated!
UPDATE Customers
SET ContactName='Juan';
The selection from the "Customers" table will now look like this:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Juan | Obere Str. 57 | Frankfurt | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Juan | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Juan | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Juan | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Juan | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
The DELETE
statement is used to delete existing records in a table.
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE
clause in the DELETE
statement. The WHERE
clause specifies which record(s) should be deleted. If you omit the WHERE
clause, all records in the table will be deleted!
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers" table:
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
The "Customers" table will now look like this:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact:
DELETE FROM table_name;
The following SQL statement deletes all rows in the "Customers" table, without deleting the table:
DELETE FROM Customers;
The SELECT TOP
clause is used to specify the number of records to return.
The SELECT TOP
clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.
Note: Not all database systems support the SELECT TOP
clause. MySQL supports the LIMIT
clause to select a limited number of records, while Oracle uses FETCH FIRST n ROWS ONLY
and ROWNUM
.
SQL Server / MS Access Syntax:
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
MySQL Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Oracle 12 Syntax:
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY;
Older Oracle Syntax:
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
Older Oracle Syntax (with ORDER BY):
SELECT *
FROM (SELECT column_name(s) FROM table_name ORDER BY column_name(s))
WHERE ROWNUM <= number;
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
The following SQL statement selects the first three records from the "Customers" table (for SQL Server/MS Access):
SELECT TOP 3 * FROM Customers;
The following SQL statement shows the equivalent example for MySQL:
SELECT * FROM Customers
LIMIT 3;
The following SQL statement shows the equivalent example for Oracle:
SELECT * FROM Customers
FETCH FIRST 3 ROWS ONLY;
The following SQL statement selects the first 50% of the records from the "Customers" table (for SQL Server/MS Access):
SELECT TOP 50 PERCENT * FROM Customers;
The following SQL statement shows the equivalent example for Oracle:
SELECT * FROM Customers
FETCH FIRST 50 PERCENT ROWS ONLY;
The following SQL statement selects the first three records from the "Customers" table, where the country is "Germany" (for SQL Server/MS Access):
SELECT TOP 3 * FROM Customers
WHERE Country='Germany';
The following SQL statement shows the equivalent example for MySQL:
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;
The following SQL statement shows the equivalent example for Oracle:
SELECT * FROM Customers
WHERE Country='Germany'
FETCH FIRST 3 ROWS ONLY;
The MIN()
function returns the smallest value of the selected column.
The MAX()
function returns the largest value of the selected column.
SELECT MIN(column_name)
FROM table_name
WHERE condition;
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Below is a selection from the "Products" table in the Northwind sample database:
ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
---|---|---|---|---|---|
1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
2 | Chang | 1 | 1 | 24 - 12 oz bottles | 19 |
3 | Aniseed Syrup | 1 | 2 | 12 - 550 ml bottles | 10 |
4 | Chef Anton's Cajun Seasoning | 2 | 2 | 48 - 6 oz jars | 22 |
5 | Chef Anton's Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
The following SQL statement finds the price of the cheapest product:
SELECT MIN(Price) AS SmallestPrice
FROM Products;
The following SQL statement finds the price of the most expensive product:
SELECT MAX(Price) AS LargestPrice
FROM Products;
The COUNT()
function returns the number of rows that matches a specified criterion.
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
The AVG()
function returns the average value of a numeric column.
SELECT AVG(column_name)
FROM table_name
WHERE condition;
The SUM()
function returns the total sum of a numeric column.
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Below is a selection from the "Products" table in the Northwind sample database:
ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
---|---|---|---|---|---|
1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
2 | Chang | 1 | 1 | 24 - 12 oz bottles | 19 |
3 | Aniseed Syrup | 1 | 2 | 12 - 550 ml bottles | 10 |
4 | Chef Anton's Cajun Seasoning | 2 | 2 | 48 - 6 oz jars | 22 |
5 | Chef Anton's Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
The following SQL statement finds the number of products:
SELECT COUNT(ProductID)
FROM Products;
Note: NULL values are not counted.
The following SQL statement finds the average price of all products:
SELECT AVG(Price)
FROM Products;
Note: NULL values are ignored.
Below is a selection from the "OrderDetails" table in the Northwind sample database:
OrderDetailID | OrderID | ProductID | Quantity |
---|---|---|---|
1 | 10248 | 11 | 12 |
2 | 10248 | 42 | 10 |
3 | 10248 | 72 | 5 |
4 | 10249 | 14 | 9 |
5 | 10249 | 51 | 40 |
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:
SELECT SUM(Quantity)
FROM OrderDetails;
Note: NULL values are ignored.
The LIKE
operator is used in a WHERE
clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE
operator:
Note: MS Access uses an asterisk (*) instead of the percent sign (%), and a question mark (?) instead of the underscore (_).
The percent sign and the underscore can also be used in combinations!
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Tip: You can also combine any number of conditions using AND
or OR
operators.
Here are some examples showing different LIKE
operators with '%' and '_' wildcards:
LIKE Operator | Description |
---|---|
WHERE CustomerName LIKE 'a%' | Finds any values that start with "a" |
WHERE CustomerName LIKE '%a' | Finds any values that end with "a" |
WHERE CustomerName LIKE '%or%' | Finds any values that have "or" in any position |
WHERE CustomerName LIKE '_r%' | Finds any values that have "r" in the second position |
WHERE CustomerName LIKE 'a_%' | Finds any values that start with "a" and are at least 2 characters in length |
WHERE CustomerName LIKE 'a__%' | Finds any values that start with "a" and are at least 3 characters in length |
WHERE ContactName LIKE 'a%o' | Finds any values that start with "a" and ends with "o" |
The table below shows the complete "Customers" table from the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
6 | Blauer See Delikatessen | Hanna Moos | Forsterstr. 57 | Mannheim | 68306 | Germany |
7 | Blondel père et fils | Frédérique Citeaux | 24, place Kléber | Strasbourg | 67000 | France |
8 | Bólido Comidas preparadas | Martín Sommer | C/ Araquil, 67 | Madrid | 28023 | Spain |
9 | Bon app' | Laurence Lebihans | 12, rue des Bouchers | Marseille | 13008 | France |
10 | Bottom-Dollar Marketse | Elizabeth Lincoln | 23 Tsawassen Blvd. | Tsawassen | T2F 8M4 | Canada |
11 | B's Beverages | Victoria Ashworth | Fauntleroy Circus | London | EC2 5NT | UK |
12 | Cactus Comidas para llevar | Patricio Simpson | Cerrito 333 | Buenos Aires | 1010 | Argentina |
13 | Centro comercial Moctezuma | Francisco Chang | Sierras de Granada 9993 | México D.F. | 05022 | Mexico |
14 | Chop-suey Chinese | Yang Wang | Hauptstr. 29 | Bern | 3012 | Switzerland |
15 | Comércio Mineiro | Pedro Afonso | Av. dos Lusíadas, 23 | São Paulo | 05432-043 | Brazil |
16 | Consolidated Holdings | Elizabeth Brown | Berkeley Gardens 12 Brewery | London | WX1 6LT | UK |
17 | Drachenblut Delikatessend | Sven Ottlieb | Walserweg 21 | Aachen | 52066 | Germany |
18 | Du monde entier | Janine Labrune | 67, rue des Cinquante Otages | Nantes | 44000 | France |
19 | Eastern Connection | Ann Devon | 35 King George | London | WX3 6FW | UK |
20 | Ernst Handel | Roland Mendel | Kirchgasse 6 | Graz | 8010 | Austria |
21 | Familia Arquibaldo | Aria Cruz | Rua Orós, 92 | São Paulo | 05442-030 | Brazil |
22 | FISSA Fabrica Inter. Salchichas S.A. | Diego Roel | C/ Moralzarzal, 86 | Madrid | 28034 | Spain |
23 | Folies gourmandes | Martine Rancé | 184, chaussée de Tournai | Lille | 59000 | France |
24 | Folk och fä HB | Maria Larsson | Åkergatan 24 | Bräcke | S-844 67 | Sweden |
25 | Frankenversand | Peter Franken | Berliner Platz 43 | München | 80805 | Germany |
26 | France restauration | Carine Schmitt | 54, rue Royale | Nantes | 44000 | France |
27 | Franchi S.p.A. | Paolo Accorti | Via Monte Bianco 34 | Torino | 10100 | Italy |
28 | Furia Bacalhau e Frutos do Mar | Lino Rodriguez | Jardim das rosas n. 32 | Lisboa | 1675 | Portugal |
29 | Galería del gastrónomo | Eduardo Saavedra | Rambla de Cataluña, 23 | Barcelona | 08022 | Spain |
30 | Godos Cocina Típica | José Pedro Freyre | C/ Romero, 33 | Sevilla | 41101 | Spain |
31 | Gourmet Lanchonetes | André Fonseca | Av. Brasil, 442 | Campinas | 04876-786 | Brazil |
32 | Great Lakes Food Market | Howard Snyder | 2732 Baker Blvd. | Eugene | 97403 | USA |
33 | GROSELLA-Restaurante | Manuel Pereira | 5ª Ave. Los Palos Grandes | Caracas | 1081 | Venezuela |
34 | Hanari Carnes | Mario Pontes | Rua do Paço, 67 | Rio de Janeiro | 05454-876 | Brazil |
35 | HILARIÓN-Abastos | Carlos Hernández | Carrera 22 con Ave. Carlos Soublette #8-35 | San Cristóbal | 5022 | Venezuela |
36 | Hungry Coyote Import Store | Yoshi Latimer | City Center Plaza 516 Main St. | Elgin | 97827 | USA |
37 | Hungry Owl All-Night Grocers | Patricia McKenna | 8 Johnstown Road | Cork | Ireland | |
38 | Island Trading | Helen Bennett | Garden House Crowther Way | Cowes | PO31 7PJ | UK |
39 | Königlich Essen | Philip Cramer | Maubelstr. 90 | Brandenburg | 14776 | Germany |
40 | La corne d'abondance | Daniel Tonini | 67, avenue de l'Europe | Versailles | 78000 | France |
41 | La maison d'Asie | Annette Roulet | 1 rue Alsace-Lorraine | Toulouse | 31000 | France |
42 | Laughing Bacchus Wine Cellars | Yoshi Tannamuri | 1900 Oak St. | Vancouver | V3F 2K1 | Canada |
43 | Lazy K Kountry Store | John Steel | 12 Orchestra Terrace | Walla Walla | 99362 | USA |
44 | Lehmanns Marktstand | Renate Messner | Magazinweg 7 | Frankfurt a.M. | 60528 | Germany |
45 | Let's Stop N Shop | Jaime Yorres | 87 Polk St. Suite 5 | San Francisco | 94117 | USA |
46 | LILA-Supermercado | Carlos González | Carrera 52 con Ave. Bolívar #65-98 Llano Largo | Barquisimeto | 3508 | Venezuela |
47 | LINO-Delicateses | Felipe Izquierdo | Ave. 5 de Mayo Porlamar | I. de Margarita | 4980 | Venezuela |
48 | Lonesome Pine Restaurant | Fran Wilson | 89 Chiaroscuro Rd. | Portland | 97219 | USA |
49 | Magazzini Alimentari Riuniti | Giovanni Rovelli | Via Ludovico il Moro 22 | Bergamo | 24100 | Italy |
50 | Maison Dewey | Catherine Dewey | Rue Joseph-Bens 532 | Bruxelles | B-1180 | Belgium |
51 | Mère Paillarde | Jean Fresnière | 43 rue St. Laurent | Montréal | H1J 1C3 | Canada |
52 | Morgenstern Gesundkost | Alexander Feuer | Heerstr. 22 | Leipzig | 04179 | Germany |
53 | North/South | Simon Crowther | South House 300 Queensbridge | London | SW7 1RZ | UK |
54 | Océano Atlántico Ltda. | Yvonne Moncada | Ing. Gustavo Moncada 8585 Piso 20-A | Buenos Aires | 1010 | Argentina |
55 | Old World Delicatessen | Rene Phillips | 2743 Bering St. | Anchorage | 99508 | USA |
56 | Ottilies Käseladen | Henriette Pfalzheim | Mehrheimerstr. 369 | Köln | 50739 | Germany |
57 | Paris spécialités | Marie Bertrand | 265, boulevard Charonne | Paris | 75012 | France |
58 | Pericles Comidas clásicas | Guillermo Fernández | Calle Dr. Jorge Cash 321 | México D.F. | 05033 | Mexico |
59 | Piccolo und mehr | Georg Pipps | Geislweg 14 | Salzburg | 5020 | Austria |
60 | Princesa Isabel Vinhoss | Isabel de Castro | Estrada da saúde n. 58 | Lisboa | 1756 | Portugal |
61 | Que Delícia | Bernardo Batista | Rua da Panificadora, 12 | Rio de Janeiro | 02389-673 | Brazil |
62 | Queen Cozinha | Lúcia Carvalho | Alameda dos Canàrios, 891 | São Paulo | 05487-020 | Brazil |
63 | QUICK-Stop | Horst Kloss | Taucherstraße 10 | Cunewalde | 01307 | Germany |
64 | Rancho grande | Sergio Gutiérrez | Av. del Libertador 900 | Buenos Aires | 1010 | Argentina |
65 | Rattlesnake Canyon Grocery | Paula Wilson | 2817 Milton Dr. | Albuquerque | 87110 | USA |
66 | Reggiani Caseifici | Maurizio Moroni | Strada Provinciale 124 | Reggio Emilia | 42100 | Italy |
67 | Ricardo Adocicados | Janete Limeira | Av. Copacabana, 267 | Rio de Janeiro | 02389-890 | Brazil |
68 | Richter Supermarkt | Michael Holz | Grenzacherweg 237 | Genève | 1203 | Switzerland |
69 | Romero y tomillo | Alejandra Camino | Gran Vía, 1 | Madrid | 28001 | Spain |
70 | Santé Gourmet | Jonas Bergulfsen | Erling Skakkes gate 78 | Stavern | 4110 | Norway |
71 | Save-a-lot Markets | Jose Pavarotti | 187 Suffolk Ln. | Boise | 83720 | USA |
72 | Seven Seas Imports | Hari Kumar | 90 Wadhurst Rd. | London | OX15 4NB | UK |
73 | Simons bistro | Jytte Petersen | Vinbæltet 34 | København | 1734 | Denmark |
74 | Spécialités du monde | Dominique Perrier | 25, rue Lauriston | Paris | 75016 | France |
75 | Split Rail Beer & Ale | Art Braunschweiger | P.O. Box 555 | Lander | 82520 | USA |
76 | Suprêmes délices | Pascale Cartrain | Boulevard Tirou, 255 | Charleroi | B-6000 | Belgium |
77 | The Big Cheese | Liz Nixon | 89 Jefferson Way Suite 2 | Portland | 97201 | USA |
78 | The Cracker Box | Liu Wong | 55 Grizzly Peak Rd. | Butte | 59801 | USA |
79 | Toms Spezialitäten | Karin Josephs | Luisenstr. 48 | Münster | 44087 | Germany |
80 | Tortuga Restaurante | Miguel Angel Paolino | Avda. Azteca 123 | México D.F. | 05033 | Mexico |
81 | Tradição Hipermercados | Anabela Domingues | Av. Inês de Castro, 414 | São Paulo | 05634-030 | Brazil |
82 | Trail's Head Gourmet Provisioners | Helvetius Nagy | 722 DaVinci Blvd. | Kirkland | 98034 | USA |
83 | Vaffeljernet | Palle Ibsen | Smagsløget 45 | Århus | 8200 | Denmark |
84 | Victuailles en stock | Mary Saveley | 2, rue du Commerce | Lyon | 69004 | France |
85 | Vins et alcools Chevalier | Paul Henriot | 59 rue de l'Abbaye | Reims | 51100 | France |
86 | Die Wandernde Kuh | Rita Müller | Adenauerallee 900 | Stuttgart | 70563 | Germany |
87 | Wartian Herkku | Pirkko Koskitalo | Torikatu 38 | Oulu | 90110 | Finland |
88 | Wellington Importadora | Paula Parente | Rua do Mercado, 12 | Resende | 08737-363 | Brazil |
89 | White Clover Markets | Karl Jablonski | 305 - 14th Ave. S. Suite 3B | Seattle | 98128 | USA |
90 | Wilman Kala | Matti Karttunen | Keskuskatu 45 | Helsinki | 21240 | Finland |
91 | Wolski | Zbyszek | ul. Filtrowa 68 | Walla | 01-012 | Poland |
The following SQL statement selects all customers with a CustomerName starting with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
The following SQL statement selects all customers with a CustomerName ending with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
The following SQL statement selects all customers with a CustomerName that have "or" in any position:
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
The following SQL statement selects all customers with a CustomerName that have "r" in the second position:
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
The following SQL statement selects all customers with a CustomerName that starts with "a" and are at least 3 characters in length:
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
The following SQL statement selects all customers with a ContactName that starts with "a" and ends with "o":
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
The following SQL statement selects all customers with a CustomerName that does NOT start with "a":
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
A wildcard character is used to substitute one or more characters in a string.
Wildcard characters are used with the LIKE
operator. The LIKE
operator is used in a WHERE
clause to search for a specified pattern in a column.
Symbol | Description | Example |
---|---|---|
* | Represents zero or more characters | bl* finds bl, black, blue, and blob |
? | Represents a single character | h?t finds hot, hat, and hit |
[] | Represents any single character within the brackets | h[oa]t finds hot and hat, but not hit |
! | Represents any character not in the brackets | h[!oa]t finds hit, but not hot and hat |
- | Represents any single character within the specified range | c[a-b]t finds cat and cbt |
# | Represents any single numeric character | 2#5 finds 205, 215, 225, 235, 245, 255, 265, 275, 285, and 295 |
Symbol | Description | Example |
---|---|---|
% | Represents zero or more characters | bl% finds bl, black, blue, and blob |
_ | Represents a single character | h_t finds hot, hat, and hit |
[] | Represents any single character within the brackets | h[oa]t finds hot and hat, but not hit |
^ | Represents any character not in the brackets | h[^oa]t finds hit, but not hot and hat |
- | Represents any single character within the specified range | c[a-b]t finds cat and cbt |
All the wildcards can also be used in combinations!
Here are some examples showing different LIKE
operators with '%' and '_' wildcards:
LIKE Operator | Description |
---|---|
WHERE CustomerName LIKE 'a%' | Finds any values that starts with "a" |
WHERE CustomerName LIKE '%a' | Finds any values that ends with "a" |
WHERE CustomerName LIKE '%or%' | Finds any values that have "or" in any position |
WHERE CustomerName LIKE '_r%' | Finds any values that have "r" in the second position |
WHERE CustomerName LIKE 'a__%' | Finds any values that starts with "a" and are at least 3 characters in length |
WHERE ContactName LIKE 'a%o' | Finds any values that starts with "a" and ends with "o" |
The table below shows the complete "Customers" table from the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
6 | Blauer See Delikatessen | Hanna Moos | Forsterstr. 57 | Mannheim | 68306 | Germany |
7 | Blondel père et fils | Frédérique Citeaux | 24, place Kléber | Strasbourg | 67000 | France |
8 | Bólido Comidas preparadas | Martín Sommer | C/ Araquil, 67 | Madrid | 28023 | Spain |
9 | Bon app' | Laurence Lebihans | 12, rue des Bouchers | Marseille | 13008 | France |
10 | Bottom-Dollar Marketse | Elizabeth Lincoln | 23 Tsawassen Blvd. | Tsawassen | T2F 8M4 | Canada |
11 | B's Beverages | Victoria Ashworth | Fauntleroy Circus | London | EC2 5NT | UK |
12 | Cactus Comidas para llevar | Patricio Simpson | Cerrito 333 | Buenos Aires | 1010 | Argentina |
13 | Centro comercial Moctezuma | Francisco Chang | Sierras de Granada 9993 | México D.F. | 05022 | Mexico |
14 | Chop-suey Chinese | Yang Wang | Hauptstr. 29 | Bern | 3012 | Switzerland |
15 | Comércio Mineiro | Pedro Afonso | Av. dos Lusíadas, 23 | São Paulo | 05432-043 | Brazil |
16 | Consolidated Holdings | Elizabeth Brown | Berkeley Gardens 12 Brewery | London | WX1 6LT | UK |
17 | Drachenblut Delikatessend | Sven Ottlieb | Walserweg 21 | Aachen | 52066 | Germany |
18 | Du monde entier | Janine Labrune | 67, rue des Cinquante Otages | Nantes | 44000 | France |
19 | Eastern Connection | Ann Devon | 35 King George | London | WX3 6FW | UK |
20 | Ernst Handel | Roland Mendel | Kirchgasse 6 | Graz | 8010 | Austria |
21 | Familia Arquibaldo | Aria Cruz | Rua Orós, 92 | São Paulo | 05442-030 | Brazil |
22 | FISSA Fabrica Inter. Salchichas S.A. | Diego Roel | C/ Moralzarzal, 86 | Madrid | 28034 | Spain |
23 | Folies gourmandes | Martine Rancé | 184, chaussée de Tournai | Lille | 59000 | France |
24 | Folk och fä HB | Maria Larsson | Åkergatan 24 | Bräcke | S-844 67 | Sweden |
25 | Frankenversand | Peter Franken | Berliner Platz 43 | München | 80805 | Germany |
26 | France restauration | Carine Schmitt | 54, rue Royale | Nantes | 44000 | France |
27 | Franchi S.p.A. | Paolo Accorti | Via Monte Bianco 34 | Torino | 10100 | Italy |
28 | Furia Bacalhau e Frutos do Mar | Lino Rodriguez | Jardim das rosas n. 32 | Lisboa | 1675 | Portugal |
29 | Galería del gastrónomo | Eduardo Saavedra | Rambla de Cataluña, 23 | Barcelona | 08022 | Spain |
30 | Godos Cocina Típica | José Pedro Freyre | C/ Romero, 33 | Sevilla | 41101 | Spain |
31 | Gourmet Lanchonetes | André Fonseca | Av. Brasil, 442 | Campinas | 04876-786 | Brazil |
32 | Great Lakes Food Market | Howard Snyder | 2732 Baker Blvd. | Eugene | 97403 | USA |
33 | GROSELLA-Restaurante | Manuel Pereira | 5ª Ave. Los Palos Grandes | Caracas | 1081 | Venezuela |
34 | Hanari Carnes | Mario Pontes | Rua do Paço, 67 | Rio de Janeiro | 05454-876 | Brazil |
35 | HILARIÓN-Abastos | Carlos Hernández | Carrera 22 con Ave. Carlos Soublette #8-35 | San Cristóbal | 5022 | Venezuela |
36 | Hungry Coyote Import Store | Yoshi Latimer | City Center Plaza 516 Main St. | Elgin | 97827 | USA |
37 | Hungry Owl All-Night Grocers | Patricia McKenna | 8 Johnstown Road | Cork | Ireland | |
38 | Island Trading | Helen Bennett | Garden House Crowther Way | Cowes | PO31 7PJ | UK |
39 | Königlich Essen | Philip Cramer | Maubelstr. 90 | Brandenburg | 14776 | Germany |
40 | La corne d'abondance | Daniel Tonini | 67, avenue de l'Europe | Versailles | 78000 | France |
41 | La maison d'Asie | Annette Roulet | 1 rue Alsace-Lorraine | Toulouse | 31000 | France |
42 | Laughing Bacchus Wine Cellars | Yoshi Tannamuri | 1900 Oak St. | Vancouver | V3F 2K1 | Canada |
43 | Lazy K Kountry Store | John Steel | 12 Orchestra Terrace | Walla Walla | 99362 | USA |
44 | Lehmanns Marktstand | Renate Messner | Magazinweg 7 | Frankfurt a.M. | 60528 | Germany |
45 | Let's Stop N Shop | Jaime Yorres | 87 Polk St. Suite 5 | San Francisco | 94117 | USA |
46 | LILA-Supermercado | Carlos González | Carrera 52 con Ave. Bolívar #65-98 Llano Largo | Barquisimeto | 3508 | Venezuela |
47 | LINO-Delicateses | Felipe Izquierdo | Ave. 5 de Mayo Porlamar | I. de Margarita | 4980 | Venezuela |
48 | Lonesome Pine Restaurant | Fran Wilson | 89 Chiaroscuro Rd. | Portland | 97219 | USA |
49 | Magazzini Alimentari Riuniti | Giovanni Rovelli | Via Ludovico il Moro 22 | Bergamo | 24100 | Italy |
50 | Maison Dewey | Catherine Dewey | Rue Joseph-Bens 532 | Bruxelles | B-1180 | Belgium |
51 | Mère Paillarde | Jean Fresnière | 43 rue St. Laurent | Montréal | H1J 1C3 | Canada |
52 | Morgenstern Gesundkost | Alexander Feuer | Heerstr. 22 | Leipzig | 04179 | Germany |
53 | North/South | Simon Crowther | South House 300 Queensbridge | London | SW7 1RZ | UK |
54 | Océano Atlántico Ltda. | Yvonne Moncada | Ing. Gustavo Moncada 8585 Piso 20-A | Buenos Aires | 1010 | Argentina |
55 | Old World Delicatessen | Rene Phillips | 2743 Bering St. | Anchorage | 99508 | USA |
56 | Ottilies Käseladen | Henriette Pfalzheim | Mehrheimerstr. 369 | Köln | 50739 | Germany |
57 | Paris spécialités | Marie Bertrand | 265, boulevard Charonne | Paris | 75012 | France |
58 | Pericles Comidas clásicas | Guillermo Fernández | Calle Dr. Jorge Cash 321 | México D.F. | 05033 | Mexico |
59 | Piccolo und mehr | Georg Pipps | Geislweg 14 | Salzburg | 5020 | Austria |
60 | Princesa Isabel Vinhoss | Isabel de Castro | Estrada da saúde n. 58 | Lisboa | 1756 | Portugal |
61 | Que Delícia | Bernardo Batista | Rua da Panificadora, 12 | Rio de Janeiro | 02389-673 | Brazil |
62 | Queen Cozinha | Lúcia Carvalho | Alameda dos Canàrios, 891 | São Paulo | 05487-020 | Brazil |
63 | QUICK-Stop | Horst Kloss | Taucherstraße 10 | Cunewalde | 01307 | Germany |
64 | Rancho grande | Sergio Gutiérrez | Av. del Libertador 900 | Buenos Aires | 1010 | Argentina |
65 | Rattlesnake Canyon Grocery | Paula Wilson | 2817 Milton Dr. | Albuquerque | 87110 | USA |
66 | Reggiani Caseifici | Maurizio Moroni | Strada Provinciale 124 | Reggio Emilia | 42100 | Italy |
67 | Ricardo Adocicados | Janete Limeira | Av. Copacabana, 267 | Rio de Janeiro | 02389-890 | Brazil |
68 | Richter Supermarkt | Michael Holz | Grenzacherweg 237 | Genève | 1203 | Switzerland |
69 | Romero y tomillo | Alejandra Camino | Gran Vía, 1 | Madrid | 28001 | Spain |
70 | Santé Gourmet | Jonas Bergulfsen | Erling Skakkes gate 78 | Stavern | 4110 | Norway |
71 | Save-a-lot Markets | Jose Pavarotti | 187 Suffolk Ln. | Boise | 83720 | USA |
72 | Seven Seas Imports | Hari Kumar | 90 Wadhurst Rd. | London | OX15 4NB | UK |
73 | Simons bistro | Jytte Petersen | Vinbæltet 34 | København | 1734 | Denmark |
74 | Spécialités du monde | Dominique Perrier | 25, rue Lauriston | Paris | 75016 | France |
75 | Split Rail Beer & Ale | Art Braunschweiger | P.O. Box 555 | Lander | 82520 | USA |
76 | Suprêmes délices | Pascale Cartrain | Boulevard Tirou, 255 | Charleroi | B-6000 | Belgium |
77 | The Big Cheese | Liz Nixon | 89 Jefferson Way Suite 2 | Portland | 97201 | USA |
78 | The Cracker Box | Liu Wong | 55 Grizzly Peak Rd. | Butte | 59801 | USA |
79 | Toms Spezialitäten | Karin Josephs | Luisenstr. 48 | Münster | 44087 | Germany |
80 | Tortuga Restaurante | Miguel Angel Paolino | Avda. Azteca 123 | México D.F. | 05033 | Mexico |
81 | Tradição Hipermercados | Anabela Domingues | Av. Inês de Castro, 414 | São Paulo | 05634-030 | Brazil |
82 | Trail's Head Gourmet Provisioners | Helvetius Nagy | 722 DaVinci Blvd. | Kirkland | 98034 | USA |
83 | Vaffeljernet | Palle Ibsen | Smagsløget 45 | Århus | 8200 | Denmark |
84 | Victuailles en stock | Mary Saveley | 2, rue du Commerce | Lyon | 69004 | France |
85 | Vins et alcools Chevalier | Paul Henriot | 59 rue de l'Abbaye | Reims | 51100 | France |
86 | Die Wandernde Kuh | Rita Müller | Adenauerallee 900 | Stuttgart | 70563 | Germany |
87 | Wartian Herkku | Pirkko Koskitalo | Torikatu 38 | Oulu | 90110 | Finland |
88 | Wellington Importadora | Paula Parente | Rua do Mercado, 12 | Resende | 08737-363 | Brazil |
89 | White Clover Markets | Karl Jablonski | 305 - 14th Ave. S. Suite 3B | Seattle | 98128 | USA |
90 | Wilman Kala | Matti Karttunen | Keskuskatu 45 | Helsinki | 21240 | Finland |
91 | Wolski | Zbyszek | ul. Filtrowa 68 | Walla | 01-012 | Poland |
The following SQL statement selects all customers with a City starting with "ber":
SELECT * FROM Customers
WHERE City LIKE 'ber%';
The following SQL statement selects all customers with a City containing the pattern "es":
SELECT * FROM Customers
WHERE City LIKE '%es%';
The following SQL statement selects all customers with a City starting with any character, followed by "ondon":
SELECT * FROM Customers
WHERE City LIKE '_ondon';
The following SQL statement selects all customers with a City starting with "L", followed by any character, followed by "n", followed by any character, followed by "on":
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';
The following SQL statement selects all customers with a City starting with "b", "s", or "p":
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';
The following SQL statement selects all customers with a City starting with "a", "b", or "c":
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';
The two following SQL statements select all customers with a City NOT starting with "b", "s", or "p":
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';
Or:
SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';
The IN
operator allows you to specify multiple values in a WHERE
clause.
The IN
operator is a shorthand for multiple OR
conditions.
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
The table below shows the complete "Customers" table from the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
6 | Blauer See Delikatessen | Hanna Moos | Forsterstr. 57 | Mannheim | 68306 | Germany |
7 | Blondel père et fils | Frédérique Citeaux | 24, place Kléber | Strasbourg | 67000 | France |
8 | Bólido Comidas preparadas | Martín Sommer | C/ Araquil, 67 | Madrid | 28023 | Spain |
9 | Bon app' | Laurence Lebihans | 12, rue des Bouchers | Marseille | 13008 | France |
10 | Bottom-Dollar Marketse | Elizabeth Lincoln | 23 Tsawassen Blvd. | Tsawassen | T2F 8M4 | Canada |
11 | B's Beverages | Victoria Ashworth | Fauntleroy Circus | London | EC2 5NT | UK |
12 | Cactus Comidas para llevar | Patricio Simpson | Cerrito 333 | Buenos Aires | 1010 | Argentina |
13 | Centro comercial Moctezuma | Francisco Chang | Sierras de Granada 9993 | México D.F. | 05022 | Mexico |
14 | Chop-suey Chinese | Yang Wang | Hauptstr. 29 | Bern | 3012 | Switzerland |
15 | Comércio Mineiro | Pedro Afonso | Av. dos Lusíadas, 23 | São Paulo | 05432-043 | Brazil |
16 | Consolidated Holdings | Elizabeth Brown | Berkeley Gardens 12 Brewery | London | WX1 6LT | UK |
17 | Drachenblut Delikatessend | Sven Ottlieb | Walserweg 21 | Aachen | 52066 | Germany |
18 | Du monde entier | Janine Labrune | 67, rue des Cinquante Otages | Nantes | 44000 | France |
19 | Eastern Connection | Ann Devon | 35 King George | London | WX3 6FW | UK |
20 | Ernst Handel | Roland Mendel | Kirchgasse 6 | Graz | 8010 | Austria |
21 | Familia Arquibaldo | Aria Cruz | Rua Orós, 92 | São Paulo | 05442-030 | Brazil |
22 | FISSA Fabrica Inter. Salchichas S.A. | Diego Roel | C/ Moralzarzal, 86 | Madrid | 28034 | Spain |
23 | Folies gourmandes | Martine Rancé | 184, chaussée de Tournai | Lille | 59000 | France |
24 | Folk och fä HB | Maria Larsson | Åkergatan 24 | Bräcke | S-844 67 | Sweden |
25 | Frankenversand | Peter Franken | Berliner Platz 43 | München | 80805 | Germany |
26 | France restauration | Carine Schmitt | 54, rue Royale | Nantes | 44000 | France |
27 | Franchi S.p.A. | Paolo Accorti | Via Monte Bianco 34 | Torino | 10100 | Italy |
28 | Furia Bacalhau e Frutos do Mar | Lino Rodriguez | Jardim das rosas n. 32 | Lisboa | 1675 | Portugal |
29 | Galería del gastrónomo | Eduardo Saavedra | Rambla de Cataluña, 23 | Barcelona | 08022 | Spain |
30 | Godos Cocina Típica | José Pedro Freyre | C/ Romero, 33 | Sevilla | 41101 | Spain |
31 | Gourmet Lanchonetes | André Fonseca | Av. Brasil, 442 | Campinas | 04876-786 | Brazil |
32 | Great Lakes Food Market | Howard Snyder | 2732 Baker Blvd. | Eugene | 97403 | USA |
33 | GROSELLA-Restaurante | Manuel Pereira | 5ª Ave. Los Palos Grandes | Caracas | 1081 | Venezuela |
34 | Hanari Carnes | Mario Pontes | Rua do Paço, 67 | Rio de Janeiro | 05454-876 | Brazil |
35 | HILARIÓN-Abastos | Carlos Hernández | Carrera 22 con Ave. Carlos Soublette #8-35 | San Cristóbal | 5022 | Venezuela |
36 | Hungry Coyote Import Store | Yoshi Latimer | City Center Plaza 516 Main St. | Elgin | 97827 | USA |
37 | Hungry Owl All-Night Grocers | Patricia McKenna | 8 Johnstown Road | Cork | Ireland | |
38 | Island Trading | Helen Bennett | Garden House Crowther Way | Cowes | PO31 7PJ | UK |
39 | Königlich Essen | Philip Cramer | Maubelstr. 90 | Brandenburg | 14776 | Germany |
40 | La corne d'abondance | Daniel Tonini | 67, avenue de l'Europe | Versailles | 78000 | France |
41 | La maison d'Asie | Annette Roulet | 1 rue Alsace-Lorraine | Toulouse | 31000 | France |
42 | Laughing Bacchus Wine Cellars | Yoshi Tannamuri | 1900 Oak St. | Vancouver | V3F 2K1 | Canada |
43 | Lazy K Kountry Store | John Steel | 12 Orchestra Terrace | Walla Walla | 99362 | USA |
44 | Lehmanns Marktstand | Renate Messner | Magazinweg 7 | Frankfurt a.M. | 60528 | Germany |
45 | Let's Stop N Shop | Jaime Yorres | 87 Polk St. Suite 5 | San Francisco | 94117 | USA |
46 | LILA-Supermercado | Carlos González | Carrera 52 con Ave. Bolívar #65-98 Llano Largo | Barquisimeto | 3508 | Venezuela |
47 | LINO-Delicateses | Felipe Izquierdo | Ave. 5 de Mayo Porlamar | I. de Margarita | 4980 | Venezuela |
48 | Lonesome Pine Restaurant | Fran Wilson | 89 Chiaroscuro Rd. | Portland | 97219 | USA |
49 | Magazzini Alimentari Riuniti | Giovanni Rovelli | Via Ludovico il Moro 22 | Bergamo | 24100 | Italy |
50 | Maison Dewey | Catherine Dewey | Rue Joseph-Bens 532 | Bruxelles | B-1180 | Belgium |
51 | Mère Paillarde | Jean Fresnière | 43 rue St. Laurent | Montréal | H1J 1C3 | Canada |
52 | Morgenstern Gesundkost | Alexander Feuer | Heerstr. 22 | Leipzig | 04179 | Germany |
53 | North/South | Simon Crowther | South House 300 Queensbridge | London | SW7 1RZ | UK |
54 | Océano Atlántico Ltda. | Yvonne Moncada | Ing. Gustavo Moncada 8585 Piso 20-A | Buenos Aires | 1010 | Argentina |
55 | Old World Delicatessen | Rene Phillips | 2743 Bering St. | Anchorage | 99508 | USA |
56 | Ottilies Käseladen | Henriette Pfalzheim | Mehrheimerstr. 369 | Köln | 50739 | Germany |
57 | Paris spécialités | Marie Bertrand | 265, boulevard Charonne | Paris | 75012 | France |
58 | Pericles Comidas clásicas | Guillermo Fernández | Calle Dr. Jorge Cash 321 | México D.F. | 05033 | Mexico |
59 | Piccolo und mehr | Georg Pipps | Geislweg 14 | Salzburg | 5020 | Austria |
60 | Princesa Isabel Vinhoss | Isabel de Castro | Estrada da saúde n. 58 | Lisboa | 1756 | Portugal |
61 | Que Delícia | Bernardo Batista | Rua da Panificadora, 12 | Rio de Janeiro | 02389-673 | Brazil |
62 | Queen Cozinha | Lúcia Carvalho | Alameda dos Canàrios, 891 | São Paulo | 05487-020 | Brazil |
63 | QUICK-Stop | Horst Kloss | Taucherstraße 10 | Cunewalde | 01307 | Germany |
64 | Rancho grande | Sergio Gutiérrez | Av. del Libertador 900 | Buenos Aires | 1010 | Argentina |
65 | Rattlesnake Canyon Grocery | Paula Wilson | 2817 Milton Dr. | Albuquerque | 87110 | USA |
66 | Reggiani Caseifici | Maurizio Moroni | Strada Provinciale 124 | Reggio Emilia | 42100 | Italy |
67 | Ricardo Adocicados | Janete Limeira | Av. Copacabana, 267 | Rio de Janeiro | 02389-890 | Brazil |
68 | Richter Supermarkt | Michael Holz | Grenzacherweg 237 | Genève | 1203 | Switzerland |
69 | Romero y tomillo | Alejandra Camino | Gran Vía, 1 | Madrid | 28001 | Spain |
70 | Santé Gourmet | Jonas Bergulfsen | Erling Skakkes gate 78 | Stavern | 4110 | Norway |
71 | Save-a-lot Markets | Jose Pavarotti | 187 Suffolk Ln. | Boise | 83720 | USA |
72 | Seven Seas Imports | Hari Kumar | 90 Wadhurst Rd. | London | OX15 4NB | UK |
73 | Simons bistro | Jytte Petersen | Vinbæltet 34 | København | 1734 | Denmark |
74 | Spécialités du monde | Dominique Perrier | 25, rue Lauriston | Paris | 75016 | France |
75 | Split Rail Beer & Ale | Art Braunschweiger | P.O. Box 555 | Lander | 82520 | USA |
76 | Suprêmes délices | Pascale Cartrain | Boulevard Tirou, 255 | Charleroi | B-6000 | Belgium |
77 | The Big Cheese | Liz Nixon | 89 Jefferson Way Suite 2 | Portland | 97201 | USA |
78 | The Cracker Box | Liu Wong | 55 Grizzly Peak Rd. | Butte | 59801 | USA |
79 | Toms Spezialitäten | Karin Josephs | Luisenstr. 48 | Münster | 44087 | Germany |
80 | Tortuga Restaurante | Miguel Angel Paolino | Avda. Azteca 123 | México D.F. | 05033 | Mexico |
81 | Tradição Hipermercados | Anabela Domingues | Av. Inês de Castro, 414 | São Paulo | 05634-030 | Brazil |
82 | Trail's Head Gourmet Provisioners | Helvetius Nagy | 722 DaVinci Blvd. | Kirkland | 98034 | USA |
83 | Vaffeljernet | Palle Ibsen | Smagsløget 45 | Århus | 8200 | Denmark |
84 | Victuailles en stock | Mary Saveley | 2, rue du Commerce | Lyon | 69004 | France |
85 | Vins et alcools Chevalier | Paul Henriot | 59 rue de l'Abbaye | Reims | 51100 | France |
86 | Die Wandernde Kuh | Rita Müller | Adenauerallee 900 | Stuttgart | 70563 | Germany |
87 | Wartian Herkku | Pirkko Koskitalo | Torikatu 38 | Oulu | 90110 | Finland |
88 | Wellington Importadora | Paula Parente | Rua do Mercado, 12 | Resende | 08737-363 | Brazil |
89 | White Clover Markets | Karl Jablonski | 305 - 14th Ave. S. Suite 3B | Seattle | 98128 | USA |
90 | Wilman Kala | Matti Karttunen | Keskuskatu 45 | Helsinki | 21240 | Finland |
91 | Wolski | Zbyszek | ul. Filtrowa 68 | Walla | 01-012 | Poland |
The following SQL statement selects all customers that are located in "Germany", "France" or "UK":
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are from the same countries as the suppliers:
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
The BETWEEN
operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN
operator is inclusive: begin and end values are included.
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Below is a selection from the "Products" table in the Northwind sample database:
ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
---|---|---|---|---|---|
1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
2 | Chang | 1 | 1 | 24 - 12 oz bottles | 19 |
3 | Aniseed Syrup | 1 | 2 | 12 - 550 ml bottles | 10 |
4 | Chef Anton's Cajun Seasoning | 1 | 2 | 48 - 6 oz jars | 22 |
5 | Chef Anton's Gumbo Mix | 1 | 2 | 36 boxes | 21.35 |
The following SQL statement selects all products with a price between 10 and 20:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
To display the products outside the range of the previous example, use NOT BETWEEN
:
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
The following SQL statement selects all products with a price between 10 and 20. In addition; do not show products with a CategoryID of 1,2, or 3:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);
The following SQL statement selects all products with a ProductName between Carnarvon Tigers and Mozzarella di Giovanni:
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
The following SQL statement selects all products with a ProductName between Carnarvon Tigers and Chef Anton's Cajun Seasoning:
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun Seasoning"
ORDER BY ProductName;
The following SQL statement selects all products with a ProductName not between Carnarvon Tigers and Mozzarella di Giovanni:
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
Below is a selection from the "Orders" table in the Northwind sample database:
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 |
The following SQL statement selects all orders with an OrderDate between '01-July-1996' and '31-July-1996':
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;
OR:
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of that query.
An alias is created with the AS
keyword.
SELECT column_name AS alias_name
FROM table_name;
SELECT column_name(s)
FROM table_name AS alias_name;
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
And a selection from the "Orders" table:
OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
---|---|---|---|---|
10354 | 58 | 8 | 1996-11-14 | 3 |
10355 | 4 | 6 | 1996-11-15 | 1 |
10356 | 86 | 6 | 1996-11-18 | 2 |
The following SQL statement creates two aliases, one for the CustomerID column and one for the CustomerName column:
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
The following SQL statement creates two aliases, one for the CustomerName column and one for the ContactName column. Note: It requires double quotation marks or square brackets if the alias name contains spaces:
SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;
The following SQL statement creates an alias named "Address" that combine four columns (Address, PostalCode, City and Country):
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address
FROM Customers;
Note: To get the SQL statement above to work in MySQL use the following:
SELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,', ',Country) AS Address
FROM Customers;
Note: To get the SQL statement above to work in Oracle use the following:
SELECT CustomerName, (Address || ', ' || PostalCode || ' ' || City || ', ' || Country) AS Address
FROM Customers;
The following SQL statement selects all the orders from the customer with CustomerID=4 (Around the Horn). We use the "Customers" and "Orders" tables, and give them the table aliases of "c" and "o" respectively (Here we use aliases to make the SQL shorter):
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;
The following SQL statement is the same as above, but without aliases:
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the Horn' AND Customers.CustomerID=Orders.CustomerID;
Aliases can be useful when: