Lesson 07 Functions in SQL
Lesson 07 Functions in SQL
Learning Objectives
• SQL functions are short programs with one or more input parameters but
just one output value.
Advantages of SQL Functions
Are complicated
mathematical logic that can
be broken down into
simpler functions.
Aggregate Functions
Aggregate Functions and Its Types
SUM () 2 3 AVG ()
COUNT () 1 4 FIRST ()
MAX () 7 5 LAST ()
MIN ()
Count Function
Syntax
Definition
SELECT COUNT (column name)
Example Output
SELECT COUNT(price) as
Price_greater_than_100 FROM product
WHERE price > 100;
Sum Function
Syntax
Definition
Example Output
Syntax
Definition
Example Output
Syntax
Definition
Note: Functions like FIRST and LAST are typically more prevalent in databases such as certain versions
of Microsoft SQL Server and PostgreSQL.
First Example
Example Output
Definition Syntax
SELECT column_name FROM table_name
ORDER BY column name DESC LIMIT
Last function returns the last value;
field value of the given column.
Note: Functions like FIRST and LAST are typically more prevalent in databases such as certain versions
of Microsoft SQL Server and PostgreSQL.
Last Example
Example Output
Definition Syntax
Example Output
Definition Syntax
Example Output
Problem Scenario: You are working in a superstore as a junior database administrator. Your manager
has asked you to collect data from the superstore’s table with the schema named as example to check
and improve the sales records and growth of your store by performing a queried operation on the
database.
Objective: You should determine the sum of the sales and profit columns, calculate the average profit,
count the total number of products with a price greater than 100, and calculate the maximum profit
and loss from the superstore table.
Problem Statement
Steps to be performed:
1. Download the superstore table from the course resources and import it in MySQL workbench.
Solution
Query
After executing the query, we get the updated value of the sales, profit, and average profit columns.
Problem Statement
Problem Scenario: You are working in a superstore as a junior database administrator. Your manager
has asked you to retrieve the first ten records of sales that were made during the opening of the store.
Objective: You are required to extract the first ten records of the sales column from the superstore
table.
Solution
SELECT Sales
FROM superstore limit 10;
Output
After executing the query, the first ten records of the database are
shown as the following output:
Problem Statement
Problem Scenario: You are working in a superstore as a junior database administrator. Your manager
has assigned you the task of identifying the top twenty sales records.
Objective: You are required to analyze the superstore table by sorting the column sales in descending
order and finding the first twenty records.
Solution
SELECT Sales
FROM superstore
ORDER BY Sales DESC limit 20;
Output
After executing the query, the first twenty records sorted in descending order will be
shown as the following output:
Scalar Functions
Scalar Functions
The scalar functions return a single value from an input value. It works on
each record independently.
ROUND () LCASE ()
LEN () UCASE ()
FORMAT () NOW ()
MID ()
Round Function
Definition Syntax
ROUND(column_name, decimals)
Output
Example
Syntax
Definition
SELECT LENGTH(column_name) FROM
table_name;
Length function returns the total
length of the given column.
Length Example
Output
Example
SELECT length(p_name) as
Length_product_name FROM product;
Format Function
Syntax
Definition
SELECT FORMAT(column_name,
Format function is used to format format) FROM table_name;
field value in the specified
format.
Format Example
Output
Example
SELECT FORMAT(Number,’####_######’)
AS Formated_Num;
MID Function
Syntax
Definition
SELECT MID(column_name, start,
MID function is used to retrieve length) FROM table_name;
the specified characters from the
text field.
MID Example
Output
Example
Syntax
Definition
SELECT NOW()
NOW function is used to retrieve
the system’s current date and
time.
NOW Example
Output
Example
Syntax
Definition
SELECT UCASE(column_name) FROM
UCASE function converts the table_name;
given column to uppercase.
UCASE Example
Output
Example
Syntax
Definition
SELECT LCASE(column_name) FROM
LCASE function converts the table_name;
given column to lowercase.
LCASE Example
Output
Example
Problem Scenario: You are working in a superstore as a junior database administrator. Your manager
has asked you to find the order number from the order ID column for the better functionality of your
store and to compare the order shipping and delivery dates.
Objective: You are required to extract the order number from the column order ID and list the
shipping and delivery dates. Also, compare these dates with the present date.
Solution
Query
After executing the query, the order number from order ID, order date, ship date, and current
date is being displayed.
String Functions
String Functions
CONCAT ()
String functions
TRIM ()
Concat Function
Syntax
Definition
SELECT CONCAT (String 1, String 2, St
ring3.., String N) FROM table name;
Concat function is used to
combine one or more characters
into a single string.
Concat Example
Output
Example
Syntax
Definition
Output
Example
Problem Scenario: You are working in a superstore as a junior database administrator. Your manager
has asked you to retrieve the list of all the customer addresses to send them a personalized invite as a
marketing strategy for an upcoming sale in the store.
Objective: You are required to display the customer's name, city, state, and postal code from the
superstore table in a single column address. Also, count the length of the customer’s name and
convert it into lowercase and state into uppercase, respectively.
Solution
Query
After executing the query, the customer's name, city, state, and postal
code are collectively shown as an address.
Problem Statement
Problem Scenario: As the junior database administrator, your manager has asked you to format the
customer ID column and remove the extra spaces.
Objective: You are required to format the customer ID column and remove the extra spaces.
Solution
Query
After executing the query, we can eliminate the excess white spaces
from the customer ID column.
Assisted Practice: String Function
Duration: 15 min
Problem Statement: As the HR of your organization, you are expected to wish Merry Christmas to
everyone. List down the full names of all the employees in uppercase using string functions.
Assisted Practice: String Function
Steps to be performed:
1. Create a database named example, then make a table named candidates, that has a column
named FirstName and LastName.
TABLE CREATION
VALUE INSERTION
3. Write a query to combine FirstName and LastName into a single string in a new column named
Name.
QUERY
SELECT CONCAT(UCASE(FirstName)," ",UCASE(LastName)) AS Name
FROM example.candidates;
Assisted Practice: Lab Output
Output:
Numeric Functions
Numeric Functions
ABS ()
TRUNCATE () CEIL ()
String Functions
Numeric
functions
MOD () FLOOR ()
ABS Function
Definition Syntax
Output
Example
Syntax
Definition
SELECT CEIL(VALUE);
Ceil function returns the
smallest integer value that is
greater than or equal to the
given number.
Ceil Example
Output
Example
Syntax
Definition
SELECT FLOOR(VALUE);
Output
Example
Definition
Syntax
Truncate function is used to
truncate a number to the specified SELECT TRUNCATE (VALUE,DECIMALS);
number of decimal places.
Truncate Example
Output
Example
Definition
Syntax
Output
Example
Problem Scenario: You are working in a superstore as a junior database administrator. Your manager
has asked you to perform different operations on the sales column in order to obtain the highest profit
so that the management can plan the next quarter accordingly.
Objective: The data that you received from the profit column is in decimals. You are required to
perform mathematical and scaler operations using different functions to manipulate and compare the
profit generated.
Solution
Query
Problem Scenario: As the junior database administrator, your manager has asked you to check if years
of experience is odd or even.
Query
After executing the query, you can check if the experience is in odd or even years.
Assisted Practice: Numeric Function
Duration: 20 min
Problem Statement: You need to understand the approximate and actual profit from your shop’s daily
transaction ledger and decide to round off the Amount up to 0 and 2 decimal places. Also, apply ceiling
and floor on the Amount respectively to understand the differences.
Assisted Practice: Numeric Function
Steps to be performed:
1. Create a database named example and then make a table named bill, that has a column named
S.no., Name and Amount. Also, assign S.no. as the primary key.
TABLE CREATION
VALUE INSERTION
3. Write a query to perform round() function up to 0 and 2 decimal places and perform ceil() and
floor() functions.
QUERY
It helps to extract the time, date, and year as per the requirement.
DATE () EXTRACT ()
String Functions
Definition Syntax
select date('expression');
Output
Example
Syntax
Definition
select time(expression);
Output
Example
Syntax
Definition
EXTRACT(part FROM expression)
Output
Example
Syntax
Definition
select date_format(date, format_mask)
Output
Example
Problem Scenario: You are working in a superstore as a junior database administrator. Your manager
has asked you to find the date, time, and year of the returned products while listing them in the
American standard format.
Objective: You are required to extract date, time, and year from the Return_Date_Time column of the
table Return product and list the date in American format.
Solution
Query
After executing the query, return date is converted into standard American date format.
Assisted Practice: Functions One
Duration: 20 mins
Problem statement: As an analyst in Audio Hub Ltd., you’ve been asked to report the number of
albums released in different years and report which day of the month has the most releases and which
category label has the most sales.
Assisted Practice: Functions One
Steps to be performed:
Step 01: Create a database named track and then make a table named album with the columns id,
title, artist, label, and release. Here, id will be 'integer' type and all other columns will be 'text’ type.
CREATE
DROP TABLE IF EXISTS album;
CREATE TABLE album (
id INTEGER,
title TEXT,
artist TEXT,
label TEXT,
released DATE
);
Assisted Practice: Functions One
Output:
Assisted Practice: Functions One
SQL Query
INSERT INTO album (id, title, artist, label, released) VALUES (1,'Two Men with the Blues','Willie Nelson and Wynton
Marsalis','Blue Note','2008-07-08'),
(11,'Hendrix in the West','Jimi Hendrix','Polydor','2008-01-07'),
(12,'Rubber Soul','The Beatles','Columbia','2009-12-03'),
(13,'Birds of Fire','Mahavishnu Orchestra','Columbia','2010-03-03'),
(14,’Blue Train','John Coltrane','Blue Note’,’1957-09-15'),
(17,'Apostrophe','Frank Zappa','DiscReet','2011-04-07'),
(18,'Kind of Blue','Miles Davis','Columbia','2008-08-03’);
Assisted Practice: Functions One
Output:
Assisted Practice: Functions One
SQL Query
SELECT * from album;
Assisted Practice: Functions One
Output:
Assisted Practice: Functions One
Step 04: Write a query to find the number of unique albums released each year. Also, figure out which
day number (i.e., from 1 to 31) has reported the most releases and for which category label.
SQL Query
SELECT EXTRACT(YEAR FROM released), COUNT(DISTINCT id)
FROM album
GROUP BY EXTRACT(YEAR FROM released)
Assisted Practice: Functions One
Output:
Assisted Practice: Functions One
SQL Query
SELECT label, DATE_FORMAT(released, '%D')
FROM album
GROUP BY label, DATE_FORMAT(released, '%D')
ORDER BY COUNT(DISTINCT id) DESC
LIMIT 1 ;
Assisted Practice: Functions One
Output:
Handling Duplicate Records
Handling Duplicate Records
• Using DISTINCT and COUNT keywords to fetch the number of unique records.
Using DISTINCT and COUNT keywords to fetch the number of unique records.
Example Output
SELECT COUNT(DISTINCT(category))
AS Unique_records FROM product;
Handling Duplicate Records
Example Output
SELECT p_code, p_name, price, category,
COUNT(*) AS Count
FROM
product
GROUP BY
category
HAVING
COUNT(*) = 1;
Problem Statement
Problem Scenario: You are working in a superstore as a junior database administrator. Your manager
informed you that the table of your superstore has duplicate customer IDs due to multiple orders from
the same customer.
Objective: You are required to filter all the duplicate values and display the list of unique customers.
Solution
Query
CONVERT
COALESCE IF
IFNULL ISNULL
Convert Function
Syntax
Definition
select CONVERT(value,datatype);
Output
Example
SELECT CONVERT(Value,int) AS
Int_value;
IF Function
Syntax
Definition
select IF(expression,VALUE1,VALUE2);
IF function returns value1 if the
expression is TRUE, or value2 if
the expression is FALSE.
IF Example
Output
Example
SELECT IF(Value<100,'YES','NO’) AS
Lesser_100;
ISNULL Function
Syntax
Definition
select ISNULL(expression)
ISNULL function returns 1 if the
expression is NULL or else 0 if
the expression is NOT NULL.
ISNULL Example
Output
Example
Definition Syntax
Output
Example
SELECT IFNULL(Value,’Null’) AS
Null_Check
Coalesce Function
Definition Syntax
select COALESCE(expression1,expression2,…..)
Coalesce function returns the first
non-null value from a list of
expressions.
Coalesce Example
Output
Example
SELECT COALESCE(Value);
Problem Statement
Problem Scenario: You are working in a superstore as a junior database administrator. Your manager
has asked you to cross-check the database for any NULL value.
Objective: You are required to check for NULL value in the database and display the output message as
problem in the record if any NULL value is found in the table.
Problem Statement
Steps to be performed:
1. Download the return_products table from course resources and import it in MySQL workbench.
Solution
Query
After executing the query, a message is displayed in the table when it encounters a
NULL value.
Problem Statement
Problem Scenario: You are working in a superstore as a junior database administrator. Your manager
has asked you to check the profit or loss in the profit column and convert the datatype of the quantity
column to decimal.
Objective: You are required to check for profit in the profit column and convert the datatype of the
quantity column to decimal.
Solution
Query
Problem Scenario You are working in a superstore as a junior database administrator. Your manager
has asked you to check for NULL values in the table return_products.
Objective: You are required to check for NULL values in the table and display NULL value as a message
if any NULL value exists in the table.
Solution
Query
After executing the query, the message is displayed as NULL value when we encounter the first
NON-NULL value in the table.
Assisted Practice: Functions Two
Duration: 20 mins
Problem statement: As a data analyst, you have been asked to clean up the product_sales data. You
will need to perform missing value treatment by implementing proper business logic.
Assisted Practice: Functions Two
Steps to be performed:
Step 01: Create a database named product and then make a table named product_sales with the
columns id (int), product (text), order_date (date), and amount (int)
CREATE
DROP TABLE IF EXISTS sales;
CREATE TABLE product_sales (
id INTEGER,
product TEXT,
order_date DATE,
amount INT
);
Assisted Practice: Functions Two
Output:
Assisted Practice: Functions Two
Query
Output:
Assisted Practice: Functions Two
Query
SELECT * from product_sales;
Assisted Practice: Functions Two
Output:
Assisted Practice: Functions Two
Step 04: Write a query to display the entire data. Replace null in the amount column with 0 and null in
order_date column with 2020-01-01.
Query
SELECT id, product, COALESCE(order_date,'2020-01-01') order_date,
COALESCE(amount,0) amount
FROM product_sales
Assisted Practice: Functions Two
Output:
Knowledge Check
Knowledge
Check
Which one of the following is an aggregate function?
1
A. Sum ( )
B. Date ( )
C. Concat ( )
D. Trim ( )
Knowledge
Check
Which one of the following is an aggregate function?
1
A. Sum ( )
B. Date ( )
C. Concat ( )
D. Trim ( )
A. Aggregate function
B. Scalar function
D. Numeric function
Knowledge
Check
Which of the following works on each record independently?
2
A. Aggregate function
B. Scalar function
D. Numeric function
Scalar, date and time, and numeric functions work in each record independently.
Knowledge
Check Which of the following function returns largest integer value which is less than or equal
3 to the given number ?
A. Ceil ( )
B. Floor ( )
C. Round ( )
D. MOD ( )
Knowledge
Check Which of the following function returns largest integer value which is less than or equal
3 to the given number ?
A. Ceil ( )
B. Floor ( )
C. Round ( )
D. MOD ( )
Floor function returns largest integer value which is less than or equal to the given number.
Knowledge
Check
Which of the following function helps to change a value into specific data type?
4
A. Convert ( )
B. IFNULL ( )
C. Coalesce ( )
D. ISNULL ( )
Knowledge
Check
Which of the following function helps to change a value into specific data type?
4
A. Convert ( )
B. IFNULL ( )
C. Coalesce ( )
D. ISNULL ( )
Problem statement:
You are a data analyst working in a hospital and you have been asked to store
the patients’ diagnosis reports as a best practice.
Objective:
The objective is to design a database to retrieve, update, and modify the
patients’ details to keep track of the patients’ health.
Tasks to be performed:
1. Write a query to create a patients table with the date, patient ID, patient
name, age, weight, gender, location, phone number, disease, doctor
name, and doctor ID fields
2. Write a query to insert values into the patients table
3. Write a query to display the total number of patients in the table
4. Write a query to display the patient ID, patient name, gender, and disease
of the oldest (age) patient
Lesson-End Project: Patient Diagnosis Report
Tasks to be performed:
5. Write a query to display the patient ID and patient name of all entries with
the current date
6. Write a query to display the old patient name and new patient name in
uppercase
7. Write a query to display the patients' names along with the total number
of characters in their name
8. Write a query to display the gender of the patient as M or F along with the
patient's name
Lesson-End Project: Patient Diagnosis Report
Tasks to be performed:
9. Write a query to combine the patient's name and doctor's name in a new
column
10. Write a query to display the patients’ age along with the logarithmic value
(base 10) of their age
11. Write a query to extract the year for a given date and place it in a separate
column
12. Write a query to check the patient’s name and doctor’s name are similar
and display NULL, else return the patient’s name
Lesson-End Project: Patient Diagnosis Report
Tasks to be performed:
13. Write a query to check if a patient’s age is greater than 40 and display Yes
if it is and No if it isn't
14. Write a query to display duplicate entries in the doctor name column
Note: Download the solution document from the Course Resources section
and follow the steps given in the document
Key Takeaways