DCM Exp
DCM Exp
3.1 For a given set of relation schemes, create tables and perform the following
using MySQL Workbench:
Syntax:
There are various aggregate functions available in MySQL. Some of the most
commonly used aggregate functions are summarised in the below table:
count() It returns the number of rows, including rows with NULL values in a
group.
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:
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.
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:
Output:
After execution, we can see that this table has six employees.
Sum () Function
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:
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:
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.
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:
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:
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.
Output:
After execution, we can see that the designation of the same dept_id concatenated successfully:
EXP 3.2
You can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc. on the grouped column.
Syntax:
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.
Output:
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.
Output:
Output:
The following example specifies the average working hours of the employees form the table
"employees".
Output:
MySQL HAVING Clause
MySQL HAVING Clause is used with GROUP BY clause. It always returns the rows where condition is TRUE.
Syntax:
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.
Here, we use the SUM function with the HAVING Clause to return the emp_name and sum of their working hours.
Simply, it can also be used with COUNT, MIN, MAX and AVG functions.
EXP 3.2
Queries involving- Date Functions, String Functions, Math Functions
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.
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.
current_timesta The current_timestamp() function is used to get the current date and
mp() 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.
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.
time() The time() function is used to get the time for the given
time/datetime.
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.
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
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
Output:
Functions Description
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.
FIND_IN_SET() The FIND_IN_SET() function returns the value of the string which is
given in the first position in the argument.
INSTR() The INSTR() function returns the 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.
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.
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.
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.
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:
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:
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.
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.
ROUND() The ROUND() function is used to round off the specified number.
Example 1
1. select pi();
Output:
Example 2
1. Select pow(3,2);
Output:
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
We can understand it with the following visual representation where Inner Joins returns only the matching
results from table1 and table2:
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.
Let us first create two tables "students" and "technologies" that contains the following data:
Table: student
Table: technologies
After successful execution of the query, it will give the following output:
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.
The WHERE clause enables you to return the filter result. The following example illustrates this clause with
Inner Join:
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:
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:
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.
Table 1: employee
Table 2: department
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
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
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:
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:
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:
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.
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:
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:
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.
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.
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.
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:
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:
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.
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.
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