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

Joining Queries and Functions in MySQL

Uploaded by

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

Joining Queries and Functions in MySQL

Uploaded by

arnela.sokolic1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

IT 101  Database Design and Implementation

JOINING QUERIES AND FUNCTIONS

Assist. Prof. Dr. Bećir ISAKOVIĆ


AGENDA
● Introduction
● UNION
● INTERSECT
● EXCEPT
● Functions
○ Working with strings

○ Working with dates

○ Working with numbers and math operations

○ Comparison

○ Control flow

● Nesting function calls


UNION
● The UNION operator lets you merge the results of multiple queries into a
single list. Here's what to keep in mind when using UNION
○ All the queries you're combining must have the same number of columns in the same order.
○ The data types in columns across queries should be either identical or compatible.
○ UNION gets rid of duplicate rows automatically. You don't need a DISTINCT command for
this.

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

● Here's what to keep in mind when using INTERSECT


○ All the queries you're combining must have the same number of columns in the same order.

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

● Let us look at Venn diagram that shows how INTERSECT operates


INTERSECT VENN DIAGRAM
INTERSECT EXAMPLE
● Let us now get all shared names between the actors and customers in
the sakila database
SELECT a.first_name
FROM actor a
INTERSECT
SELECT c.first_name
FROM customer c;

● As previously discussed the default behaviour of the INTERSECT


operator is DISTINCT and if we want to have the duplicates in the list
we would have to add the ALL keyword after the INTERSECT operator
EXCEPT
● The EXCEPT compares the result sets of two queries and returns rows that are
present in first query but not in the second.
● Here's what to keep in mind when using EXCEPT
○ All the queries you're combining must have the same number of columns in the same order.
○ The data types in columns across queries should be either identical or compatible.

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

● As previously discussed the default behaviour of the EXCEPT operator


is DISTINCT and if we want to have the duplicates in the list we would
have to add the ALL keyword after the EXCEPT operator
MySQL FUNCTIONS
● In MySQL, functions are a set of built-in operations that perform
specific tasks. These functions can manipulate data, perform
calculations, format output, and more. MySQL provides a wide range
of functions to cater to different needs. Here are some common
categories of MySQL functions:
○ String Functions: These functions manipulate string values
○ Date and Time Functions: These functions handle date and time values.
○ Mathematical Functions: These functions perform mathematical operations
○ Control Flow Functions: These functions control the flow of execution based on
specified conditions.
○ Comparison Functions: Used to compare values and get values
STRING CONCATENATION FUNCTIONS
● Now we will show the most common string functions in MySQL. They
allow you to manipulate character string data effectively.
● CONCAT(expression1, expression2, expression3,...): Combines two
or more strings into a single string.
● CONCAT_WS(separator, expression1, expression2, expression3,...):
Combines multiple strings into a single string with a specified
separator.
● Let us look at examples of how to use the concatenation functions in
MySQL
STRING CONCATENATION FUNCTIONS CONT.
SELECT CONCAT(firstName, ' ', lastName) AS full_name,
CONCAT_WS(' ', firstName, lastName) AS full_name_ws
FROM employees e
● In the example above, we have concatenated the first and last name of
the employees from the classic models by using the ordinary concat
function, and second more convenient for this example the concat_ws
function that allows to specify the separator as a first parameter
STRING SUBSTRING FUNCTIONS
● Let us now look at the functions that are used to extract the portion of the
string in MySQL
● SUBSTRING(string, start, length) or SUBSTRING(string FROM start FOR
length): Extracts a substring from a given string.
● SUBSTRING_INDEX(string, delimiter, number): Extracts a substring from a
string using a delimiter.
● LEFT(string, number_of_chars): Returns a specified number of characters
from the beginning of a string.
● RIGHT(string, number_of_chars): Returns a specified number of characters
from the end of a string.
● MID(string, start, length): Extracts a substring from the middle of a string.
The MID function is a synonym for SUBSTRING.
STRING SUBSTRING FUNCTIONS EXAMPLE
SELECT SUBSTRING(e.firstName, 2), -- from second character until the end
SUBSTRING(e.firstName, 2, 2), -- from second character take 2 characters
SUBSTRING(e.firstName, -4), -- take 4 characters starting from end of string
SUBSTRING(e.firstName, -4, 1), -- starting from 4 character from the end take one character
SUBSTRING_INDEX(e.firstName, 'i', 1), -- gets the substring from the nth occurence of substring
LEFT(e.firstName, 2), -- gets the substring of specified length starting from the left side
RIGHT(e.firstName, 2), -- gets the substring of specified length starting from the right side
MID(e.firstName, -4, 1), -- MID is a equivalent of SUBSTRING function
e.firstName
FROM employees e
● The above example shows how all of the substring functions act and
gives the explanation of them
STRING SEARCHING AND LOCATING FUNCTIONS
● LOCATE(substring, string, start): Finds the position of a substring within
a string.
● POSITION(substring IN string): Finds the position of a substring. The
POSITION is a synonym for the LOCATE function.
● INSTR(string1, string2 Another function for finding the position of a
substring.
STRING SEARCHING AND LOCATING FUNCTIONS CONT.
SELECT e.firstName,
LOCATE("ia", e.firstName, 1), -- returns index of substring beginning starting from provided position
POSITION("ia" IN e.firstName), -- returns index of substring beginning starting from 1
INSTR(e.firstName, "ia") -- returns index of substring beginning starting from 1
FROM employees e;

● INSTR(string1, string2 Another function for finding the position of a


substring.
STRING CASE CONVERSION FUNCTIONS
● UPPER(string): Converts a string to uppercase.
● LOWER(string): Converts a string to lowercase.
SELECT e.firstName,
UPPER(e.firstName),
LOWER(e.firstName)
FROM employees e;
STRING CHARACTER MANIPULATION FUNCTIONS
● REPLACE(string, substring, new_string): Replaces all occurrences of a
substring in a string.
● TRIM(string): Removes leading and trailing spaces from a string.
● LTRIM(string): Removes leading spaces from a string.
● RTRIM(string): Removes trailing spaces from a string.
● REPEAT(string, number): Repeats a string a specified number of times.
● REVERSE(string): Reverses the characters in a string.
● INSERT(string, position, number, string2,): Replaces a substring within a
string with a new substring.
STRING CHARACTER MANIPULATION FUNCTIONS CONT.
SELECT e.firstName,
REPLACE(e.firstName, "r", "B"), -- replaces all occurrences of string r to string B
in employee first name
TRIM(e.firstName),
LTRIM(e.firstName),
RTRIM(e.firstName),
REPEAT(e.firstName, 2), -- repeats a string for specified number of times
REVERSE(e.firstName),
INSERT(e.firstName, 2, 1, "BEL") -- in first name, starting from position 2 removes
next 1 character and inserts "BEL" instead of it
FROM employees e;
STRING WHITESPACE FUNCTIONS
● SPACE(number): Returns a string consisting of spaces.
● ASCII(string): Returns the ASCII value of the leftmost character of a
string.
● CHAR Converts an ASCII value to a character.
SELECT e.firstName,
SPACE(10),
ASCII(e.firstName),
CHAR(77,74)
FROM employees e
STRING LENGTH AND COUNT FUNCTIONS
● LENGTH Returns the length of a string in bytes.
● CHAR_LENGTH: Returns the length of a string in characters.
● OCTET_LENGTH: Returns the length of a string in bytes.
● BIT_LENGTH: Returns the length of a string in bits.
● CHARACTER_LENGTH: Returns the length of a string in characters.
● BIT_COUNT: Counts the number of bits in a binary string.
● STRCMP: Compares two strings and returns their relative order.
SELECT LENGTH(e.firstName),
CHAR_LENGTH(e.firstName),
OCTET_LENGTH(e.firstName),
BIT_LENGTH(e.firstName),
CHARACTER_LENGTH(e.firstName),
BIT_COUNT(e.firstName),
STRCMP(e.firstName, e.lastName)
FROM employees e
STRING PADDING FUNCTIONS
● LPAD(string, length, lpad_string) – Left-pads a string with a set of
characters to a specified length.
● RPAD(string, length, lpad_string) – Right-pads a string with a set of
characters to a specified length.

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 153 – equivalent to WEEK(date, 3.
● DAY(date) – Return the day of the month for a specific date 131. DAYOFMONTH is the synonym for
DAY.
● DAYOFYEAR(date) – Return the day of the year 1366.
● DAYOFWEEK(date) – Return the day of the week 17.
● 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
● RADIANSReturns 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

You might also like