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

SQL Queries Notes

SQL is used to interact with relational databases by inserting, searching, updating and deleting records. The SELECT statement is used to retrieve data from databases. Common SQL commands include SELECT, UPDATE, DELETE, INSERT and more. Operators like WHERE, AND, OR and NOT can filter records and the ORDER BY clause sorts the results.

Uploaded by

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

SQL Queries Notes

SQL is used to interact with relational databases by inserting, searching, updating and deleting records. The SELECT statement is used to retrieve data from databases. Common SQL commands include SELECT, UPDATE, DELETE, INSERT and more. Operators like WHERE, AND, OR and NOT can filter records and the ORDER BY clause sorts the results.

Uploaded by

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

What is SQL?

SQL is the standard language for dealing with Relational Databases.

SQL is used to insert, search, update, and delete database records.

How to Use SQL


The following SQL statement selects all the records in the "Customers" table:

SELECT * FROM Customers;

Keep in Mind That...


• SQL keywords are NOT case sensitive: select is the same as SELECT

In this tutorial we will write all SQL keywords in upper-case.

Semicolon after SQL Statements?


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 semicolons at the end of each SQL statement.

Some of The Most Important SQL Commands


• SELECT - extracts data from a database
• UPDATE - updates data in a database
• DELETE - deletes data from a database
• INSERT INTO - inserts new data into a database
• CREATE DATABASE - creates a new database
• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table
• CREATE INDEX - creates an index (search key)
• DROP INDEX - deletes an index

Page 1 of 45
MySQL SELECT Statement
The SELECT statement is used to select data from a database.

The data returned is stored in a result table, called the result-set.

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:

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 * FROM table_name;

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

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:

Page 3 of 45
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;

Page 4 of 45
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 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 2222 D.F.
helados

3 Antonio Moreno Antonio Mataderos 2312 México 05023 Mexico


Taquería Moreno D.F.

Page 5 of 45
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

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


Berglund

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

Page 6 of 45
> 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

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.

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;

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';

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

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;

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
Page 11 of 45
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;

Page 12 of 45
MySQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Syntax


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, ...);

INSERT INTO Example


The following SQL statement inserts a new record in the "Customers" table:

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.

Insert Data Only in Specified Columns


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):

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!

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;

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;

Page 15 of 45
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;

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;

UPDATE Multiple Records


It is the WHERE clause that determines how many records will be updated.

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:

Customer Customer Contact Address City Postal Country


ID Name Name Code

1 Alfreds Alfred Obere Str. Frankfurt 00000 Germany


Futterkiste Schmidt 57

2 Ana Ana Avda. de México 00000 Mexico


Trujillo Trujillo la D.F.
Empareda Constituci
dos y ón 2222
helados

3 Antonio Antonio Mataderos México 00000 Mexico


Moreno Moreno 2312 D.F.
Taquería

4 Around Thomas 120 London 00000 UK


the Horn Hardy Hanover
Sq.

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!

SQL DELETE Example


The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers"
table:

Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

Delete All Records


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:

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 (%) 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 '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"

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__%';

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.

Wildcard Characters in MySQL


Symbol Description Example

% Represents zero or more bl% finds bl, black, blue,


characters and blob

_ Represents a single h_t finds hot, hat, and hit


character

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

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"

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';

Page 24 of 45
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);

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;

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

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

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

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';

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.

Let's look at a selection from the "Orders" table:

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

Then, look at a selection from the "Customers" table:

CustomerID CustomerName ContactName Country

1 Alfreds Futterkiste Maria Anders Germany

2 Ana Trujillo Ana Trujillo Mexico


Emparedados y helados

3 Antonio Moreno Antonio Moreno Mexico


Taquería

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;

and it will produce something like this:

OrderID CustomerName OrderDate

10308 Ana Trujillo 9/18/1996


Emparedados y
helados

10365 Antonio Moreno 11/27/1996


Taquería

10383 Around the Horn 12/16/1996

10355 Around the Horn 11/15/1996

10278 Berglunds 8/12/1996


snabbköp

Supported Types of Joins in MySQL


• INNER JOIN: Returns records that have matching values in both tables

• 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.

INNER JOIN Syntax


SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

And a selection from the "Customers" table:

Page 32 of 45
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. Berlin 12209 Germany


Futterkiste 57

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.

MySQL INNER JOIN Example


The following SQL statement selects all orders with customer information:

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!

JOIN Three Tables


The following SQL statement selects all orders with customer and shipper information:

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).

LEFT JOIN Syntax


SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_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

1 Alfreds Maria Anders Obere Str. Berlin 12209 Germany


Futterkiste 57

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.

Page 34 of 45
And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

MySQL LEFT JOIN Example


The following SQL statement will select all customers, and any orders they might have:

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).

RIGHT JOIN Syntax


SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

And a selection from the "Employees" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

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

1 Davolio Nancy 12/8/1968 EmpID1.pic

2 Fuller Andrew 2/19/1952 EmpID2.pic

3 Leverling Janet 8/30/1963 EmpID3.pic

MySQL RIGHT JOIN Example


The following SQL statement will return all employees, and any orders they might have
placed:

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).

CROSS JOIN Syntax


SELECT column_name(s)
FROM table1
CROSS JOIN table2;

Note: CROSS JOIN can potentially return very large result-sets!

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

1 Alfreds Maria Anders Obere Str. Berlin 12209 Germany


Futterkiste 57

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


Emparedados y Constitución D.F.
helados 2222

Page 38 of 45
3 Antonio Moreno Antonio Mataderos México 05023 Mexico
Taquería Moreno 2312 D.F.

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

MySQL CROSS JOIN Example


The following SQL statement selects all customers, and all orders:

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.

Self Join Syntax


SELECT column_name(s)
FROM table1 , table1
WHERE condition;

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

1 Alfreds Maria Anders Obere Str. Berlin 12209 Germany


Futterkiste 57

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.

MySQL Self Join Example


The following SQL statement matches customers that are from the same city:

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;

UNION ALL Syntax


The UNION operator selects only distinct values by default. To allow duplicate values,
use UNION ALL:

SELECT column_name(s) FROM table1


UNION ALL
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.

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. Berlin 12209 Germany


Futterkiste 57

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


Emparedados y Constitución D.F.
helados 2222

Page 42 of 45
3 Antonio Moreno Antonio Mataderos México 05023 Mexico
Taquería Moreno 2312 D.F.

Below is a selection from the "Customers" table:

And a selection from the "Suppliers" table:

SupplierID Supplier Contact Address City Postal Code Country


Name Name

1 Exotic Charlotte 49 Gilbert St. London EC1 4SD UK


Liquid Cooper

2 New Orleans Shelley P.O. Box New Orleans 70117 USA


Cajun Burke 78934
Delights

3 Grandma Regina 707 Oxford Ann Arbor 48104 USA


Kelly's Murphy Rd.
Homestead

SQL UNION Example


The following SQL statement returns the cities (only distinct values) from both the
"Customers" and the "Suppliers" table:

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!

SQL UNION ALL Example


Page 43 of 45
The following SQL statement returns the cities (duplicate values also) from both the
"Customers" and the "Suppliers" table:

Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;

SQL UNION With WHERE


The following SQL statement returns the German cities (only distinct values) from both the
"Customers" and the "Suppliers" table:

Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

SQL UNION ALL With WHERE


The following SQL statement returns the German cities (duplicate values also) from both the
"Customers" and the "Suppliers" table:

Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

Another UNION Example


The following SQL statement lists all customers and suppliers:

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

You might also like