MySQL-Full Notes
MySQL-Full Notes
• A database is an organized collection of data stored in a computer system and usually controlled
by a database management system (DBMS).
• Structured query language (SQL) is commonly used for data querying and writing.
• The Database is an essential part of our life. We encounter several activities that involve our
interaction with databases, for example in the bank, in the railway station, in school, in a grocery
store, etc.
• These are the instances where we need to store a large amount of data in one place and fetch
these data easily.
There are many databases available like MySQL, Sybase, Oracle, MongoDB, Informix,
PostgreSQL, SQL Server, etc.
SQL or Structured Query Language is used to operate on the data stored in a database.
Controls redundancy
It stores all the data in a single database file, so it can control data redundancy (when the same data
is stored in multiple tables. This can happen intentionally for data backup, faster access, or easier
updates).
Data Sharing
Backup
It provides a backup and recovery subsystem. This recovery system creates automatic data from
system failure and restores data if required.
It provides a different type of user interfaces like GUI, and application interfaces.
Size
1|Page
It occupies large disk space and large memory to run efficiently.
Cost
DBMS requires a high-speed data processor and larger memory to run DBMS software, so it is costly.
Complexity
There are various types of databases used for storing different varieties of data:
The word RDBMS is termed as 'Relational Database Management System.' It is represented as a table
that contains rows and columns.
• Table
• Record/ Tuple
• Field/Column name /Attribute
• Instance
• Schema
• Keys
An RDBMS is a tabular DBMS that maintains the security, integrity, accuracy, and consistency of the
data.
2|Page
Following are the various terminologies of RDBMS:
4) DBMS uses a file system to store in RDBMS, data values are stored in the
data, so there will be no relation form of tables, so
between the tables. a relationship between these data
values will be stored in the form of a
table as well.
3|Page
2.1 MySQL Introduction
• MySQL is cross platform which means it runs on a number of different platforms such as
Windows, Linux, and Mac OS etc.
• Literals
• Data types
• Nulls
• Comments
2.2.1 Literals
• It means the fixed value or constant value. It may be of character, numeric or date time type.
• Character and date/time literals are always in single quotation marks whereas numeric
we want to store value as Tom’s Cat then it should be written as Tom\’s Cat.
• Means the type of value and type of operation we can perform on data. For example on
numeric value we can store numbers and perform all arithmetic operations and so on.
• MySQL support three categories of data types:
o Numeric
o Date and time
o String types
4|Page
Numeric Data Types:
FLOAT(M,D) Real numbers i.e. number with decimal. M specify length of numeric value
including decimal place D and decimal symbol. For example if it is given as
FLOAT(8,2) then 5 integer value 1 decimal symbol and 2 digit after decimal TOTAL
– 8. it can work on 24 digits after decimal.
DOUBLE(M,D) Real numbers with more precision up to 53 place after decimal.
DECIMAL It is used to store exact numeric value that preserve exact precision for e.g.
money data in accounting system.
DECIMAL(P,D) means P no. of significant digits (1-65), D represent no. of digit after
decimal(0-30), for e.g DECIMAL(6,2) means 4 digit before decimal and 2 digit after
decimal. Max will be 9999.99
DATETIME Combination of date and time. For example to store 4th December 2018 and time is afternoon
3:30 then it should be written as – 2018-12-04 15:30:00
TIMESTAMP Similar to DATATIME but it is written without hyphen for example the above date time is stored as
20181204153000
YEAR(M) To store only year part of data where M may be 2 or 4 i.e. year in 2
5|Page
String Types:
CHAR(M) Fixed length string between 1 and 255. it always occupy M size for each data for example if
size is CHAR(20) and we store value ‘MOBILE’ , although the size of MOBILE is 6 but in a table
it will occupy 20 size with space padded at right side for remaining place.
Mostly use in the case where the data to be insert is of fixed size like Grade (A,B,C,..) or
Employee code as E001, E002, etc. In this case CHAR will give better performance than
varchar
VARCHAR(M) Variable length string between 1 and 65535 (from MySQL 5.0.3) , earlier it was
255. it takes size as per the data entered for example with VARCHAR(20) if the data entered is
MOBILE then it will take only 6 byte. It is useful for the data like name, address where the number
of character to be enter is not fixed.
VARCHAR2 It is supported in ORACLE, both are almost same with minor difference. The difference is in the
way they are handling Empty String and NULL, for VARCHAR these two are different where as
VARCHAR2 treats both same.
Difference between CHAR & VARCHAR
CHAR VARCHAR
Fast, no memory allocation every time Slow, as it take size according to data so
every time memory allocation is done
It takes more memory It takes less space
2.2.3 Comments
It is a text that is not executed, only for documentation purpose. Comments in MySQL can be
written as
For example,
Commands Description
Keywords That have special meaning in SQL. They are the commands in MySQL
6|Page
Clause They are used to support MySQL commands like FROM, WHERE etc.
Arguments Values passed to clause like table name to FROM clause conditions to WHERE clause
for e.g.
SELECT is keyword
Data Definition Language actually consists of the SQL commands that can be used to define the
database schema. Following are the commands that fall under DDL category: -
• CREATE TABLE
• DROP TABLE
• ALTER TABLE
• TRUNCATE
• RENAME
• COMMENT
The SQL commands that deal with the manipulation of data are DML Commands. The following
commands fall under the DML Commands category:-
• SELECT
• INSERT
• UPDATE
• DELETE
• MERGE
• CALL
7|Page
DCL is the short name of Data Control Language mostly concerned with rights, permissions, and
other controls of the database system. The following commands fall under the DML Commands
category:-.
• GRANT
• REVOKE
TCL is the short name of Transaction Control Language which deals with a transaction within a
database. The following commands fall under the DML Commands category:-.
• COMMIT
• ROLLBACK
• SAVEPOINT
• SET TRANSACTION
8|Page
4.1 MySQL Constraints
The constraint in MySQL is used to specify the rule that allows or restricts what values/data will be
stored in the table. They provide a suitable method to ensure data accuracy and integrity inside the
table. It also helps to limit the type of data that will be inserted inside the table. If any interruption
occurs between the constraint and data action, the action is failed.
Column Level Constraints: These constraints are applied only to the single column that limits the
type of particular column data.
Table Level Constraints: These constraints are applied to the entire table that limits the type of
data for the whole table.
We can define the constraints during a table created by using the CREATE TABLE statement. MySQL
also uses the ALTER TABLE statement to specify the constraints in the case of the existing table
schema.
Syntax:
.........
);
• NOT NULL
• CHECK
• DEFAULT
• PRIMARY KEY
• AUTO_INCREMENT
• UNIQUE
• INDEX
• ENUM
• FOREIGN KEY
9|Page
4.1.2.1. NOT NULL Constraint
This constraint specifies that the column cannot have NULL or empty values. The below statement
creates a table with NOT NULL constraint.
Output
This constraint ensures that all values inserted into the column will be unique. It means a column
cannot stores duplicate values. MySQL allows us to use more than one column with UNIQUE
constraint in a table.
1. mysql> CREATE TABLE ShirtBrands(Id INT, BrandName VARCHAR(40) UNIQUE, Size VAR
CHAR(30));
1. mysql> INSERT INTO ShirtBrands(Id, BrandName, Size) VALUES(1, 'Pantaloons', 38), (2, 'Ca
ntabil', 40);
2.
3. mysql> INSERT INTO ShirtBrands(Id, BrandName, Size) VALUES(1, 'Raymond', 38), (2, 'Cant
abil', 40);
Output
In the below output, we can see that the first INSERT query executes correctly, but the second
statement fails and gives an error that says: Duplicate entry 'Cantabil' for key BrandName.
10 | P a g e
4.1.2.3. CHECK Constraint
Let us understand how a CHECK constraint works in MySQL. For example, the following statement
creates a table "Persons" that contains CHECK constraint on the "Age" column. The CHECK constraint
ensures that the inserted value in a column must be satisfied with the given condition means the
Age of a person should be greater than or equal to 18:
Execute the listed queries to insert the values into the table:
Output
11 | P a g e
4.1.2.4. DEFAULT Constraint
This constraint is used to set the default value for the particular column where we have not
specified any value. It means the column must contain a value, including NULL.
For example, the following statement creates a table "Persons" that contains DEFAULT constraint on
the "City" column. If we have not specified any value to the City column, it inserts the default value:
Execute the listed queries to insert the values into the table:
Output
Now, executes the following statement to validate the default value for the 4th column:
This constraint is used to identify each record in a table uniquely. If the column contains primary key
constraints, then it cannot be null or empty. A table may have duplicate columns, but it can contain
only one primary key. It always contains unique value into a column.
The following statement creates a table "Person" and explains the use of this primary key more
clearly:
Output
In the below output, we can see that the first insert query executes successfully. While the second
insert statement fails and gives an error that says: Duplicate entry for the primary key column.
13 | P a g e
4.1.2.6. AUTO_INCREMENT Constraint
This constraint automatically generates a unique number whenever we insert a new record into the
table. Generally, we use this constraint for the primary key field in a table.
Output
In the output, we can see that I have not specified any value for the auto-increment column, so
MySQL automatically generates a unique number in the sequence order for this field.
14 | P a g e
4.1.2.7. Foreign Key Constraint
This constraint is used to link two tables together. It is also known as the referencing key. A foreign
key column matches the primary key field of another table. It means a foreign key field in one table
refers to the primary key field of another table.
Table: Persons
Table: Orders
In the above table structures, we can see that the "Person_ID" field in the "Orders" table points to
the "Person_ID" field in the "Persons" table. The "Person_ID" is the PRIMARY KEY in the "Persons"
table, while the "Person_ID" column of the "Orders" table is a FOREIGN KEY.
Output
The ENUM data type in MySQL is a string object. It allows us to limit the value chosen from a list of
permitted values in the column specification at the time of table creation. It is short for enumeration,
which means that each column may have one of the specified possible values.
Next, we need to insert the values into the "Shirts" table using the below statements:
16 | P a g e
4. (3, 'formal-shirt', 'large');
Now, execute the SELECT statement to see the inserted values into the table:
Output
This constraint allows us to create and retrieve values from the table very quickly and easily. An index
can be created using one or more than one column. It assigns a ROWID for each row in that way
they were inserted into the table.
The following illustration creates a table named "shirts" that contains three columns: id, name, and
size.
Next, we need to insert the values into the "Shirts" table using the below statements:
17 | P a g e
1. mysql> INSERT INTO Shirts(id, name, size)
2. VALUES (1,'t-shirt', 'medium'),
3. (2, 'casual-shirt', 'small'),
4. (3, 'formal-shirt', 'large');
We can use the query below to retrieve the data using the index column:
Output
The show or list table is very important when we have many databases that contain various tables.
Sometimes the table names are the same in many databases;
18 | P a g e
The following output explains it more clearly:
MySQL allows us to use the FROM or IN clause followed by the database name. The following
statement explains it more clearly:
When we execute the below statements, we will get the same result:
Output:
19 | P a g e
1. mysql> SHOW TABLES FROM mystudentdb LIKE "stud%";
Syntax
Example
20 | P a g e
Syntax
column1 datatype,
column2 datatype,
column3 datatype,
....
);
Example
Syntax:-
Example:-
Create Table Employee(empno int, name varchar(20), dept varchar(20), salary int);
Create table Student(roll int, name varchar(20), stream varchar(20), per int);
21 | P a g e
5.4 INSERTING RECORDS IN TABLE
Syntax:-
Note:-
3) Date values are passed in the format dd-mon-yyyy i.e. 20-Sep-2015 (in oracle) yyyy-mm-dd
(in mysql)
Syntax:-
Select statement allows to send queries to table and fetch the desired record. Select can be used
to select both horizontal and vertical subset.
Syntax:-
DISTINCT keyword is used to eliminate the duplicate records from output. For e.g. if we select dept
from employee table it will display all the department from the table including duplicate rows.
22 | P a g e
Dept
--------
Sales
Sales
IT
IT
HR
If we don’t want to see the duplicate rows in output we have to use DISTINCT keyword.
Dept
--------
Sales
IT
HR
For Example
Select 10*2;
Select 10*3/6;
MySQL also provides DUAL table to provide compatibility with other DBMS. It is dummy table used
for these type queries where table name is not required. It contains one row and one column. For
example:
23 | P a g e
5.7 COLUMN ALIAS
It is a temporary name/label given to column that will appear in output. For example if column
name is dept and you want Department to appear as column heading then we have to give
Column Alias. If we want alias name of multiple words then it should be enclosed in double
quotes. Its format is :
Example
(i) Select empno Employee_Number, name, dept Department, Salary Income from emp;
From the above table we can observe that salary of Shaban is NULL i.e. not assigned, Now
if we want 0 or “not assigned” for the salary information of shaban, we have to use IFNULL()
SQL allows to put user defined symbols or text with table output. Like ‘Rs’ with Salary or ‘%’ symbol
with commission
For e.g.
Select name, ‘ works in department’, dept, ‘ and getting salary rs. ‘, salary from emp;
24 | P a g e
6.0 WHERE clause
WHERE clause is used to select specified rows. It allows to select only desired rows by applying
condition. We can use all comparison(>, <, >=, <=, =, <>) and logical operator (AND, OR, NOT).
For example
AND(&&) means both conditions must be true, OR(||) means any condition must be true to
produce output. NOT(!) will do the reverse checking.
Select name,dept from emp where dept=‘HR’ and salary>=20000 and salary<=40000;
1) BETWEEN
2) IN
3) LIKE
4) IS NULL
6.1.1 BETWEEN
BETWEEN allows to specify range of values to search in any column. It is used with AND clause and
it will include the specified values during the searching. For e.g.
Select * from emp where salary NOT between 25000 and 35000
6.1.2 IN
IN allows to specify LIST of values in which searching will be performed. It will return all those
record that matches any value in a given list of values. It can be thought as an alternative of
multiple ORs
6.1.3 LIKE
LIKE allows to search based on pattern. It is used when we don’t want to search an exact value or
we don’t know that exact value, and we know only the pattern of value like name starting from any
particular letter, or ending with and containing any particular letter or word.
6.1.4 IS NULL
IS NULL is used to compare NULL values present in any column. Because NULL is not considered as
value so we cannot compare with = sign, so to compare with NULL SQL provides IS NULL.
26 | P a g e
OPERATOR PRECEDENCE
When multiple operators are used in expression, then evaluation of expression takes place in
the order of precedence. Higher precedence operator will execute first
By default records will come in the output in the same order in which it was entered. To see the
output rows in sorted or arranged in ascending or descending order SQL provide ORDER BY
clause. By default output will be ascending order(ASC) to see output in descending order we
use DESC clause with ORDER BY.
The GROUP BY statement groups rows that have the same values into summary rows, like "find the
number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(),
AVG()) to group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
27 | P a g e
Example:
SELECT * FROM Customers GROUP BY Country;
The HAVING clause was added to SQL because the WHERE keyword cannot be used with
aggregate functions.
HAVING Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition;
Example:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
A function is built – in code for specific purpose that takes value and returns a single value. Values
passed to functions are known as arguments/parameters.
1) String Function
2) Mathematical function
28 | P a g e
10.1 String Function
29 | P a g e
10.2 Numeric Function
30 | P a g e
Difference Between NOW() and SYSDATE() :
NOW() function return the date and time at which function was executed even if we execute
multiple NOW() function with select. whereas SYSDATE() will always return date and time at which
each SYDATE() function started execution. For example.
Aggregate function is used to perform calculation on group of rows and return the calculated
summary like sum of salary, average of salary etc.
1. SUM()
2. AVG()
3. COUNT()
4. MAX()
5. MIN()
6. COUNT(*)
Output – 161000
31 | P a g e
Output – 59000
Output – 32200
Output - 29500
Output – 5
Output - 1
Output - 3
Output – 45000
Output - 35000
Output – 24000
Output - 27000
Output – 6
Output - 5
Count(*) function is used to count the number of rows in query output whereas count() is used to
count values present in any column excluding NULL values.
Note:
Aggregate functions by default takes the entire table as a single group that’s why we are getting
the sum(), avg(), etc output for the entire table. Now suppose organization wants the sum() of all
32 | P a g e
the job separately, or wants to find the average salary of every job. In this case we have to logically
divide our table into groups based on job, so that every group will be passed to aggregate
function for calculation and aggregate function will return the result for every group.
Group by clause helps up to divide the table into logical groups based on any column value. In
those logically divided records we can apply functions.
For. E.g.
NOTE :- when we are using GROUP BY we can use only aggregate function and the column on
which we are grouping in the SELECT list because they will form a group other than any column
will gives you an error because they will be not the part of the group.
For e.g.
• If we want to filter or restrict some rows from the output produced by GROUP BY then we
use HAVING clause. It is used to put condition of group of rows. With having clause we can
use aggregate functions also.
• WHERE is used before the GROUP BY. With WHERE we cannot use aggregate function.
E.g.
UPDATE Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
33 | P a g e
UPDATE – Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
WHERE CustomerID = 1;
UPDATE Customers
SET PostalCode = 00000
WHERE Country = 'Mexico';
Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!
UPDATE Customers
SET PostalCode = 00000
WHERE Country = 'Mexico';
Wrong Query:
UPDATE Customers
SET PostalCode = 00000;
DELETE Syntax
34 | P a g e
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!
It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
DELETE FROM table_name;
The following SQL statement deletes all rows in the "Customers" table, without deleting the table:
DELETE FROM Customers;
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing
table.
Example
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name;
The following SQL deletes the "Email" column from the "Customers" table:
ALTER TABLE Customers
DROP COLUMN Email;
35 | P a g e
15.1.3 ALTER TABLE - MODIFY COLUMN
To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
Example:
ALTER TABLE Persons
ADD DateOfBirth date;
Change Data Type Example
ALTER TABLE Persons
MODIFY COLUMN DateOfBirth year;
Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
Syntax:
DROP TABLE table_name;
Note: Be careful before dropping a table. Deleting a table will result in loss of complete
information stored in the table!
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table itself.
Syntax:
TRUNCATE TABLE table_name;
In MySQL, the DELETE, TRUNCATE, and DROP statements are used to modify and delete data in a
table. The main difference between these statements is how they work:
36 | P a g e
DELETE
Deletes a record or records from a table. If you don't specify a WHERE condition, it will delete all
rows in the table. Data can be rolled back with the DELETE command
TRUNCATE
Deletes all rows or data in a table. It's similar to a DELETE statement without a WHERE condition.
TRUNCATE drops the table and recreates it. Data cannot be rolled back with the TRUNCATE
command
DROP
Deletes the table structure and all data. It permanently deletes a table and its data.
37 | P a g e
19.1 KEYS:
For example, ID is used as a key in the Student table because it is unique for each student. In the
PERSON table, passport_number, license_number, SSN are keys since they are unique for each
person.
Types of keys:
1. Primary key
o It is the first key used to identify one and only one instance of an entity uniquely. An entity
can contain multiple keys, as we saw in the PERSON table. The key which is most suitable
from those lists becomes a primary key.
o In the EMPLOYEE table, ID can be the primary key since it is unique for each employee. In the
EMPLOYEE table, we can even select License_Number and Passport_Number as primary keys
since they are also unique.
o For each entity, the primary key selection is based on requirements and developers.
38 | P a g e
2. Candidate key
o A candidate key is an attribute or set of attributes that can uniquely identify a tuple.
o Except for the primary key, the remaining attributes are considered a candidate key. The
candidate keys are as strong as the primary key.
For example: In the EMPLOYEE table, id is best suited for the primary key. The rest of the attributes,
like SSN, Passport_Number, License_Number, etc., are considered a candidate key.
3. Super Key
Super key is an attribute set that can uniquely identify a tuple. A super key is a superset of a candidate
key.
39 | P a g e
For example: In the above EMPLOYEE table, for(EMPLOEE_ID, EMPLOYEE_NAME), the name of two
employees can be the same, but their EMPLYEE_ID can't be the same. Hence, this combination can
also be a key.
4. Foreign key
• Foreign keys are the column of the table used to point to the primary key of another table.
• Every employee works in a specific department in a company, and employee and department
are two different entities. So we can't store the department's information in the employee
table. That's why we link these two tables through the primary key of one table.
• We add the primary key of the DEPARTMENT table, Department_Id, as a new attribute in the
EMPLOYEE table.
• In the EMPLOYEE table, Department_Id is the foreign key, and both the tables are related.
5. Alternate key
There may be one or more attributes or a combination of attributes that uniquely identify each
tuple in a relation. These attributes or combinations of the attributes are called the candidate keys.
One key is chosen as the primary key from these candidate keys, and the remaining candidate key,
40 | P a g e
if it exists, is termed the alternate key. In other words, the total number of the alternate keys is the
total number of candidate keys minus the primary key. The alternate key may or may not exist. If
there is only one candidate key in a relation, it does not have an alternate key.
For example, employee relation has two attributes, Employee_Id and PAN_No, that act as candidate
keys. In this relation, Employee_Id is chosen as the primary key, so the other candidate key, PAN_No,
acts as the Alternate key.
6. Composite key
Whenever a primary key consists of more than one attribute, it is known as a composite key. This
key is also known as Concatenated Key.
For example, in employee relations, we assume that an employee may be assigned multiple roles,
and an employee may work on multiple projects simultaneously. So the primary key will be
composed of all three attributes, namely Emp_ID, Emp_role, and Proj_ID in combination. So these
attributes act as a composite key since the primary key comprises more than one attribute.
41 | P a g e
Difference between different Keys in SQL
Foreign Key Used to maintain referential integrity between tables It can be NULL
It is a combination of
Composite Used to uniquely identify a row when a single column
columns, however, they
Key is not sufficient
must be unique.
42 | P a g e
20.1 MySQL Joins
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
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:
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:
43 | P a g e
20.2 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
The INNER JOIN keyword selects records that have matching values in both tables.
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
44 | P a g e
Demo Database
The following SQL statement selects all orders with customer information:
Example:
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!
The following SQL statement selects all orders with customer and shipper information:
Example
45 | P a g e
20.4 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).
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Demo Database
46 | P a g e
MySQL LEFT JOIN Example
The following SQL statement will select all customers, and any orders they might have:
Example
Note: The LEFT JOIN keyword returns all records from the left table (Customers), even if
there are no matches in the right table (Orders).
The RIGHT JOIN keyword returns all records from the right table (table2), and the matching
records (if any) from the left table (table1).
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Demo Database
The following SQL statement will return all employees, and any orders they might have
placed:
47 | P a g e
Example
Note: The RIGHT JOIN keyword returns all records from the right table (Employees), even
if there are no matches in the left table (Orders).
The CROSS JOIN keyword returns all records from both tables (table1 and table2).
SELECT column_name(s)
FROM table1
CROSS JOIN table2;
Demo Database
The following SQL statement selects all customers, and all orders:
Example
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
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
49 | P a g e
UNION ALL Syntax
The UNION operator selects only distinct values by default. To allow duplicate values,
use UNION ALL:
Note: The column names in the result-set are usually equal to the column names in the
first SELECT statement.
Demo Database
The following SQL statement returns the cities (only distinct values) from both the
"Customers" and the "Suppliers" table:
Example
50 | P a g e
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!
The following SQL statement returns the cities (duplicate values also) from both the
"Customers" and the "Suppliers" table:
Example
The following SQL statement returns the German cities (only distinct values) from both
the "Customers" and the "Suppliers" table:
Example
51 | P a g e