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

Mysql Select Notes

mysql notes

Uploaded by

jounpark7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Mysql Select Notes

mysql notes

Uploaded by

jounpark7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

MySQL SELECT Statement:

The SELECT statement in MySQL is used to fetch data from one or more tables. We can retrieve records of all fields or
specified fields that match specified criteria using this statement.

It is the most commonly used SQL query.

SELECT Syntax
The general syntax of this statement to fetch data from tables are as follows:

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;

Northwind database script :

northwind.sql
Copy and run this sql script :

Examples:

we will use the well-known Northwind sample database.

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

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

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


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.
4 Around the Thomas 120 Hanover London WA1 1DP UK
Horn Hardy Sq.

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


snabbköp Berglund 8

SELECT Columns Example


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

Example

SELECT CustomerName, City, Country FROM Customers;

SELECT * Example
The following SQL statement selects ALL the columns from the "Customers" table:

Example
SELECT * FROM Customers;
The MySQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct (different) values.

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

SELECT DISTINCT Syntax


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

SELECT Example Without DISTINCT


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

Example
SELECT Country FROM Customers;

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:

Example
SELECT DISTINCT Country FROM Customers;

The following SQL statement counts and returns the number of different (distinct)
countries in the "Customers" table:

Example
SELECT COUNT(DISTINCT Country) FROM Customers;

The MySQL WHERE Clause


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

WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: The WHERE clause is not only used in SELECT statements, it is also used
in UPDATE, DELETE, etc.!

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

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

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


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

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


snabbköp Berglund 8

WHERE Clause Example


The following SQL statement selects all the customers from "Mexico":

Example
SELECT * FROM Customers
WHERE Country = 'Mexico';

Text Fields vs. Numeric Fields


SQL requires single quotes around text values (most database systems will also allow
double quotes).

However, numeric fields should not be enclosed in quotes:

Example
SELECT * FROM Customers
WHERE CustomerID = 1;

Operators in The WHERE Clause


The following operators can be used in the WHERE clause:

Operator Description

= Equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal


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

BETWEEN Between a certain range

LIKE Search for a pattern

IN To specify multiple possible values for a column

The MySQL AND, OR and NOT Operators


The WHERE clause can be combined with AND, OR, and NOT operators.

The AND and OR operators are used to filter records based on more than one condition:

 The AND operator displays a record if all the conditions separated by AND are TRUE.
 The OR operator displays a record if any of the conditions separated by OR is TRUE.

The NOT operator displays a record if the condition(s) is NOT TRUE.

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

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

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

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

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

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


Emparedados y Constitución
helados 2222

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


Taquería Moreno 2312

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

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


snabbköp Berglund 8

6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany


Delikatessen

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


et fils Citeaux Kléber
AND Example
The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city is "Berlin":

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

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

Example
SELECT * FROM Customers
WHERE City = 'Berlin' OR City = 'Stuttgart';

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

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

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

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

Combining AND, OR and NOT


You can also combine the AND, OR and NOT operators.
The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city must be "Berlin" OR "Stuttgart" (use parenthesis to form complex
expressions):

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

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

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

Test Yourself With Exercises


Exercise:
Select all records where the City column has the value 'Berlin' and the PostalCode column has
the value 12209.

<blank> * FROM Customers


<blank> City = 'Berlin'
<blank> = 12209;

----

The MySQL ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.

ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

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

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


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos 2312 México 05023 Mexico


Taquería Moreno D.F.

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

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


snabbköp Berglund

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;

ORDER BY DESC Example


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

Example
SELECT * FROM Customers
ORDER BY Country DESC;

ORDER BY Several Columns Example


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

Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;

ORDER BY Several Columns Example 2


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

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

Test Yourself With Exercises


Exercise:
Select all records from the Customers table, sort the result alphabetically by the column City.

SELECT * FROM Customers


<blank> <blank>;
What is a NULL Value?
A field with a NULL value is a field with no value.

If a field in a table is optional, it is possible to insert a new record or update a record


without adding a value to this field. Then, the field will be saved with a NULL value.

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

How to Test for NULL Values?


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

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

IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;

IS NOT NULL Syntax


SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

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

CustomerID CustomerName ContactName Address City PostalCode Country

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


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

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

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

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


snabbköp Berglund 8

The IS NULL Operator


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

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

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

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

The IS NOT NULL Operator


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

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

Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
The MySQL LIMIT Clause
The LIMIT clause is used to specify the number of records to return.

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

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

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

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

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


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden
snabbköp Berglund 8

MySQL LIMIT Examples


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

Example
SELECT * FROM Customers
LIMIT 3;

What if we want to select records 4 - 6 (inclusive)?

MySQL provides a way to handle this: by using OFFSET.

The SQL query below says "return only 3 records, start on record 4 (OFFSET 3)":

Example
SELECT * FROM Customers
LIMIT 3 OFFSET 3;

ADD a WHERE CLAUSE


The following SQL statement selects the first three records from the "Customers" table,
where the country is "Germany":

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

---

MySQL MIN() and MAX() Functions


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

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

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

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

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 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

MIN() Example
The following SQL statement finds the price of the cheapest product:
Example
SELECT MIN(Price) AS SmallestPrice
FROM Products;

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

Example
SELECT MAX(Price) AS LargestPrice
FROM Products;

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


The COUNT() function returns the number of rows that matches a specified criterion.

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

The AVG() function returns the average value of a numeric column.

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

The SUM() function returns the total sum of a numeric column.

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

Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 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

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

Example
SELECT COUNT(ProductID)
FROM Products;

Note: NULL values are not counted.

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

Example
SELECT AVG(Price)
FROM Products;

Note: NULL values are ignored.

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

OrderDetailID OrderID ProductID Quantity

1 10248 11 12

2 10248 42 10

3 10248 72 5

4 10249 14 9

5 10249 51 40

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

Example
SELECT SUM(Quantity)
FROM OrderDetails;

Note: NULL values are ignored.


The MySQL LIKE Operator
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:

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


 The underscore sign (_) represents one, single character

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

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

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

LIKE Operator Description

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

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

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

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

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

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

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

CustomerID CustomerName City PostalCode Country

1 Alfreds Futterkiste Berlin 12209 Germany

2 Ana Trujillo México D.F. 05021 Mexico


Emparedados y
helados

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


Taquería

4 Around the Horn London WA1 1DP UK

5 Berglunds snabbköp Luleå S-958 22 Sweden

6 Blauer See Mannheim 68306 Germany


Delikatessen
7 Blondel père et fils Strasbourg 67000 France

8 Bólido Comidas Madrid 28023 Spain


preparadas

9 Bon app' Marseille 13008 France

10 Bottom-Dollar Tsawassen T2F 8M4 Canada


Marketse

11 B's Beverages London EC2 5NT UK

12 Cactus Comidas para Buenos Aires 1010 Argentina


llevar

13 Centro comercial México D.F. 05022 Mexico


Moctezuma

14 Chop-suey Chinese Bern 3012 Switzerland

15 Comércio Mineiro São Paulo 05432-043 Brazil

16 Consolidated London WX1 6LT UK


Holdings

17 Drachenblut Aachen 52066 Germany


Delikatessend

18 Du monde entier Nantes 44000 France


19 Eastern Connection London WX3 6FW UK

20 Ernst Handel Graz 8010 Austria

21 Familia Arquibaldo São Paulo 05442-030 Brazil

22 FISSA Fabrica Inter. Madrid 28034 Spain


Salchichas S.A.

23 Folies gourmandes Lille 59000 France

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

25 Frankenversand München 80805 Germany

26 France restauration Nantes 44000 France

27 Franchi S.p.A. Torino 10100 Italy

28 Furia Bacalhau e Lisboa 1675 Portugal


Frutos do Mar

29 Galería del Barcelona 08022 Spain


gastrónomo

30 Godos Cocina Típica Sevilla 41101 Spain

31 Gourmet Lanchonetes Campinas 04876-786 Brazil


32 Great Lakes Food Eugene 97403 USA
Market

33 GROSELLA- Caracas 1081 Venezuela


Restaurante

34 Hanari Carnes Rio de 05454-876 Brazil


Janeiro

35 HILARIÓN-Abastos San Cristóbal 5022 Venezuela

36 Hungry Coyote Elgin 97827 USA


Import Store

37 Hungry Owl All- Cork Ireland


Night Grocers

38 Island Trading Cowes PO31 7PJ UK

39 Königlich Essen Brandenburg 14776 Germany

40 La corne d'abondance Versailles 78000 France

41 La maison d'Asie Toulouse 31000 France

42 Laughing Bacchus Vancouver V3F 2K1 Canada


Wine Cellars

43 Lazy K Kountry Store Walla Walla 99362 USA


44 Lehmanns Marktstand Frankfurt 60528 Germany
a.M.

45 Let's Stop N Shop San 94117 USA


Francisco

46 LILA-Supermercado Barquisimeto 3508 Venezuela

47 LINO-Delicateses I. de 4980 Venezuela


Margarita

48 Lonesome Pine Portland 97219 USA


Restaurant

49 Magazzini Alimentari Bergamo 24100 Italy


Riuniti

50 Maison Dewey Bruxelles B-1180 Belgium

51 Mère Paillarde Montréal H1J 1C3 Canada

52 Morgenstern Leipzig 04179 Germany


Gesundkost

53 North/South London SW7 1RZ UK

54 Océano Atlántico Buenos Aires 1010 Argentina


Ltda.
55 Old World Anchorage 99508 USA
Delicatessen

56 Ottilies Käseladen Köln 50739 Germany

57 Paris spécialités Paris 75012 France

58 Pericles Comidas México D.F. 05033 Mexico


clásicas

59 Piccolo und mehr Salzburg 5020 Austria

60 Princesa Isabel Lisboa 1756 Portugal


Vinhoss

61 Que Delícia Rio de 02389-673 Brazil


Janeiro

62 Queen Cozinha São Paulo 05487-020 Brazil

63 QUICK-Stop Cunewalde 01307 Germany

64 Rancho grande Buenos Aires 1010 Argentina

65 Rattlesnake Canyon Albuquerque 87110 USA


Grocery

66 Reggiani Caseifici Reggio 42100 Italy


Emilia
67 Ricardo Adocicados Rio de 02389-890 Brazil
Janeiro

68 Richter Supermarkt Genève 1203 Switzerland

69 Romero y tomillo Madrid 28001 Spain

70 Santé Gourmet Stavern 4110 Norway

71 Save-a-lot Markets Boise 83720 USA

72 Seven Seas Imports London OX15 4NB UK

73 Simons bistro København 1734 Denmark

74 Spécialités du monde Paris 75016 France

75 Split Rail Beer & Ale Lander 82520 USA

76 Suprêmes délices Charleroi B-6000 Belgium

77 The Big Cheese Portland 97201 USA

78 The Cracker Box Butte 59801 USA

79 Toms Spezialitäten Münster 44087 Germany


80 Tortuga Restaurante México D.F. 05033 Mexico

81 Tradição São Paulo 05634-030 Brazil


Hipermercados

82 Trail's Head Gourmet Kirkland 98034 USA


Provisioners

83 Vaffeljernet Århus 8200 Denmark

84 Victuailles en stock Lyon 69004 France

85 Vins et alcools Reims 51100 France


Chevalier

86 Die Wandernde Kuh Stuttgart 70563 Germany

87 Wartian Herkku Oulu 90110 Finland

88 Wellington Resende 08737-363 Brazil


Importadora

89 White Clover Markets Seattle 98128 USA

90 Wilman Kala Helsinki 21240 Finland

91 Wolski Walla 01-012 Poland


SQL LIKE Examples
The following SQL statement selects all customers with a CustomerName starting with
"a":

Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';

The following SQL statement selects all customers with a CustomerName ending with "a":

Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';

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

Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';

The following SQL statement selects all customers with a CustomerName that have "r" in
the second position:

Example
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';

The following SQL statement selects all customers with a CustomerName that starts with
"a" and are at least 3 characters in length:

Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';

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

Example
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';

The following SQL statement selects all customers with a CustomerName that does NOT
start with "a":
Example
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';

MySQL Wildcard Characters


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.

Wildcard Characters in MySQL

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

The wildcards can also be used in combinations!

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

LIKE Operator Description

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

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

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

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

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

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

CustomerI CustomerNa ContactNam Address City PostalCo Country


D me e de

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

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


Emparedados Constitución D.F.
y helados 2222

3 Antonio Antonio Mataderos México 05023 Mexico


Moreno Moreno 2312 D.F.
Taquería

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.
5 Berglunds Christina Berguvsväge Luleå S-958 22 Sweden
snabbköp Berglund n8

6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany


Delikatessen

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


et fils Citeaux Kléber

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


Comidas Sommer 67
preparadas

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


Lebihans Bouchers

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


Marketse Lincoln Blvd.

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


Ashworth Circus

12 Cactus Patricio Cerrito 333 Buenos 1010 Argentina


Comidas para Simpson Aires
llevar

13 Centro Francisco Sierras de México 05022 Mexico


comercial Chang Granada 9993 D.F.
Moctezuma

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


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

16 Consolidated Elizabeth Berkeley London WX1 6LT UK


Holdings Brown Gardens 12
Brewery

17 Drachenblut Sven Ottlieb Walserweg Aachen 52066 Germany


Delikatessend 21

18 Du monde Janine 67, rue des Nantes 44000 France


entier Labrune Cinquante
Otages

19 Eastern Ann Devon 35 King London WX3 UK


Connection George 6FW

20 Ernst Handel Roland Kirchgasse 6 Graz 8010 Austria


Mendel

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


Arquibaldo

22 FISSA Fabrica Diego Roel C/ Madrid 28034 Spain


Inter. Moralzarzal,
Salchichas 86
S.A.

23 Folies Martine 184, chaussée Lille 59000 France


gourmandes Rancé de Tournai

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


HB
25 Frankenversan Peter Franken Berliner Platz München 80805 Germany
d 43

26 France Carine 54, rue Nantes 44000 France


restauration Schmitt Royale

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


Bianco 34

28 Furia Lino Jardim das Lisboa 1675 Portugal


Bacalhau e Rodriguez rosas n. 32
Frutos do Mar

29 Galería del Eduardo Rambla de Barcelona 08022 Spain


gastrónomo Saavedra Cataluña, 23

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


Típica Freyre 33

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


Lanchonetes Fonseca 442

32 Great Lakes Howard 2732 Baker Eugene 97403 USA


Food Market Snyder Blvd.

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


Restaurante Pereira Palos
Grandes

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


67 Janeiro
35 HILARIÓN- Carlos Carrera 22 San 5022 Venezuela
Abastos Hernández con Ave. Cristóbal
Carlos
Soublette #8-
35

36 Hungry Yoshi Latimer City Center Elgin 97827 USA


Coyote Import Plaza 516
Store Main St.

37 Hungry Owl Patricia 8 Johnstown Cork Ireland


All-Night McKenna Road
Grocers

38 Island Trading Helen Bennett Garden Cowes PO31 7PJ UK


House
Crowther
Way

39 Königlich Philip Cramer Maubelstr. 90 Brandenbur 14776 Germany


Essen g

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


d'abondance l'Europe

41 La maison Annette 1 rue Alsace- Toulouse 31000 France


d'Asie Roulet Lorraine

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


Bacchus Wine Tannamuri
Cellars

43 Lazy K John Steel 12 Orchestra Walla 99362 USA


Kountry Store Terrace Walla
44 Lehmanns Renate Magazinweg Frankfurt 60528 Germany
Marktstand Messner 7 a.M.

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


Shop Suite 5 Francisco

46 LILA- Carlos Carrera 52 Barquisime 3508 Venezuela


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

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


Delicateses Izquierdo Mayo Margarita
Porlamar

48 Lonesome Fran Wilson 89 Portland 97219 USA


Pine Chiaroscuro
Restaurant Rd.

49 Magazzini Giovanni Via Ludovico Bergamo 24100 Italy


Alimentari Rovelli il Moro 22
Riuniti

50 Maison Catherine Rue Joseph- Bruxelles B-1180 Belgium


Dewey Dewey Bens 532

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

52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 Germany


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

54 Océano Yvonne Ing. Gustavo Buenos 1010 Argentina


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

55 Old World Rene Phillips 2743 Bering Anchorage 99508 USA


Delicatessen St.

56 Ottilies Henriette Mehrheimerst Köln 50739 Germany


Käseladen Pfalzheim r. 369

57 Paris Marie 265, Paris 75012 France


spécialités Bertrand boulevard
Charonne

58 Pericles Guillermo Calle Dr. México 05033 Mexico


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

59 Piccolo und Georg Pipps Geislweg 14 Salzburg 5020 Austria


mehr

60 Princesa Isabel Isabel de Estrada da Lisboa 1756 Portugal


Vinhoss Castro saúde n. 58

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


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

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


10

64 Rancho grande Sergio Av. del Buenos 1010 Argentina


Gutiérrez Libertador Aires
900

65 Rattlesnake Paula Wilson 2817 Milton Albuquerqu 87110 USA


Canyon Dr. e
Grocery

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

67 Ricardo Janete Av. Rio de 02389-890 Brazil


Adocicados Limeira Copacabana, Janeiro
267

68 Richter Michael Holz Grenzacherw Genève 1203 Switzerlan


Supermarkt eg 237 d

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


tomillo Camino

70 Santé Gourmet Jonas Erling Stavern 4110 Norway


Bergulfsen Skakkes gate
78

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


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

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

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


monde Perrier Lauriston

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

76 Suprêmes Pascale Boulevard Charleroi B-6000 Belgium


délices Cartrain Tirou, 255

77 The Big Liz Nixon 89 Jefferson Portland 97201 USA


Cheese Way Suite 2

78 The Cracker Liu Wong 55 Grizzly Butte 59801 USA


Box Peak Rd.

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


Spezialitäten

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


Restaurante Paolino 123 D.F.

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


Hipermercado Domingues Castro, 414
s
82 Trail's Head Helvetius 722 DaVinci Kirkland 98034 USA
Gourmet Nagy Blvd.
Provisioners

83 Vaffeljernet Palle Ibsen Smagsløget Århus 8200 Denmark


45

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


stock Commerce

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


Chevalier l'Abbaye

86 Die Rita Müller Adenaueralle Stuttgart 70563 Germany


Wandernde e 900
Kuh

87 Wartian Pirkko Torikatu 38 Oulu 90110 Finland


Herkku Koskitalo

88 Wellington Paula Parente Rua do Resende 08737-363 Brazil


Importadora Mercado, 12

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


Markets Ave. S. Suite
3B

90 Wilman Kala Matti Keskuskatu Helsinki 21240 Finland


Karttunen 45

91 Wolski Zbyszek ul. Filtrowa Walla 01-012 Poland


68
Using the % Wildcard
The following SQL statement selects all customers with a City starting with "ber":

Example
SELECT * FROM Customers
WHERE City LIKE 'ber%';

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

Example
SELECT * FROM Customers
WHERE City LIKE '%es%';

Using the _ Wildcard


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

Example
SELECT * FROM Customers
WHERE City LIKE '_ondon';

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

Example
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';

The MySQL IN Operator


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

The IN operator is a shorthand for multiple OR conditions.

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

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

CustomerI CustomerNa ContactNam Address City PostalCo Country


D me e de

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

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


Emparedados Constitución D.F.
y helados 2222

3 Antonio Antonio Mataderos México 05023 Mexico


Moreno Moreno 2312 D.F.
Taquería

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

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


snabbköp Berglund n8
6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
Delikatessen

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


et fils Citeaux Kléber

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


Comidas Sommer 67
preparadas

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


Lebihans Bouchers

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


Marketse Lincoln Blvd.

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


Ashworth Circus

12 Cactus Patricio Cerrito 333 Buenos 1010 Argentina


Comidas para Simpson Aires
llevar

13 Centro Francisco Sierras de México 05022 Mexico


comercial Chang Granada 9993 D.F.
Moctezuma

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


Chinese d

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


Mineiro Lusíadas, 23
16 Consolidated Elizabeth Berkeley London WX1 6LT UK
Holdings Brown Gardens 12
Brewery

17 Drachenblut Sven Ottlieb Walserweg Aachen 52066 Germany


Delikatessend 21

18 Du monde Janine 67, rue des Nantes 44000 France


entier Labrune Cinquante
Otages

19 Eastern Ann Devon 35 King London WX3 UK


Connection George 6FW

20 Ernst Handel Roland Kirchgasse 6 Graz 8010 Austria


Mendel

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


Arquibaldo

22 FISSA Fabrica Diego Roel C/ Madrid 28034 Spain


Inter. Moralzarzal,
Salchichas 86
S.A.

23 Folies Martine 184, chaussée Lille 59000 France


gourmandes Rancé de Tournai

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


HB

25 Frankenversan Peter Franken Berliner Platz München 80805 Germany


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

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


Bianco 34

28 Furia Lino Jardim das Lisboa 1675 Portugal


Bacalhau e Rodriguez rosas n. 32
Frutos do Mar

29 Galería del Eduardo Rambla de Barcelona 08022 Spain


gastrónomo Saavedra Cataluña, 23

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


Típica Freyre 33

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


Lanchonetes Fonseca 442

32 Great Lakes Howard 2732 Baker Eugene 97403 USA


Food Market Snyder Blvd.

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


Restaurante Pereira Palos
Grandes

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


67 Janeiro

35 HILARIÓN- Carlos Carrera 22 San 5022 Venezuela


Abastos Hernández con Ave. Cristóbal
Carlos
Soublette #8-
35
36 Hungry Yoshi Latimer City Center Elgin 97827 USA
Coyote Import Plaza 516
Store Main St.

37 Hungry Owl Patricia 8 Johnstown Cork Ireland


All-Night McKenna Road
Grocers

38 Island Trading Helen Bennett Garden Cowes PO31 7PJ UK


House
Crowther
Way

39 Königlich Philip Cramer Maubelstr. 90 Brandenbur 14776 Germany


Essen g

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


d'abondance l'Europe

41 La maison Annette 1 rue Alsace- Toulouse 31000 France


d'Asie Roulet Lorraine

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


Bacchus Wine Tannamuri
Cellars

43 Lazy K John Steel 12 Orchestra Walla 99362 USA


Kountry Store Terrace Walla

44 Lehmanns Renate Magazinweg Frankfurt 60528 Germany


Marktstand Messner 7 a.M.

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


Shop Suite 5 Francisco
46 LILA- Carlos Carrera 52 Barquisime 3508 Venezuela
Supermercado González con Ave. to
Bolívar #65-
98 Llano
Largo

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


Delicateses Izquierdo Mayo Margarita
Porlamar

48 Lonesome Fran Wilson 89 Portland 97219 USA


Pine Chiaroscuro
Restaurant Rd.

49 Magazzini Giovanni Via Ludovico Bergamo 24100 Italy


Alimentari Rovelli il Moro 22
Riuniti

50 Maison Catherine Rue Joseph- Bruxelles B-1180 Belgium


Dewey Dewey Bens 532

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

52 Morgenstern Alexander Heerstr. 22 Leipzig 04179 Germany


Gesundkost Feuer

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


Crowther 300
Queensbridge

54 Océano Yvonne Ing. Gustavo Buenos 1010 Argentina


Atlántico Ltda. Moncada Moncada Aires
8585 Piso 20-
A
55 Old World Rene Phillips 2743 Bering Anchorage 99508 USA
Delicatessen St.

56 Ottilies Henriette Mehrheimerst Köln 50739 Germany


Käseladen Pfalzheim r. 369

57 Paris Marie 265, Paris 75012 France


spécialités Bertrand boulevard
Charonne

58 Pericles Guillermo Calle Dr. México 05033 Mexico


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

59 Piccolo und Georg Pipps Geislweg 14 Salzburg 5020 Austria


mehr

60 Princesa Isabel Isabel de Estrada da Lisboa 1756 Portugal


Vinhoss Castro saúde n. 58

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


Batista Panificadora, Janeiro
12

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


Cozinha Carvalho Canàrios, 891

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


10

64 Rancho grande Sergio Av. del Buenos 1010 Argentina


Gutiérrez Libertador Aires
900
65 Rattlesnake Paula Wilson 2817 Milton Albuquerqu 87110 USA
Canyon Dr. e
Grocery

66 Reggiani Maurizio Strada Reggio 42100 Italy


Caseifici Moroni Provinciale Emilia
124

67 Ricardo Janete Av. Rio de 02389-890 Brazil


Adocicados Limeira Copacabana, Janeiro
267

68 Richter Michael Holz Grenzacherw Genève 1203 Switzerlan


Supermarkt eg 237 d

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


tomillo Camino

70 Santé Gourmet Jonas Erling Stavern 4110 Norway


Bergulfsen Skakkes gate
78

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


Markets Ln.

72 Seven Seas Hari Kumar 90 Wadhurst London OX15 UK


Imports Rd. 4NB

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

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


monde Perrier Lauriston
75 Split Rail Beer Art P.O. Box 555 Lander 82520 USA
& Ale Braunschweig
er

76 Suprêmes Pascale Boulevard Charleroi B-6000 Belgium


délices Cartrain Tirou, 255

77 The Big Liz Nixon 89 Jefferson Portland 97201 USA


Cheese Way Suite 2

78 The Cracker Liu Wong 55 Grizzly Butte 59801 USA


Box Peak Rd.

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


Spezialitäten

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


Restaurante Paolino 123 D.F.

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


Hipermercado Domingues Castro, 414
s

82 Trail's Head Helvetius 722 DaVinci Kirkland 98034 USA


Gourmet Nagy Blvd.
Provisioners

83 Vaffeljernet Palle Ibsen Smagsløget Århus 8200 Denmark


45

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


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

86 Die Rita Müller Adenaueralle Stuttgart 70563 Germany


Wandernde e 900
Kuh

87 Wartian Pirkko Torikatu 38 Oulu 90110 Finland


Herkku Koskitalo

88 Wellington Paula Parente Rua do Resende 08737-363 Brazil


Importadora Mercado, 12

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


Markets Ave. S. Suite
3B

90 Wilman Kala Matti Keskuskatu Helsinki 21240 Finland


Karttunen 45

91 Wolski Zbyszek ul. Filtrowa Walla 01-012 Poland


68

IN Operator Examples
The following SQL statement selects all customers that are located in "Germany",
"France" or "UK":

Example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');

The following SQL statement selects all customers that are NOT located in "Germany",
"France" or "UK":
Example
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');

The following SQL statement selects all customers that are from the same countries as
the suppliers:

Example
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);

The MySQL BETWEEN Operator


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

The BETWEEN operator is inclusive: begin and end values are included.

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

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

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 18
bags

2 Chang 1 1 24 - 12 oz bottles 19

3 Aniseed Syrup 1 2 12 - 550 ml bottles 10


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

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

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

Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

NOT BETWEEN Example


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

Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

BETWEEN with IN Example


The following SQL statement selects all products with a price between 10 and 20. In
addition; do not show products with a CategoryID of 1,2, or 3:

Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);
BETWEEN Text Values Example
The following SQL statement selects all products with a ProductName between
"Carnarvon Tigers" and "Mozzarella di Giovanni":

Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

The following SQL statement selects all products with a ProductName between
"Carnarvon Tigers" and "Chef Anton's Cajun Seasoning":

Example
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun Seasoning"
ORDER BY ProductName;

NOT BETWEEN Text Values Example


The following SQL statement selects all products with a ProductName not between
"Carnarvon Tigers" and "Mozzarella di Giovanni":

Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

Sample Table
Below is a selection from the "Orders" table in the Northwind sample database:

OrderID CustomerID EmployeeID OrderDate ShipperID

10248 90 5 7/4/1996 3
10249 81 6 7/5/1996 1

10250 34 4 7/8/1996 2

10251 84 3 7/9/1996 1

10252 76 4 7/10/1996 2

BETWEEN Dates Example


The following SQL statement selects all orders with an OrderDate between '01-July-1996'
and '31-July-1996':

Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';

MySQL Aliases
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.

Alias Column Syntax


SELECT column_name AS alias_name
FROM table_name;

Alias Table Syntax


SELECT column_name(s)
FROM table_name AS alias_name;
Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode Country

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


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

4 Around the Thomas 120 London WA1 1DP UK


Horn Hardy Hanover Sq.

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10354 58 8 1996-11-14 3

10355 4 6 1996-11-15 1

10356 86 6 1996-11-18 2

Alias for Columns Examples


The following SQL statement creates two aliases, one for the CustomerID column and one
for the CustomerName column:

Example
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;

The following SQL statement creates two aliases, one for the CustomerName column and
one for the ContactName column. Note: Single or double quotation marks are required if
the alias name contains spaces:

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

The following SQL statement creates an alias named "Address" that combine four
columns (Address, PostalCode, City and Country):

Example
SELECT CustomerName, CONCAT_WS(', ', Address, PostalCode, City,
Country) AS Address
FROM Customers;

Alias for Tables Example


The following SQL statement selects all the orders from the customer with CustomerID=4
(Around the Horn). We use the "Customers" and "Orders" tables, and give them the table
aliases of "c" and "o" respectively (Here we use aliases to make the SQL shorter):

Example
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;

The following SQL statement is the same as above, but without aliases:

Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the
Horn' AND Customers.CustomerID=Orders.CustomerID;

Aliases can be useful when:

 There are more than one table involved in a query


 Functions are used in the query
 Column names are big or not very readable
 Two or more columns are combined together

Solve SQL Exercises

Database script :

exercise1.sql

1. Select employeesdata first name, last name, job_id and salary whose first
name starts with alphabet S
select first_name,

last_name,

job_id,

salary

from employeesdata

where upper(first_name) like 'S%';

2. Write a query to select employee with the highest salary


select employee_id,

first_name,

last_name,

job_id,

salary

from employeesdata

where salary = (select max(salary) from employeesdata);

3. Write a SQL query to display the 5 least earning employeesdata


select
first_name, last_name,

employee_id,

salary

from employeesdata

order by salary

limit 5;

4. Find the employeesdata hired in the 80s


select employee_id,
concat(first_name,' ' , last_name) employee,
hire_date
from employeesdata
where year(hire_date) between 1980 and 1989;

18. Display the employeesdata first name and the name in reverse order
select lower(first_name) name,

lower(reverse(first_name)) name_in_reverse

from employeesdata;

5. Find the employeesdata who joined the company after 15th of the month
select employee_id,

concat(first_name, ' ' , last_name) employee,

hire_date

from employeesdata

where day(hire_date)> 15;

6. Get the count of employeesdata hired year wise


select year(hire_date) hired_year, count(*) employeesdata_hired_count

from employeesdata

group by year(hire_date)
order by 2 desc;

9. Find the salary range of employeesdata


select min(salary) min_sal,

max(salary) max_sal,

round(avg(salary)) avg_sal

from employeesdata;

10. Write a query to divide people into three groups based on their salaries
select concat(first_name,' ',last_name) employee,

salary,

case

when salary >=2000 and salary < 5000 then "low"

when salary >=5000 and salary < 10000 then "mid"

else

"high"

end as salary_level

from employeesdata

order by 1;

11. Select the employeesdata whose first_name contains “an”


select (first_name)

from employeesdata

where lower(first_name) like '%an%';

12. Select employee first name and the corresponding phone number in the
format (_ _ _)-(_ _ _)-(_ _ _ _)
select concat(first_name, ' ', last_name) employee,

replace(phone_number,'.','-') phone_number

from employeesdata;
13. Find the employeesdata who joined in August, 1994.
select concat(first_name, ' ', last_name) employee,

hire_date

from employeesdata

where year(hire_date) = '1994'

and month(hire_date) = '08';

You might also like