0% found this document useful (0 votes)
27 views33 pages

DCM Exp

Uploaded by

aashrithsai7.dkm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views33 pages

DCM Exp

Uploaded by

aashrithsai7.dkm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Expeerment: 3

3.1 For a given set of relation schemes, create tables and perform the following
using MySQL Workbench:

 Simple Queries with Aggregate functions

MySQL's aggregate function is used to perform calculations on multiple values


and return the result in a single value like the average of all values, the
sum of all values, and maximum & minimum value among certain groups of values.
We mostly use the aggregate functions with SELECT statements in the data query
languages.

Syntax:

The following are the syntax to use aggregate functions in MySQL:

function_name (DISTINCT | ALL expression)

n the above syntax, we had used the following parameters:

o First, we need to specify the name of the aggregate function.


o Second, we use the DISTINCT modifier when we want to calculate the result
based on distinct values or ALL modifiers when we calculate all values,
including duplicates. The default is ALL.
o Third, we need to specify the expression that involves columns and
arithmetic operators.

There are various aggregate functions available in MySQL. Some of the most
commonly used aggregate functions are summarised in the below table:

Aggregate Function Descriptions

count() It returns the number of rows, including rows with NULL values in a
group.

sum() It returns the total summed values (Non-NULL) in a set.

average() It returns the average value of an expression.

min() It returns the minimum (lowest) value in a set.

max() It returns the maximum (highest) value in a set.

groutp_concat() It returns a concatenated string.


first() It returns the first value of an expression.

last() It returns the last value of an expression.

Why we use aggregate functions?


We mainly use the aggregate functions in databases, spreadsheets and many other
data manipulation software packages. In the context of business, different
organization levels need different information such as top levels managers
interested in knowing whole figures and not the individual details. These functions
produce the summarised data from our database. Thus they are extensively used in
economics and finance to represent the economic health or stock and sector
performance.

Let us take an example of myflix (video streaming website which has huge
collections of the movie) database, where management may require the following
details:

o Most rented movies.


o Least rented movies.
o Average number that each movie is rented out in a month.

We can easily produce these details with the help of aggregate functions.

Let us discuss the most commonly used aggregate functions in detail. First, we will
create a new table for the demonstration of all aggregate functions.

Create an employee table:

Mysql> CREATE TABLE employee(


name varchar(45) NOT NULL,
occupation varchar(35) NOT NULL,
working_date date,
working_hours varchar(10)
);

Insert the records into the employee table:


NSERT INTO employee VALUES
('robin', 'Scientist', '2020-10-04', 12),
('warner', 'Engineer', '2020-10-04', 10),
('Peter', 'Actor', '2020-10-04', 13),
('marco', 'Doctor', '2020-10-04', 14),
('Brayden', 'Teacher', '2020-10-04', 12),
('Antonio', 'Business', '2020-10-04', 11);

Display the table


SELECT statement to show the record:

Count() Function

MySQL count() function returns the total number of values in the expression. This function produces all rows or
only some rows of the table based on a specified condition, and its return type is BIGINT. It returns zero if it does
not find any matching rows. It can work with both numeric and non-numeric data types.

Example

Suppose we want to get the total number of employees in the employee table, we
need to use the count() function as shown in the following query:

mysql> SELECT COUNT(name) FROM employee;

Output:

After execution, we can see that this table has six employees.
Sum () Function

The MySQL sum () function returns the total summed (non-NULL)


value of an expression. It returns NULL if the result set does not have any
rows. It works with numeric data type only.

Suppose we want to calculate the total number of working hours of all


employees in the table, we need to use the sum () function as shown in the
following query:

1. mysql> SELECT SUM(working_hours) AS "Total working hours" FROM employee;

Output:

After execution, we can see the total working hours of all employees in the table.

AVG() Function:
MySQL AVG() function calculates the average of the values specified in the
column. Similar to the SUM() function, it also works with numeric data type only.

Suppose we want to get the average working hours of all employees in the table, we need to use
the AVG() function as shown in the following query:

mysql> SELECT AVG(working_hours) AS "Average working hours" FROM employe


e;
Output:

After execution, we can see that the average working hours of all employees
in the organization:
MIN() Function

MySQL MIN() function returns the minimum (lowest) value of the specified column. It also
works with numeric data type only.

Suppose we want to get minimum working hours of an employee available in the table, we need
to use the MIN () function as shown in the following query:

mysql> SELECT MIN(working_hours) AS Minimum_working_hours FR


OM employee;

Output:

After execution, we can see that the minimum working hours of an employee
available in the table:

MAX() Function

MySQL MAX() function returns the maximum (highest) value of the specified
column. It also works with numeric data type only.

Suppose we want to get maximum working hours of an employee available in the


table, we need to use the MAX() function as shown in the following query:

mysql> SELECT MAX(working_hours) AS Maximum_working_hours FROM employe


e;
Output:

After execution, we can see that the maximum working hours of an employee
available in the table:

FIRST() Function

This function returns the first value of the specified column. To get the first value of the
column, we must have to use the LIMIT clause. It is because FIRST() function only supports in
MS Access.

Suppose we want to get the first working date of an employee available in the table, we need to
use the following query:

mysql> SELECT working_date FROM employee LIMIT 1;

Output:

After execution, we can see that the first working date of an employee available in the table:
LAST() Function

This function returns the last value of the specified column. To get the last value
of the column, we must have to use the ORDER BY and LIMIT clause. It is because
the LAST() function only supports in MS Access.

Suppose we want to get the last working hour of an employee available in the table,
we need to use the following query:

mysql> SELECT working_hours FROM employee ORDER BY name DESC LIMIT 1;

Output:

After execution, we can see that the last working hour of an employee available in
the table:

GROUP_CONCAT () Function

The GROUP_CONCAT() function returns the concatenated string from multiple rows into a
single string. If the group contains at least one non-null value, it always returns a string value.
Otherwise, we will get a null value.

Suppose we have another employee table as below:


If we want to concatenate the designation of the same dept_id on the employee table, we need to use the following
query:

mysql> SELECT emp_id, emp_fname, emp_lname, dept_id,


GROUP_CONCAT(designation) as "designation" FROM employee group by emp_id;

Output:

After execution, we can see that the designation of the same dept_id concatenated successfully:
EXP 3.2

Queries with Aggregate functions (group by and having clause)

MySQL GROUP BY Clause


The MYSQL GROUP BY Clause is used to collect data from multiple records and group the result by one or more
column. It is generally used in a SELECT statement.

You can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc. on the grouped column.

Syntax:

SELECT expression1, expression2, expression_n,


aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, expression_n;

Parameters

expression1, expression2, expression_n: It specifies the expressions that are not encapsulated within an
aggregate function and must be included in the GROUP BY clause.

aggregate_function: It specifies a function such as SUM, COUNT, MIN, MAX, or AVG etc. tables: It specifies the
tables, from where you want to retrieve the records. There must be at least one table listed in the FROM clause.

WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for the records to be selected.

i) MySQL GROUP BY Clause with COUNT function


Consider a table named "officers" table, having the following records.

Now, let's count repetitive number of cities in the column address.


Execute the following query:

SELECT address, COUNT(*)


FROM officers
GROUP BY address;

Output:

(ii) MySQL GROUP BY Clause with SUM function


Let's take a table "employees" table, having the following data.

Now, the following query will GROUP BY the example using the SUM function and return the emp_name and total
working hours of each employee.

Execute the following query:

SELECT emp_name, SUM(working_hours) AS "Total working hours"


FROM employees
GROUP BY emp_name;
Output:

(iii) MySQL GROUP BY Clause with MIN function


The following example specifies the minimum working hours of the employees form the table "employees".

Execute the following query:

SELECT emp_name, MIN(working_hours) AS "Minimum working hour"


FROM employees
GROUP BY emp_name;

Output:

(iv) MySQL GROUP BY Clause with MAX function


The following example specifies the maximum working hours of the employees form the table "employees".

Execute the following query:

SELECT emp_name, MAX (working_hours) AS "Minimum working hour"


FROM employees
GROUP BY emp_name;

Output:

(v) MySQL GROUP BY Clause with AVG function

The following example specifies the average working hours of the employees form the table
"employees".

Execute the following query:

SELECT emp_name, AVG(working_hours) AS "Average working hour"


FROM employees
GROUP BY emp_name;

Output:
MySQL HAVING Clause
MySQL HAVING Clause is used with GROUP BY clause. It always returns the rows where condition is TRUE.

Syntax:

SELECT expression1, expression2, ... expression_n,


aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, expression_n
HAVING condition;

Parameters

aggregate_function: It specifies any one of the aggregate function such as SUM, COUNT, MIN, MAX, or AVG.

expression1, expression2, expression_n: It specifies the expressions that are not encapsulated within an
aggregate function and must be included in the GROUP BY clause.

WHERE conditions: It is optional. It specifies the conditions for the records to be selected.

HAVING condition: It is used to restrict the groups of returned rows. It shows only those groups in result set
whose conditions are TRUE.

HAVING Clause with SUM function


Consider a table "employees" table having the following data.

Here, we use the SUM function with the HAVING Clause to return the emp_name and sum of their working hours.

Execute the following query:

SELECT emp_name, SUM(working_hours) AS "Total working hours"


FROM employees
GROUP BY emp_name
HAVING SUM(working_hours) > 5;

Simply, it can also be used with COUNT, MIN, MAX and AVG functions.

EXP 3.2
Queries involving- Date Functions, String Functions, Math Functions

MySQL date/time Functions


MySQL date/time functions are used to manipulate temporal values. The following table indicates each of the
functions with a brief description:

Functions Description

date() The date() function is used to get the date from given date/datetime.

adddata() The adddata() function is used to get the date in which some
time/date intervals are added.

curdate() The curdate() function is used to get the current date.

current_date() The current_date() function is used to get the current date.

date_add() The date_add() function is used to get the date in which some
date/datetime intervals are added.

date_format() The date_format() function is used to get the date in specified format.

datediff() The datediff() function is used to get the difference between the two
specified date values.

day() The day() function is used to get the day from the given date.

dayname() The dayname() function is used to get the name of the day from the
given date.

dayofmonth() The dayofmonth() function is used to get the day for the specified
date.

dayofweek() The dayofweek() function is used to get the day of the week in
numeric.

dayofyear() The dayofyear() function is used to get the number of day in the year.

from_days() The from_days() function is used to get the date of the given number
of days.

hour() The hour() function is used to get the hour from the given datetime.

addtime() The addtime() function is used to get the time/datetime value in


which some time intervals are added.

current_time() The current_time() function is used to get the current time.

current_timesta The current_timestamp() function is used to get the current date and
mp() time.

curtime() The curtime() function is used to get the current time.

last_day() The last_day() function is used to get the last date of the given month
on the date.

localtime() The localtime() function is used to get the current date and time.

localtimestamp() The localtimestamp() function is used to get the current date and
time.

makedate() The makedate() function is used to make the date from the given
year and number of days.

maketime() The maketime() function is used to make the time from given hour,
minute and second.
microsecond() The microsecond() function is used to get the value of the
microsecond from the given datetime or time.

minute() The minute() function is used to get the value of month for the
specified datetime or time.

month() The month() function is used to get the value of month from given
datetime or time.

monthname() The monthname() function is used to get the full month name.

now() The now() function is used to get the current date and time.

period_add() The period_add() function adds the given number of month in the
given period in the format YYMM or YYYYMM.

period_diff() The period_diff() function is used to get the difference between the
given two periods.

quater() The quarter() function is used to get the quarter portion of the
specified date/datetime.

sec_to_time() The sec_to_time() function is used to convert the specified second


into time.

second() The second() function is used to get the second portion from the
specified date/datetime.

str_to_date() The str_to_date() function is used to convert the string into the given
format_mask.

subdate() The subdate() function is used to get the date which is subtracted by
given intervals.

subtime() The subtime() function is used to get the time/datetime which is


subtracted by certain intervals.

sysdate() The sysdate() function is used to get the system date.

time() The time() function is used to get the time for the given
time/datetime.

time_format() The time_format() function is used to format the time in specified


format_mask.

time_to_sec() The time_to_sec() function is used to convert the time into seconds.

timediff() The timediff() function is used to get the difference for the given two
time/datetime.

timestamp() The timestamp() function is used to convert the expression into


datetime/time.

to_day() The to_day() function is used to convert the date into numeric number
of days.

weekday() The weekday() function is used to get the index for a date

week() The week() function is used to get the week portion for the specified
date.

weekofyear() The weekofyear() function is used to get the week of the given date.

Example 1

1. SELECT ADDDATE('1997-01-02', 31);

Output:
mysql> SELECT ADDDATE('1997-01-02', 31);
+---------------------------------------------------------+
| DATE_ADD('1997-01-02', INTERVAL 31 DAY) |
+---------------------------------------------------------+
| 1997-02-02 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

Example 2

1. SELECT DATE('2004-12-21 01:02:03');

Output:

mysql> SELECT DATE('2004-12-21 01:02:03');


+---------------------------------------------------------+
| DATE('2004-12-21 01:02:03') |
+---------------------------------------------------------+
| 2004-12-21 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

MySQL String Function


MySQL string functions manipulate the character string data effectively. The following table indicates each of the
functions with a brief description:

Functions Description

CONCAT_WS() MySQL CONCAT_WS() function returns a string by concatenating


arguments using separator.

CONCAT() The CONCAT() function returns a string by concatenating all the


arguments.

CHARACTER_LENGT The CHARACTER_LENGTH() function returns the size of the


H() specified string.

ELT() The ELT() function returns the Nth element from the list of string.

EXPORT_SET() The EXPORT_SET() function the returns string for each bit set.

FIELD() The FIELD() function returns the index of string.

FIND_IN_SET() The FIND_IN_SET() function returns the value of the string which is
given in the first position in the argument.

FORMAT() The FORMAT() function formats the number X to round of D


decimal place.

FROM_BASE64() The FROM_BASE64() function encodes the given string to binary


format.

HEX() The HEX() function returns the specified number or string in a


hexadecimal string.

INSERT() In INSERT() function, a string str is passed with a position 'pos'


which tells at which position the character is to be placed, and 'len'
length is the length of the character to be placed.

INSTR() The INSTR() function returns the 1st occurrence of substring substr
in string str.

LCASE() The LCASE() function returns 1st occurrence of substring substr in


string str.

LEFT() The LEFT() function returns left side 'len' characters from the given
string 'str'.

LENGTH() The LENGTH() function returns the length of the specified string
which is measured in bytes.

LIKE() The LIKE() function returns either 1 or 0 and is used for checking
pattern matching.

LOAD_FILE() The LOAD_FILE() function returns the content of the file.

LOCATE() The LOCATE() function returns the first occurrence of given 'substr'
in the given string.

LOWER() The LOWER() function returns the given string in lower case.

LPAD() The LPAD() function returns string 'str' which is left-padded to the
given length.

LTRIM() The LTRIM() function returns string by removing leading space.

MAKE_SET() The MAKE_SET() function returns values from the set for the given
bit.

MID() The MID() function extracts a substring from a string and returns a
string with given length and position.

OCTET_LENGTH() The OCTET_LENGTH() function returns length of given string.


OCT() The OCT() function returns length of given string.

ORD() The ORD() function returns the code for the leftmost character if
that character is a multi-byte.

POSITION() The POSITION() function returns the position of the given substring
in a string.

QUOTE() The QUOTE() function returns the string which is passed in a single
quote.

REPEAT() The REPEAT() function repeats a string for a specified number of


times.

REPLACE() The REPLACE() function replaces all the occurrences of a substring


within a string.

REVERSE() The REVERSE() function reverses a string supplied as an argument.

RIGHT() The RIGHT() function extracts a specified number of characters


from the right side of a string.

RPAD() The MYSQL RPAD() function pads the specified strings from the
right.

RTRIM() The MYSQL RTRIM() function removes the trailing spaces from the
specified string.

SOUNDEX() The MYSQL SOUNDEX() function returns the soundex string for the
specified string.

Example 1
1. SELECT SOUNDEX('javatpoint');

Output:

mysql> SELECT SOUNDEX('javatpoint');


+-----------------------+
| SOUNDEX('javatpoint') |
+-----------------------+
| W6262 |
+-----------------------+
1 row in set (0.00 sec)

Example 2
1. SELECT ORD('mysql');

Output:
mysql> SELECT ORD('mysql');
+-------------------+
| ORD('mysql') |
+-------------------+
| 109 |
+-------------------+
1 row in set (0.00 sec)

Example 3
1. SELECT REPEAT('*+*',15);

Output:

mysql> SELECT REPEAT('*+*',15);


+-----------------------------------------------+
| REPEAT('*+*',15) |
+-----------------------------------------------+
| *+**+**+**+**+**+**+**+**+**+**+**+**+**+**+* |
+-----------------------------------------------+
1 row in set (0.03 sec)

MYSQL Math functions


MySQL provides a wide range of functions which serves a wide range of arithmetical purposes. The following table
indicates each of the functions with a brief description:

Functions Description

ABS() The ABS() function returns the absolute value of the specified number.

ACOS() The ACOS() function is used to get the arc cosine of the given number.

SIGN() The SIGN() function is used to get a sign of the specified number.

SIN() The SIN() function is used to get the sine value of the given number.

SQRT() The SQRT() function is used to get the square root of the given number.

SUM() This function is used to sum the values of given expressions.

TAN() The TAN() function is used to get the tangent of the given number

TRUNCATE The TRUNCATE() function is used to get the given number truncated up to
() given certain decimal places.

ASIN() The ASIN() function is used to get the arc sine of the given number.

ATAN2() The ATAN2 function is used to get the arc tangent of the specified numbers
n and m.

ATAN() The ATAN() function is used to get the arc tangent of the specified number.

AVG() The AVG() function is used to get the average value from the given
expression.

CEIL() The CEIL() function returns the smallest value which is greater than or equal
to the specified number.

CEILING() The CEILING() function returns the smallest value which is greater than or
equal to the given number.

COS() The COS() function is used to get the cosine of the given number.

COT() The COT() function is used to get the cotangent of the given number.

COUNT() The COUNT() function is used to get the total count for the specified column
of the table.

DEGREES( DEGREES() function is used to convert the given radian number into a
) degree.

DIV() The DIV() function is used to find the integer division by dividing the number
n by the number m.

EXP() The EXP() function is used to find e raised to the power of number i.e.
enumber.

FLOOR() The FLOOR() function is used to find the greatest integer which is equal to or
less than the specified number.

GREATEST The GREATEST() function is used to get the largest number from the list.
()

LEAST() The LEAST() function is used to get the smallest number from the list.

LN() The LN() function is used to get the natural logarithm for the specified
number.

LOG10() The LOG10() function is used to get the base-10 logarithm for the specified
number.

LOG() The LOG() function is used to return either the natural logarithm of the given
number if it has one parameter or specified base logarithm number if it has
two parameters.

LOG2() The LOG2() function is used to get the base-2 logarithm for the specified
number.

MAX() The MAX() function is used to get the maximum number of the given column
name.

MIN() The MIN() function is used to get the minimum number of the given column
name.

MOD() The MOD() function is used to get the remainder for the specified values.

PI() The PI() function is used to get the value of pi upto 6 decimal places.

POWER() The POWER() function is used to get the power for the specified values.

POW() The POW function is used to get the power for the specified values.

RADIANS() The RADIANS() function is used to convert the given degrees to radians.

RAND() The RAND() function is used to generate the random number.

ROUND() The ROUND() function is used to round off the specified number.

Example 1

1. select pi();

Output:

mysql> SELECT PI();


+----------+
| PI() |
+----------+
| 3.141593 |
+----------+
1 row in set (0.00 sec)

Example 2

1. Select pow(3,2);

Output:

mysql> SELECT POW(3, 2);


+-----------+
| POW(3, 2) |
+-----------+
| 9 |
+-----------+
1 row in set (0.00 sec)

Example 3

1. select 4 % 3;

Output:

mysql> SELECT 4 % 3;
+-------+
| 4 % 3 |
+-------+
| 1 |
+-------+
1 row in set (0.00 sec)
EXP 4
For a given set of relation schemes, create tables and perform the following Join Queries using MySQL Workbench:

o Inner Join
o Outer Join

MySQL Inner Join


The MySQL Inner Join is used to returns only those results from the tables that match the specified condition
and hides other rows and columns. MySQL assumes it as a default Join, so it is optional to use the Inner Join
keyword with the query.

We can understand it with the following visual representation where Inner Joins returns only the matching
results from table1 and table2:

MySQL Inner Join Syntax:

The Inner Join keyword is used with the SELECT statement and must be written after the FROM clause. The
following syntax explains it more clearly:

1. SELECT columns
2. FROM table1
3. INNER JOIN table2 ON condition1
4. INNER JOIN table3 ON condition2
5. ...;

In this syntax, we first have to select the column list, then specify the table name that will be joined to the
main table, appears in the Inner Join (table1, table2), and finally, provide the condition after the ON keyword.
The Join condition returns the matching rows between the tables specifies in the Inner clause.

MySQL Inner Join Example

Let us first create two tables "students" and "technologies" that contains the following data:

Table: student
Table: technologies

To select records from both tables, execute the following query:

1. SELECT students.stud_fname, students.stud_lname, students.city, technologies.technology


2. FROM students
3. INNER JOIN technologies
4. ON students.student_id = technologies.tech_id;

After successful execution of the query, it will give the following output:

MySQL Inner Join with Group By Clause

The Inner Join can also be used with the GROUP BY clause. The following statement returns student id,
technology name, city, and institute name using the Inner Join clause with the GROUP BY clause.

1. SELECT students.student_id, technologies.inst_name, students.city, technologies.technology


2. FROM students
3. INNER JOIN technologies
4. ON students.student_id = technologies.tech_id GROUP BY inst_name;

The above statement will give the following output:

MySQL Inner Join with USING clause


Sometimes, the name of the columns is the same in both the tables. In that case, we can use a USING
keyword to access the records. The following query explains it more clearly:

1. SELECT student_id, inst_name, city, technology


2. FROM students
3. INNER JOIN technologies
4. USING (student_id);

It will give the following output:

Inner Join with WHERE Clause

The WHERE clause enables you to return the filter result. The following example illustrates this clause with
Inner Join:

1. SELECT tech_id, inst_name, city, technology


2. FROM students
3. INNER JOIN technologies
4. USING (student_id) WHERE technology = "Java";

This statement gives the below result:

MySQL Inner Join Multiple Tables

We have already created two tables named students and technologies. Let us create one more table and
name it as a contact.

Execute the following statement to join the three table students, technologies, and contact:

1. SELECT student_id, inst_name, city, technology, cellphone


2. FROM students
3. INNER JOIN technologies USING (student_id)
4. INNER JOIN contact ORDER BY student_id;
After successful execution of the above query, it will give the following output:

MySQL Inner Join using Operators

MySQL allows many operators that can be used with Inner Join, such as greater than (>), less than (<), equal
(=), not equal (=), etc. The following query returns the result whose income is in the range of 20000 to
80000:

1. SELECT emp_id, designation, income, qualification


2. FROM employee
3. INNER JOIN customer
4. WHERE income>20000 and income<80000;

This will give the following output:


SQL OUTER JOIN
o In the SQL outer JOIN, all the content from both the tables is integrated together.
o Even though the records from both the tables are matched or not, the matching and non-matching records
from both the tables will be considered an output of the outer join in SQL.
o There are three different types of outer join in SQL:
1. Left Outer Join
2. Right Outer Join
3. Full Outer Join

Now let us take a deeper dive into the different types of outer join in SQL with the help of examples. All the queries
in the examples will be written using the MySQL database.

Consider we have the following tables with the given data:

Table 1: employee

EmployeeID Employee_Name Employee_Salary

1 Arun Tiwari 50000

2 Sachin Rathi 64000

3 Harshal Pathak 48000

4 Arjun Kuwar 46000

5 Sarthak Gada 62000

6 Saurabh Sheik 53000

7 Shubham Singh 29000

8 Shivam Dixit 54000

9 Vicky Gujral 39000

10 Vijay Bose 28000

Table 2: department

DepartmentID Department_Name Employee_ID

1 Production 1

2 Sales 3

3 Marketing 4

4 Accounts 5

5 Development 7

6 HR 9

7 Sales 10

Table 3: Loan
LoanID Branch Amount

1 B1 15000

2 B2 10000

3 B3 20000

4 B4 100000

5 B5 150000

6 B6 50000

7 B7 35000

8 B8 85000

Table 4: Borrower

CustID CustName LoanID

1 Sonakshi Dixit 1

2 Shital Garg 4

3 Swara Joshi 5

4 Isha Deshmukh 2

5 Swati Bose 7

6 Asha Kapoor 10

7 Nandini Shah 9

1. Left Outer Join:

o If we use the left outer join to combine two different tables, then we will get all the records from the left
table. But we will get only those records from the right table, which have the corresponding key in the left
table.
o Syntax of writing a query to perform left outer join:

SELECT TableName1.columnName1, TableName2.columnName2 FROM TableName1 LEFT OUTER JOIN TableName2


ON TableName1.ColumnName = TableName2.ColumnName;

Example 1:

Write a query to perform left outer join considering employee table as the left table and department table as the
right table.

Query:

1. mysql> SELECT e.EmployeeID, e.Employee_Name, e.Employee_Salary, d.DepartmentID, d.Department_Name FRO


M employee e LEFT OUTER JOIN department d ON e.EmployeeID = d.Employee_ID;

We have used the SELECT command to retrieve EmployeeID, Employee_Name, Employee_Salary, DepartmentID,
Department_Name present in the employee and department table. Then we have used the LEFT OUTER JOIN
keyword to perform the left outer join operation on the employee and department table where 'e' and 'd' are
aliases. These two tables are joined on the column EmployeeID which is present in both the tables.
You will get the following output:

EmployeeID Employee_Name Employee_Salary DepartmentID Department_Name

1 Arun Tiwari 50000 1 Production

2 Sachin Rathi 64000 NULL NULL

3 Harshal Pathak 48000 2 Sales

4 Arjun Kuwar 46000 3 Marketing

5 Sarthak Gada 62000 4 Accounts

6 Saurabh Sheik 53000 NULL NULL

7 Shubham Singh 29000 5 Development

8 Shivam Dixit 54000 NULL NULL

9 Vicky Gujral 39000 6 HR

10 Vijay Bose 28000 7 Sales

EmployeeID, Employee_Name, Employee_Salary, Department_ID, Department_Name are retrieved from employee


and department tables. All the records from the employee table are retrieved. Only those records that have a
corresponding EmployeeID in the employee table are retrieved from the department table. Rest other records in the
department table for which an employeeID doesn't match with the employeeID of the employee table; then, it is
displayed as NULL.

Example 2:

Write a query to perform left outer join considering loan table as the left table and borrower table as the right table.

Query:

1. mysql> SELECT l.LoanID, l.Branch, l.Amount, b.CustID, b.CustName FROM Loan l LEFT OUTER JOIN Borrower b ON
l.LoanID = b.LoanID;

We have used the SELECT command to retrieve LoanID, Branch, Amount, CustID, CustName present in the loan and
borrower table. Then we have used the LEFT OUTER JOIN keyword to perform the left outer join operation on the
loan and borrower table where 'l' and 'b' are aliases. These two tables are joined on the column LoanID which is
present in both the tables.

You will get the following output:

LoanID Branch Amount CustID CustName

1 B1 15000 1 Sonakshi Dixit

2 B2 10000 4 Isha Deshmukh

3 B3 20000 NULL NULL

4 B4 100000 2 Shital Garg

5 B5 150000 3 Swara Joshi

6 B6 50000 NULL NULL

7 B7 35000 5 Swati Bose

8 B8 85000 NULL NULL


LoanID, Branch, Amount, CustID, CustName are retrieved from loan and borrower tables. All the records from the
loan table are retrieved. Only those records that have a corresponding LoanID in the loan table are retrieved from
the borrower table. Rest other records in the borrower table for which a LoanID doesn't match with the LoanID of
the loan table; are displayed as NULL.

2. Right Outer Join:

o Right outer join is the reverse of left outer join. If we use the right outer join to combine two different
tables, then we will get all the records from the right table. But we will get only those records from the left
table, which have the corresponding key in the right table.
o Syntax of writing a query to perform right outer join:

1. SELECT TableName1.columnName1, TableName2.columnName2 FROM TableName1 RIGHT OUTER JOIN TableNa


me2 ON TableName1.ColumnName = TableName2.ColumnName;

Example 1:

Write a query to perform right outer join considering employee table as the left table and department table as the
right table.

Query:

1. mysql> SELECT e.EmployeeID, e.Employee_Name, e.Employee_Salary, d.DepartmentID, d.Department_Name FRO


M employee e RIGHT OUTER JOIN department d ON e.EmployeeID = d.Employee_ID;

We have used the SELECT command to retrieve EmployeeID, Employee_Name, Employee_Salary, DepartmentID,
Department_Name present in the employee and department table. Then we have used the RIGHT OUTER JOIN
keyword to perform the right outer join operation on the employee and department table where 'e' and 'd' are
aliases. These two tables are joined on the column EmployeeID which is present in both the tables.

You will get the following output:

EmployeeID Employee_Name Employee_Salary DepartmentID Department_Name

1 Arun Tiwari 50000 1 Production

3 Harshal Pathak 48000 2 Sales

4 Arjun Kuwar 46000 3 Marketing

5 Sarthak Gada 62000 4 Accounts

7 Shubham Singh 29000 5 Development

9 Vicky Gujral 39000 6 HR

10 Vijay Bose 28000 7 Sales

EmployeeID, Employee_Name, Employee_Salary, DepartmentID, Department_Name are retrieved from employee


and department tables. All the records from the department table are retrieved. Only those records that have a
corresponding EmployeeID in the department table are retrieved from the employee table.

Example 2:

Write a query to perform right outer join considering loan table as the left table and borrower table as the right
table.

Query:
1. mysql> SELECT l.LoanID, l.Branch, l.Amount, b.CustID, b.CustName FROM Loan l RIGHT OUTER JOIN Borrower b O
N l.LoanID = b.LoanID;

We have used the SELECT command to retrieve LoanID, Branch, Amount, CustID, CustName present in the loan and
borrower table. Then we have used the RIGHT OUTER JOIN keyword to perform the right outer join operation on the
loan and borrower table where 'l' and 'b' are aliases. These two tables are joined on the column LoanID which is
present in both the tables.

You will get the following output:

LoanID Branch Amount CustID CustName

1 B1 15000 1 Sonakshi Dixit

4 B4 100000 2 Shital Garg

5 B5 150000 3 Swara Joshi

2 B2 10000 4 Isha Deshmukh

7 B7 35000 5 Swati Bose

NULL NULL NULL 6 Asha Kapoor

NULL NULL NULL 7 Nandini Shah

LoanID, Branch, Amount, CustID, CustName are retrieved from loan and borrower tables. All the records from the
borrower table are retrieved. Only those records that have a corresponding LoanID in the borrower table are
retrieved from the loan table. Rest other records in the loan table for which a LoanID doesn't match with the LoanID
of the borrower table; then, are displayed as NULL.

3. Full Outer Join:

o If we use a full outer join to combine two different tables, then we will get all the records from both
the table,e., we will get all the records from the left table as well as the right table.
o MySQL doesn't support FULL OUTER JOIN directly. So to implement full outer join in MySQL, we will
execute two queries in a single query. The first query will be of LEFT OUTER JOIN, and the second query
will be of RIGHT OUTER JOIN. We will combine the first and second query with the UNION operator to see
the results of FULL OUTER JOIN.
o Syntax of writing a query to perform full outer join:

1. SELECT TableName1.columnName1, TableName2.columnName2 FROM TableName1 LEFT OUTER JOIN TableName


2 ON TableName1.ColumnName = TableName2.ColumnName UNION SELECT TableName1.columnName1, TableN
ame2.columnName2 FROM TableName1 RIGHT OUTER JOIN TableName2 ON TableName1.ColumnName = TableN
ame2.ColumnName;

Example 1:

Write a query to perform full outer join considering the employee table as the left table and department table as
the right table.

Query:

1. mysql> SELECT e.EmployeeID, e.Employee_Name, e.Employee_Salary, d.DepartmentID, d.Department_Name FRO


M department d LEFT OUTER JOIN employee e ON e.EmployeeID = d.Employee_ID UNION SELECT e.EmployeeID,
e.Employee_Name, e.Employee_Salary, d.DepartmentID, d.Department_Name FROM department d RIGHT OUTER J
OIN employee e ON e.EmployeeID = d.Employee_ID;

We have used the SELECT command to retrieve EmployeeID, Employee_Name, Employee_Salary, DepartmentID,
Department_Name present in the employee and department table. Then we have used the LEFT OUTER JOIN
keyword to perform the left outer join operation on the employee and department table where 'e' and 'd' are
aliases. Then we have written a SELECT query to perform right outer join operation on employee and department
table where 'e' and 'd' are aliases. These two tables are joined on the column EmployeeID which is present in both
the tables. Both the SELECT queries are combined using the UNION operator.

You will get the following output:

EmployeeID Employee_Name Employee_Salary DepartmentID Department_Name

1 Arun Tiwari 50000 1 Production

3 Harshal Pathak 48000 2 Sales

4 Arjun Kuwar 46000 3 Marketing

5 Sarthak Gada 62000 4 Accounts

7 Shubham Singh 29000 5 Development

9 Vicky Gujral 39000 6 HR

10 Vijay Bose 28000 7 Sales

2 Sachin Rathi 64000 NULL NULL

6 Saurabh Sheik 53000 NULL NULL

8 Shivam Dixit 54000 NULL NULL

EmployeeID, Employee_Name, Employee_Salary, Department_ID, Department_Name are retrieved from employee


and department tables. All the records from the employee table are retrieved as a result of the left outer join. Only
those records that have a corresponding EmployeeID in the employee table are retrieved from the department
table. Rest other records in the department table for which an employeeID doesn't match with the employeeID of
the employee table; then, are displayed as NULL. All the records from the department table are retrieved as a result
of the right outer join. Only those records that have a corresponding EmployeeID in the department table are
retrieved from the employee table.

Example 2:

Write a query to perform full outer join considering loan table as the left table and borrower table as the right table.

Query:

1. mysql> SELECT l.LoanID, l.Branch, l.Amount, b.CustID, b.CustName FROM Loan l LEFT OUTER JOIN Borrower b ON
l.LoanID = b.LoanID UNION SELECT l.LoanID, l.Branch, l.Amount, b.CustID, b.CustName FROM Loan l RIGHT OUTE
R JOIN Borrower b ON l.LoanID = b.LoanID;

We have used the SELECT command to retrieve LoanID, Branch, Amount, CustID, CustName present in the loan and
borrower table. Then we have used the LEFT OUTER JOIN keyword to perform the left outer join operation on the
loan and borrower table where 'l' and 'b' are aliases. Then we have written a SELECT query to perform the right
outer join operation on the loan and borrower table where 'l' and 'b' are aliases. These two tables are joined on the
column LoanID which is present in both the tables. Both the SELECT queries are combined using the UNION
operator.

You will get the following output:


LoanID Branch Amount CustID CustName

1 B1 15000 1 Sonakshi Dixit

2 B2 10000 4 Isha Deshmukh

3 B3 20000 NULL NULL

4 B4 100000 2 Shital Garg

5 B5 150000 3 Swara Joshi

6 B6 50000 NULL NULL

7 B7 35000 5 Swati Bose

8 B8 85000 NULL NULL

NULL NULL NULL 6 Asha Kapoor

NULL NULL NULL 7 Nandini Shah

LoanID, Branch, Amount, CustID, CustName are retrieved from loan and borrower tables. All the records from the
loan table are retrieved as a result of the left outer join. Only those records that have a corresponding LoanID in the
loan table are retrieved from the borrower table. Rest other records in the borrower table for which a LoanID
doesn't match with the LoanID of the loan table; are displayed as NULL. All the records from the borrower table are
retrieved as a result of the right outer join. Only those records that have a corresponding LoanID in the borrower
table are retrieved from the loan table. Rest other records in the loan table for which a LoanID does

You might also like