Functions in SQL
Functions in SQL
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
Definition Syntax
Example Output
SELECT COUNT(price) as
Price_greater_than_100 FROM product
WHERE price > 100;
Sum Function
Definition Syntax
Example Output
Syntax
Definition
Example Output
Syntax
Definition
Example Output
Definition Syntax
SELECT column_name FROM
table_name ORDER BY column name
Last function returns the last DESC LIMIT value;
field value of the given column.
Last Example
Example Output
Definition Syntax
Example Output
Definition Syntax
Example Output
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
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
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)
Example Output
SELECT ROUND(2.372891,3)
Length Function
Syntax
Definition
SELECT LENGTH(column_name) FROM
table_name;
Length function returns the
total length of the given column.
Length Example
Example Output
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
Example Output
SELECT FORMAT(121.234,2)
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
Example Output
SELECT MID(p_name,1,4) as
new_product_name FROM product;
NOW Function
Syntax
Definition
SELECT NOW()
NOW function is used to retrieve
the system’s current date and
time.
NOW Example
Example Output
Syntax
Definition
SELECT UCASE(column_name) FROM
UCASE function converts the table_name;
given column to uppercase.
UCASE Example
Example Output
Syntax
Definition
SELECT LCASE(column_name) FROM
LCASE function converts the table_name;
given column to lowercase.
LCASE Example
Example Output
SELECT LCASE('HELLO')
Problem Statement
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
Example Output
Syntax
Definition
SELECT TRIM (String 1) FROM table
name;
Trim function is used to remove
the spaces from both sides of
the given string.
Trim Example
Example Output
SELECT TRIM('JESSICA')
Problem Statement
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
CREATE TABLE
`example`.`candidates` (
`FirstName` VARCHAR(255) NOT NULL,
`LastName` VARCHAR(255) NOT NULL);
Assisted Practice: String Function
VALUE INSERTION
3. Write a query to combine FirstName and LastName into a single string in a new column
named Name.
QUERY
ABS ()
TRUNCATE () CEIL ()
String Functions
Numeric
functions
MOD () FLOOR ()
ABS Function
Definition Syntax
Example Output
SELECT ABS(-121.23)
Ceil Function
Syntax
Definition
SELECT CEIL(VALUE);
Ceil function returns the
smallest integer value that is
greater than or equal to the
given number.
Ceil Example
Example Output
SELECT CEIL(121.34)
Floor Function
Syntax
Definition
SELECT FLOOR(VALUE);
Example Output
SELECT FLOOR(121.34)
Truncate Function
Definition Syntax
Example Output
SELECT TRUNCATE(1345.32,1)
MOD Function
Syntax
Definition
Example Output
SELECT MOD(8,3)
Problem Statement
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
calculate the profit percentage in order to review your sales.
Objective: You are required to calculate the profit percentage using the sales, profit, and
discount columns.
Solution
Query
After executing the query, we can calculate the profit percentage for the
superstore table.
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');
Example Output
Syntax
Definition
select time(expression);
Example Output
Syntax
Definition
EXTRACT(part FROM expression)
Example Output
Definition Syntax
Example Output
SELECT DATE_FORMAT('2007-10-04
22:23:00', '%H:%i:%s');
Problem Statement
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'),
(1,'Two Men with the Blues','Willie Nelson and Wynton Marsalis','Blue Note','2008-07-08'),
(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.
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 CountFROM
productGROUP BY categoryHAVING
COUNT(*) = 1
Problem Statement
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);
Example Output
SELECT CONVERT('11:52:35',TIME)
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
Example Output
SELECT IF(200<100,'YES','NO')
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
Example Output
SELECT ISNULL('1213')
IFNULL Function
Definition Syntax
Example Output
Definition Syntax
select COALESCE(expression1,expression
Coalesce function returns the first 2,…..)
Example Output
SELECT COALESCE(NULL,'121','AAA',NULL)
Problem Statement
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
Objective: You are required to check for profit in the profit column and convert the
datatype of the quantity column to decimal.
Solution
Query
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.
General Functions
General Functions and Its Types
Version
ASCII Function
Syntax
Definition
select ASCII(expression);
Example Output
SELECT ASCII('A')
Version Function
Syntax
Definition
select VERSION()
Example Output
SELECT VERSION()
Session User Function
Syntax
Definition
select SESSION_USER()
Example Output
SELECT SESSION_USER()
Problem Statement
Objective: You are required to find the current version of MySQL installed on your system.
Solution
Query
SELECT VERSION();
Output
Objective: You are required to find the ASCII value of the first character from all the
records in column Customer_Name.
Solution
Query
After executing the query, the ASCII value of the first character from all the records in
Customer_Name column is shown as the following output:
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
VALUES(1, 'YogaMat','2020-01-01',150),
(2, 'Rod','2020-01-01',50),
(3, 'Dumbell',null,100),
(4, 'YogaMat','2020-01-01',null),
(5, 'Bench','2020-01-01',null);
Assisted Practice: Functions Two
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:
Assisted Practice: Functions Two
SQL Query
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
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 to the given number ?
3
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