Mysql Select Notes
Mysql Select Notes
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.
SELECT Syntax
The general syntax of this statement to fetch data from tables are as follows:
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:
northwind.sql
Copy and run this sql script :
Examples:
Below is a selection from the "Customers" table in the Northwind sample database:
Example
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.
Example
SELECT Country FROM Customers;
Now, let us use the SELECT DISTINCT statement and see the result.
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;
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:
Example
SELECT * FROM Customers
WHERE Country = 'Mexico';
Example
SELECT * FROM Customers
WHERE CustomerID = 1;
Operator Description
= Equal
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.
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:
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';
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';
----
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:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
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;
Example
SELECT * FROM Customers
ORDER BY Country DESC;
Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
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!
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;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
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;
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:
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
Example
SELECT * FROM Customers
LIMIT 3;
The SQL query below says "return only 3 records, start on record 4 (OFFSET 3)":
Example
SELECT * FROM Customers
LIMIT 3 OFFSET 3;
Example
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;
---
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:
2 Chang 1 1 24 - 12 oz bottles 19
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;
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
ProductID ProductName SupplierID CategoryID Unit Price
2 Chang 1 1 24 - 12 oz bottles 19
COUNT() Example
The following SQL statement finds the number of products:
Example
SELECT COUNT(ProductID)
FROM Products;
AVG() Example
The following SQL statement finds the average price of all products:
Example
SELECT AVG(Price)
FROM Products;
Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample database:
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails"
table:
Example
SELECT SUM(Quantity)
FROM OrderDetails;
There are two wildcards often used in conjunction with the LIKE operator:
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:
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:
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%';
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.
% Represents zero or more characters bl% finds bl, black, blue, and blob
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
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:
51 Mère Paillarde Jean Fresnière 43 rue St. Montréal H1J 1C3 Canada
Laurent
75 Split Rail Beer Art P.O. Box 555 Lander 82520 USA
& Ale Braunschweig
er
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%';
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';
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:
51 Mère Paillarde Jean Fresnière 43 rue St. Montréal H1J 1C3 Canada
Laurent
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 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:
1 Chais 1 1 10 boxes x 20 18
bags
2 Chang 1 1 24 - 12 oz bottles 19
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;
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
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;
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:
10248 90 5 7/4/1996 3
10249 81 6 7/5/1996 1
10250 34 4 7/8/1996 2
10251 84 3 7/9/1996 1
10252 76 4 7/10/1996 2
Example
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.
10354 58 8 1996-11-14 3
10355 4 6 1996-11-15 1
10356 86 6 1996-11-18 2
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;
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;
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
first_name,
last_name,
job_id,
salary
from employeesdata
employee_id,
salary
from employeesdata
order by salary
limit 5;
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,
hire_date
from employeesdata
from employeesdata
group by year(hire_date)
order by 2 desc;
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
else
"high"
end as salary_level
from employeesdata
order by 1;
from employeesdata
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