Joining Queries and Functions in MySQL
Joining Queries and Functions in MySQL
○ Comparison
○ Control flow
● If you use the UNION ALL explicitly, the duplicate rows, if available, remain in
the result. Because UNION ALL does not need to handle duplicates, it
performs faster than UNION DISTINCT .
● Let us look at Venn diagram that shows how UNION operator combine
results from two distinct queries
UNION VENN REPRESENTATION
UNION EXAMPLE
● Let us know look at the example that will further clarify usage of
UNION operator
● We want to get the names and surnames of all employees and
customers in a single query
SELECT c.contactFirstName, c.contactLastName
FROM customers c
UNION ALL
SELECT e.firstName, e.lastName
FROM employees e
UNION EXAMPLE CONT.
● As previously discussed, the UNION ALL will return all entities no
matter if there are duplicates or not whereas the UNION DISTINCT
(that is a default behaviour of UNION) will return only unique values for
the columns list
SELECT c.contactFirstName, c.contactLastName
FROM customers c
UNION ALL
SELECT e.firstName, e.lastName
FROM employees e
FULL OUTER JOIN
● Although MySQL does not support the FULL OUTER JOIN in many
other SQL implementations you are able to use this type of join. By
using the UNION operator this is also possible in the MySQL by using
the combination of JOIN and UNION operator. Let us consider the
example of three tables: students, courses, and student_courses
where the student_courses table creates the many to many
relationship between students and courses.
● Let us now consider two scenarios, in first we want to get all records
from both tables and in second we want to get students who are not
taking any courses and all courses that have no students taking them
FULL OUTER JOIN 1st SCENARIO
SELECT s.student_id, s.student_name, c.course_id, c.course_name
FROM students s
LEFT JOIN enrollments e ON s.student_id = e.student_id
LEFT JOIN courses c ON e.course_id = c.course_id
UNION
SELECT s.student_id, s.student_name, c.course_id, c.course_name
FROM students s
RIGHT JOIN enrollments e ON s.student_id = e.student_id
RIGHT JOIN courses c ON e.course_id = c.course_id
FULL OUTER JOIN 2nd SCENARIO
SELECT s.student_id, s.student_name, c.course_id, c.course_name
FROM students s
LEFT JOIN enrollments e ON s.student_id = e.student_id
LEFT JOIN courses c ON e.course_id = c.course_id
WHERE c.course_id IS NULL
UNION
SELECT s.student_id, s.student_name, c.course_id, c.course_name
FROM students s
RIGHT JOIN enrollments e ON s.student_id = e.student_id
RIGHT JOIN courses c ON e.course_id = c.course_id
WHERE s.student_id IS NULL;
JOIN VS UNION
● Imagine you have two tables of information. When you use a JOIN, it's
like merging those tables side-by-side, bringing together related data
points in new columns. Think of it as creating a wider table.
● On the other hand, UNION acts like stacking the tables on top of each
other. It combines the results row by row, adding new rows to get a
final list.
INTERSECT
● The INTERSECT compares the result sets of two queries and returns the common rows.
○ The data types in columns across queries should be either identical or compatible.
○ INTERSECT gets rid of duplicate rows automatically. You don't need a DISTINCT command for this.
● If you use the INTERSECT ALL explicitly, the duplicate rows, if available, remain in the
result. Because INTERSECT ALL does not need to handle duplicates, it performs faster than
INTERSECT DISTINCT .
○ EXCEPT gets rid of duplicate rows automatically. You don't need a DISTINCT command for this.
● If you use the EXCEPT ALL explicitly, the duplicate rows, if available, remain in the
result. Because EXCEPT ALL does not need to handle duplicates, it performs faster
than EXCEPT DISTINCT .
● Let us look at Venn diagram that shows how EXCEPT operates
EXCEPT VENN DIAGRAM
EXCEPT EXAMPLE
● Let us now get all names from the actor table that are not in the
customers table in the sakila database
SELECT a.first_name
FROM actor a
EXCEPT
SELECT c.first_name
FROM customer c;
SELECT e.firstName,
LPAD(e.firstName, 8, "b"),
RPAD(e.firstName, 8, "b")
FROM employees e;
COMPARISON FUNCTIONS
● COALESCE – return the first non-NULL arguments, which is very handy
for substitution of NULL.
● GREATEST & LEAST – take n arguments and return the greatest and least
values of the narguments respectively.
● ISNULL – return 1 if the argument is NULL, otherwise, return zero.
SELECT COALESCE(NULL, e.firstName),
GREATEST(e.firstName, e.lastName, e.email),
LEAST(1,2,0,10),
ISNULL(NULL)
FROM employees e
CONTROL FLOW FUNCTIONS
● CASE – return the corresponding result in THEN branch if the condition in
the WHEN branch is satisfied, otherwise, return the result in the ELSE
branch.
● IF(condition, value_if_true, value_if_false) – return a value based on a
given condition.
● IFNULL(expression, alt_value) - return the first argument if it is not NULL,
otherwise returns the second argument.
● NULLIF( expr1, expr2 return NULL if the first argument is equal to the
second argument, otherwise, returns the first argument.
CONTROL FLOW FUNCTIONS CONT.
SELECT e.firstName,
IF(e.firstName = 'Mary', 1, 0),
IFNULL(NULL, e.firstName),
IFNULL(e.firstName, e.lastName),
NULLIF(e.firstName, e.firstName),
NULLIF(e.firstName, e.lastName)
FROM employees e;
CONTROL FLOW FUNCTIONS CONT.
SELECT e.firstName,
e.lastName,
CASE
WHEN e.firstName = 'Diane' THEN "OK"
WHEN e.firstName = 'Mary' THEN "NOT OK"
WHEN e.lastName = 'Bow' THEN "GOOD SURNAME"
ELSE e.firstName
END AS conditions
FROM employees e
● Case is extremely useful when you have certain conditions inside of the
SQL code and its syntax is straightforward
DATE FUNCTIONS
● Date functions are operating on date and data types that are compatible
with date (datetime, time) and are used to manipulate the dates, getting
current date and time, converting date to timestamp and vice versa,
adding and subtracting dates
● In following slides we will cover the most commonly used date functions
and explain their usage in different scenarios
GETTING THE CURRENT DATE & TIME
● CURDATE – Return the current date. ( synonyms: CURRENT_DATE &
CURRENT_DATE.
● CURRENT_TIME – Return the current time ( synonyms: CURRENT_TIME
& CURTIME .
● NOW – Return the current date and time ( synonyms:
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, LOCALTIME,
LOCALTIMESTAMP.
● SYSDATE – Return the time at which it executes.
● UTC_TIMESTAMP – Return the current UTC date and time.
● UTC_DATE – Return the current UTC date.
● UTC_TIME – Return the current UTC time.
GETTING THE CURRENT DATE & TIME CONT.
● The usage of previously mentioned functions is straightforward and they
donʼt accept any arguments
SELECT CURDATE(),
CURRENT_TIME,
NOW(),
SYSDATE(),
UTC_TIMESTAMP(),
UTC_DATE(),
UTC_TIME();
CALCULATING DATE AND TIME
● ADDTIME(datetime, addtime) – Add a time interval to a time value or datetime value.
● DATE_ADD(date, INTERVAL value addunit) – Add a time value to a date (synonyms:
ADDDATE.
● DATE_SUB(date, INTERVAL value addunit) – Subtract a time value (interval) from a date.
● DATEDIFF(date1, date2 – Return the difference in days of two date values.
● TIMEDIFF(time1, time2 – Return the difference of two time values.
● TIMESTAMPADD(unit,interval,datetime_expr) – Add or subtract an interval from a timestamp
or date.
● TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2 – Return the difference between two
timestamp values.
● TIME_TO_SEC(time) – Return the number of seconds from a time argument.
● TO_DAYS(date) – Return a day number (the number of days since year 0) from a given date.
● The unit can be one of the following values FRAC_SECOND (microseconds), SECOND,
MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.
CALCULATING DATE AND TIME CONT.
SELECT o.orderDate,
ADDTIME(o.orderDate , 10000),
DATE_ADD(o.orderDate, INTERVAL 1 QUARTER),
DATE_SUB(o.orderDate, INTERVAL 2 DAY),
DATEDIFF(o.orderDate, o.shippedDate),
TIMEDIFF(o.orderDate, o.shippedDate),
TIMESTAMPADD(DAY, 10, o.orderDate),
TIMESTAMPDIFF(DAY, o.orderDate, o.shippedDate),
TIME_TO_SEC('1:00:00'),
TO_DAYS(o.orderDate)
FROM orders o;
FUNCTIONS FOR CONVERTING DATE AND TIME
● FROM_UNIXTIME(unix_timestamp, [format -optional]) – Convert UNIX
timestamps into a readable date and time format.
● UNIX_TIMESTAMP(date) – Convert a datetime to a UNIX timestamp.
use sakila;
SELECT FROM_UNIXTIME(1714933934),
UNIX_TIMESTAMP(f.last_update)
FROM film f;
FUNCTIONS FOR EXTRACTING DATE AND TIME
● DATE(date) – Extract the date component from a date.
● EXTRACT(unit FROM date) – Extract a component of a date.
● YEAR(date) – Return the year component of a date.
● YEARWEEK(data) – Return the year and week for a date.
● QUARTER(date) – Return the quarter of the year for a date.
● MONTH(date) – Return the month component of a date.
● WEEK(date) – Return the week component of a date.
● WEEKDAY(date) – Return the weekday index of a date.
● WEEKOFYEAR(date) – Return the calendar week of the date 153 – equivalent to WEEK(date, 3.
● DAY(date) – Return the day of the month for a specific date 131. DAYOFMONTH is the synonym for
DAY.
● DAYOFYEAR(date) – Return the day of the year 1366.
● DAYOFWEEK(date) – Return the day of the week 17.
● HOUR(datetime) – Return the hour for a time.
● MINUTE(datetime) – Return the minute for a time.
● SECOND(datetime) – Return the second for a time.
● LAST_DAY(date) – Return an integer that represents the last day of the month for a specific date.
FUNCTIONS FOR EXTRACTING DATE AND TIME CONT.
use classicmodels;
SELECT DATE(p.paymentDate),
EXTRACT(DAY FROM p.paymentDate),
YEAR(p.paymentDate),
YEARWEEK(p.paymentDate),
QUARTER(p.paymentDate),
MONTH(p.paymentDate),
WEEK(p.paymentDate),
WEEKDAY(p.paymentDate),
WEEKOFYEAR(p.paymentDate),
DAY(p.paymentDate),
DAYOFYEAR(p.paymentDate),
DAYOFWEEK(p.paymentDate),
HOUR(p.paymentDate),
MINUTE(p.paymentDate),
SECOND(p.paymentDate),
LAST_DAY(p.paymentDate)
FROM payments p;
MATH FUNCTIONS
● ABS(n) Returns the absolute value of a number
● CEIL(n) Returns the smallest integer value greater than or equal to the input number (n).
● FLOOR(n) Returns the largest integer value not greater than the argument
● MOD(n) Returns the remainder of a number divided by another
● ROUND(n) Rounds a number to a specified number of decimal places.
● TRUNCATE Truncates a number to a specified number of decimal places
● ACOS(n) Returns the arc cosine of n or null if n is not in the range 1 and 1.
● ASIN(n) Returns the arcsine of n which is the value whose sine is n. It returns null if n is not
in the range 1 to 1.
● ATAN Returns the arctangent of n.
● ATAN2(n,m), ATAN(m,n) Returns the arctangent of the two variables n and m
● CONV(n,from_base,to_base) Converts a number between different number bases
● COS(n) Returns the cosine of n, where n is in radians
● COT(n) Returns the cotangent of n.
● CRC32 Computes a cyclic redundancy check value and returns a 32-bit unsigned value
● DEGREES(n) Converts radians to degrees of the argument n
MATH FUNCTIONS CONT.
● EXP(n) Raises to the power of e raised to the power of n
● LN(n) Returns the natural logarithm of n
● LOG(n) Returns the natural logarithm of the first argument
● LOG10 Returns the base-10 logarithm of the argument
● LOG2 Returns the base-2 logarithm of the argument
● PI Returns the value of PI
● POW(base, exponent) Returns the argument raised to the specified power
● POWER(base, exponent) Returns the argument raised to the specified power
● RADIANSReturns argument converted to radians
● RAND Returns a random floating-point value between 0 and 1.
● SIGN(n) Returns the sign of n that can be 1, 0, or 1 depending on whether n is negative,
zero, or positive.
● SIN(n) Returns the sine of n
● SQRT(n) Returns the square root of n
● TAN(n) Returns the tangent of n
MATH FUNCTIONS CONT
SELECT ABS(-1),
MOD(3,2),
CEIL(1.13),
FLOOR(1.13),
EXP(1),
POW(2,3), -- 8
POWER(2,3) -- 8
FUNCTION NESTING
● What is important to mention is that the function calls in SQL are allowed
to be nested so that an argument for one function can be another
functions as shown in the examples below
SELECT CONCAT(UPPER(c.contactFirstName), ' ', LOWER(c.contactLastName)) AS full_name,
IF(c.country <> 'USA', LOWER(c.country), REPLACE(c.country, 'A', '')) AS cexample,
POW(c.creditLimit / 1000, 2) AS example,
REPLACE(c.phone, '.', '-'),
COALESCE(c.state, c.country)
FROM customers c;
Thank you