SQL Queries Notes
SQL Queries Notes
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 semicolons at the end of each SQL statement.
Page 1 of 45
MySQL SELECT Statement
The SELECT statement is used to select data from a database.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If
you want to select all the fields available in the table, use the following syntax:
Page 2 of 45
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
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;
Inside a table, a column often contains many duplicate values; and sometimes you only want
to list the different (distinct) values.
Page 3 of 45
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;
Page 4 of 45
MySQL WHERE Clause
The WHERE clause is used to filter records.
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:
Page 5 of 45
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Example
SELECT * FROM Customers
WHERE Country = 'Mexico';
Example
SELECT * FROM Customers
WHERE CustomerID = 1;
Operator Description
= Equal
Page 6 of 45
> Greater than
<> Not equal. Note: In some versions of SQL this operator may
be written as !=
Page 7 of 45
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.
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;
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
Page 8 of 45
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';
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
Page 9 of 45
SELECT * FROM Customers
WHERE NOT Country = 'Germany' AND NOT Country = 'USA';
Page 10 of 45
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;
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
Page 11 of 45
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
Page 12 of 45
MySQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
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:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('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.
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):
Page 13 of 45
Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
Page 14 of 45
MySQL NULL Values
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!
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;
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;
Page 15 of 45
Tip: Always use IS NULL to look for 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;
Page 16 of 45
MySQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax
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!
UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact
person and a new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
WHERE CustomerID = 1;
The following SQL statement will update the PostalCode to 00000 for all records where
country is "Mexico":
Example
UPDATE Customers
SET PostalCode = 00000
WHERE Country = 'Mexico';
Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!
Example
Page 17 of 45
UPDATE Customers
SET PostalCode = 00000;
The selection from the "Customers" table will now look like this:
Page 18 of 45
MySQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
DELETE Syntax
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!
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
The following SQL statement deletes all rows in the "Customers" table, without deleting the
table:
Example
DELETE FROM Customers;
Page 19 of 45
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 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 '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
Page 20 of 45
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends
with "o"
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__%';
Page 21 of 45
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%';
Page 22 of 45
MySQL Wildcards
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.
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
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
Page 23 of 45
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"
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';
Page 24 of 45
MySQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
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);
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);
Page 25 of 45
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;
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);
Page 26 of 45
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
Page 27 of 45
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';
Page 28 of 45
MySQL Joins
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID"
column.
Then, we can create the following SQL statement (that contains an INNER JOIN), that selects
records that have matching values in both tables.
Page 29 of 45
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
• LEFT JOIN: Returns all records from the left table, and the matched records from the
right table
• RIGHT JOIN: Returns all records from the right table, and the matched records from the
left table
• CROSS JOIN: Returns all records from both tables
Page 30 of 45
Page 31 of 45
MySQL INNER JOIN Keyword
The INNER JOIN keyword selects records that have matching values in both tables.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Page 32 of 45
CustomerID CustomerName ContactName Address City PostalCode Country
Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns. If there are records in the "Orders" table that do not have matches in
"Customers", these orders will not be shown!
Example
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
Page 33 of 45
MySQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all records from the left table (table1), and the matching
records (if any) from the right table (table2).
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Page 34 of 45
And a selection from the "Orders" table:
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
Note: The LEFT JOIN keyword returns all records from the left table (Customers), even if there
are no matches in the right table (Orders).
Page 35 of 45
MySQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all records from the right table (table2), and the matching
records (if any) from the left table (table1).
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Page 36 of 45
EmployeeID LastName FirstName BirthDate Photo
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
Note: The RIGHT JOIN keyword returns all records from the right table (Employees), even if
there are no matches in the left table (Orders).
Page 37 of 45
MySQL CROSS JOIN Keyword
The CROSS JOIN keyword returns all records from both tables (table1 and table2).
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Page 38 of 45
3 Antonio Moreno Antonio Mataderos México 05023 Mexico
Taquería Moreno 2312 D.F.
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
CROSS JOIN Orders;
Note: The CROSS JOIN keyword returns all matching records from both tables whether the
other table matches or not. So, if there are rows in "Customers" that do not have matches in
"Orders", or if there are rows in "Orders" that do not have matches in "Customers", those
rows will be listed as well.
If you add a WHERE clause (if table1 and table2 has a relationship), the CROSS JOIN will
produce the same result as the INNER JOIN clause:
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
CROSS JOIN Orders
WHERE Customers.CustomerID=Orders.CustomerID;
Page 39 of 45
MySQL Self Join
A self join is a regular join, but the table is joined with itself.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Example
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
Page 40 of 45
AND A.City = B.City
ORDER BY A.City;
Page 41 of 45
MySQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.
• Every SELECT statement within UNION must have the same number of columns
• The columns must also have similar data types
• The columns in every SELECT statement must also be in the same order
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Note: The column names in the result-set are usually equal to the column names in the
first SELECT statement.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Page 42 of 45
3 Antonio Moreno Antonio Mataderos México 05023 Mexico
Taquería Moreno 2312 D.F.
Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
Note: If some customers or suppliers have the same city, each city will only be listed once,
because UNION selects only distinct values. Use UNION ALL to also select duplicate values!
Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Page 44 of 45
Example
SELECT 'Customer' AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;
Notice the "AS Type" above - it is an alias. SQL Aliases are used to give a table or a column a
temporary name. An alias only exists for the duration of the query. So, here we have created
a temporary column named "Type", that list whether the contact person is a "Customer" or a
"Supplier".
Page 45 of 45