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

Lesson 07 Functions in SQL

Uploaded by

Achraf Charif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lesson 07 Functions in SQL

Uploaded by

Achraf Charif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 168

Functions in SQL

Learning Objectives

By the end of this lesson, you will be able to:

Illustrate SQL functions

Identify aggregate functions

Outline date and time, numeric, and advance functions

List general, duplicate, and inline functions


Understanding SQL Functions
Understanding SQL Functions

• SQL functions are basic subprograms used extensively to handle or


manipulate data.

• SQL functions enhance database speed and performance.

• SQL functions are short programs with one or more input parameters but
just one output value.
Advantages of SQL Functions

Boost the database's


efficiency and productivity Are compiled and cached

Are complicated
mathematical logic that can
be broken down into
simpler functions.
Aggregate Functions
Aggregate Functions and Its Types

The aggregate functions allow performing the calculation on a set of


values to return a single scalar value.

SUM () 2 3 AVG ()

COUNT () 1 4 FIRST ()

MAX () 7 5 LAST ()

MIN ()
Count Function

Syntax
Definition
SELECT COUNT (column name)

Count function returns the total FROM table name

number of rows in a specified WHERE condition;


column or a table.
Count Example

Example Output

SELECT COUNT(price) as
Price_greater_than_100 FROM product
WHERE price > 100;
Sum Function

Syntax
Definition

SELECT SUM (column name)


FROM table name;
Sum function returns the sum of
values from a particular column.
Sum Example

Example Output

SELECT SUM(stock) as total_stock FROM


product;
Average Function

Syntax
Definition

SELECT AVG (Column name)


Average function returns the FROM table name;
average value of a particular
column.
Average Example

Example Output

SELECT AVG(price) as average_price FROM


product;
First Function

Syntax
Definition

SELECT column_name FROM


table_name LIMIT value;
First function returns the first
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.
First Example

Example Output

SELECT stock FROM product LIMIT 5;


Last Function

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

SELECT stock FROM product ORDER BY


p_code DESC LIMIT 5;
Min Function

Definition Syntax

SELECT MIN(column_name) FROM


table_name;
Min function returns the
minimum value of the given
column.
Min Example

Example Output

SELECT MIN(price) as minimum_price FROM


product;
Max Function

Definition Syntax

SELECT MAX(column_name) FROM


table_name;
Max function returns the
maximum value of the given
column.
Max Example

Example Output

SELECT MAX(price) as maximum_price FROM


product;
Problem Statement

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

SELECT COUNT(Sales) as Updated_value, sum(Sales) as Total_Sales, Sum(Profit) as Total_Profit,


avg(Profit) as Average_Profit, ABS(min(Profit)) as Maximum_Loss, max(Profit) as Maximum_Profit
FROM example.superstore
WHERE Sales > 100;
Output

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

Query for FIRST ten records

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

Query for LAST twenty records

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)

Round function helps to round a


value to a specified number of
places.
Round Example

Output

Example

SELECT Product_name, Buying_price,


ROUND(Buying_price, 2) AS
Rounded_Bprice,
FROM Product;
Length Function

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

SELECT MID(Number,1,4) as New_Num


FROM Contacts;
NOW Function

Syntax
Definition
SELECT NOW()
NOW function is used to retrieve
the system’s current date and
time.
NOW Example

Output

Example

SELECT NOW() AS current_date_time


UCASE Function

Syntax
Definition
SELECT UCASE(column_name) FROM
UCASE function converts the table_name;
given column to uppercase.
UCASE Example

Output

Example

SELECT UCASE(p_name) FROM product


LCASE Function

Syntax
Definition
SELECT LCASE(column_name) FROM
LCASE function converts the table_name;
given column to lowercase.
LCASE Example

Output

Example

SELECT LCASE(p_name) FROM product


Problem Statement

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

SELECT Order_ID, mid(Order_ID,9,14) as Order_Number , Order_Date, Ship_Date, Now() as Today


FROM example.superstore;
Output

After executing the query, the order number from order ID, order date, ship date, and current
date is being displayed.
String Functions
String Functions

The string functions are used for string manipulation.

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

SELECT CONCAT(p_name,' ',category) AS


product_name_category FROM product
Trim Function

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

Output

Example

SELECT TRIM(BOTH ' ‘ pname) AS


Trimmed_pname
FROM product;
Problem Statement

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

SELECT Concat(lcase(Customer_Name),' ','(' , length(Customer_Name), ')', ' ', ucase(City),' ',


ucase(State),' ', Postal_Code) as Address
FROM example.superstore;
Output

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

SELECT Customer_ID, TRIM(Customer_ID) as trimed_output


FROM example.return_products;
Output

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

2. Insert values in the candidates table.

VALUE INSERTION

INSERT INTO `example`.`candidates` (`FirstName`, `LastName`)


VALUES ('James', 'Smith'),
('Maria ', 'Gracia'),
('Michael ', 'Rodriguez'),
('Robert ', 'Johnson'),
('David', 'Hernandez');
Assisted Practice: String Function

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

The numeric functions are used to perform numeric manipulation or


mathematical operations.

ABS ()

TRUNCATE () CEIL ()

String Functions

Numeric
functions

MOD () FLOOR ()
ABS Function

Definition Syntax

SELECT ABS (VALUE);

ABS function is used to return


the absolute value of a given
number.
ABS Example

Output

Example

SELECT ABS(Value) AS New_value


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

Output

Example

SELECT CEIL(Value) AS Ceil_value


Floor Function

Syntax
Definition
SELECT FLOOR(VALUE);

Floor function returns the largest


integer value that is less than or
equal to the given number.
Floor Example

Output

Example

SELECT FLOOR(Value) AS Floor_value


Truncate Function

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

SELECT TRUNCATE(Value,1) AS New_value


MOD Function

Definition
Syntax

MOD function returns the SELECT MOD (VALUE1 , VALUE2);


remainder of a number by dividing
it with another number.
MOD Example

Output

Example

SELECT MOD(Value,4) AS New_value


Problem Statement

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

SELECT Round(Profit, 1) as Profit_per_delivery_Round_off, Format(Profit, 3) as


Profit_per_delivery_Format, Truncate(Profit,2) as Profit_per_delivery_Truncate, ABS(Profit) as
Profiit_per_delivery_Absolute_Value, Ceil(Profit) as Profiit_per_delivery_Ceiling, Floor(Profit)
as Profiit_per_delivery_Floor
FROM example.superstore;
Output

The following output is generated after executing the query:


Problem Statement

Problem Scenario: As the junior database administrator, your manager has asked you to check if years
of experience is odd or even.

Objective: You are required to calculate the experience MOD 2.


Solution

Query

SELECT employee_id, exp,


CASE
WHEN MOD(exp, 2) = 0 THEN 'Even'
ELSE 'Odd'
END AS Exp_type
FROM employees;
Output

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

CREATE TABLE `example'.' bill` (


`S.no.` INT NOT NULL,
`Name` VARCHAR(255) NOT NULL,
`Amount` DECIMAL NOT NULL,
PRIMARY KEY (`S.no.`));
Assisted Practice: Numeric Function

2. Insert values in the bill table.

VALUE INSERTION

INSERT INTO `example`.`bill` (`S.no.`, `Name`, `Amount`)


VALUES ('1', 'Oliver', '2753.3491’),
('2', 'George', '2532.4082’),
('3', 'Arthur', '2021.5541’),
('4', 'Muhammad', '1934.9436’),
('5', 'Leo', '1846.2651’),
('6', 'Jack', '1244.0034’),
('7', 'Harry', '1187.0017');
Assisted Practice: Numeric Function

3. Write a query to perform round() function up to 0 and 2 decimal places and perform ceil() and
floor() functions.

QUERY

1.SELECT round(Amount, 0) 2.SELECT round(Amount, 2)


FROM example.bill; FROM example.bill;

3.SELECT ceil(Amount) 4.SELECT floor(Amount)


FROM example.bill; FROM example.bill;
Assisted Practice: Lab Output
Assisted Practice: Lab Output
Date and Time Functions
Date and Time Functions

It helps to extract the time, date, and year as per the requirement.

DATE () EXTRACT ()

String Functions

TIME () DATE FORMAT ()


Date Function

Definition Syntax

select date('expression');

Date function extracts the date


part from the given expression.
Date Example

Output

Example

SELECT DATE(Order_date) AS New_date


Time Function

Syntax
Definition
select time(expression);

Time function extracts the time


from the given expression.
Time Example

Output
Example

SELECT TIME(Order_time) AS New_time


Extract Function

Syntax
Definition
EXTRACT(part FROM expression)

Extract function extracts the date,


month, year, and time from the
given expression.
Extract Example

Output

Example

SELECT EXTRACT(YEAR_MONTH FROM


Order_date) AS New_YM;
Date Format Function

Syntax
Definition
select date_format(date, format_mask)

Date format function returns


the date in a specified format.
Date Format Example

Output

Example

SELECT DATE_FORMAT(Order_date, ‘%M:%Y’)


AS MY;
Problem Statement

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

SELECT Date(Return_Date_Time) as Return_Date, Time(Return_Date_Time) as Return_Time,


EXTRACT(YEAR FROM Return_Date_Time) AS Year, DATE_FORMAT(Return_Date_Time, '%M %d %Y') as
American_Date_Format
FROM example.return_products;
Output

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

Step 02: Insert values in the album table

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

Step 03: Write a query to display the contents of the table

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

The duplicate records can be handled in two ways:

• Using DISTINCT and COUNT keywords to fetch the number of unique records.

• Using COUNT and GROUP BY keywords to eliminate the 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

Using COUNT and GROUP BY keywords to eliminate the 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

SELECT Customer_ID , COUNT(DISTINCT Customer_ID) as Count


FROM example.superstore
GROUP BY Customer_ID;
Output

After executing the query, we get the list of unique customers.


Miscellaneous Functions
Miscellaneous Functions and Its Types

CONVERT

COALESCE IF

IFNULL ISNULL
Convert Function

Syntax
Definition
select CONVERT(value,datatype);

Convert function converts a value


into a specified data type.
Convert Example

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

SELECT ISNULL(Value) AS Null_Check;


IFNULL Function

Definition Syntax

• IFNULL function takes two


expression. select IFNULL(expression1,expression2)

• It returns the first expression if


the first expression is NOT NULL
otherwise returns the second
expression.
IFNULL Example

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

SELECT ISNULL(Return_Date_Time) as Check_NULL, IFNULL(Return_Date_Time,'Problem in the record')


as Return_Date_Time
FROM example.return_products;
Output

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

SELECT Convert(Quantity, Decimal(10,2)) as Decimal_Conversion, Profit,


IF((ABS(Profit))!=profit, 'LOSS', 'Profit') as Profit_LOSS
FROM example.superstore;
Output

After executing the query, we can check the profit or loss.


Problem Statement

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

SELECT *, COALESCE(Return_Date_Time,NULL,'NULL value',NULL,NULL,5) as COALESCE


FROM example.return_products;
Output

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

Step 02: Insert values in the product_sales table

Query

INSERT INTO product_sales(id, product, order_date, amount)


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

Step 03: Write a query to display the contents of the table

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 ( )

The correct answer is A

Sum function is an aggregate function.


Knowledge
Check
Which of the following works on each record independently?
2

A. Aggregate function

B. Scalar function

C. Date and time function

D. Numeric function
Knowledge
Check
Which of the following works on each record independently?
2

A. Aggregate function

B. Scalar function

C. Date and time function

D. Numeric function

The correct answer is B, C, and D.

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 ( )

The correct answer is B

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 ( )

The correct answer is A

Convert function helps to convert a value into specific data type.


Lesson-End Project: Patient Diagnosis Report

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.

Note: Download the patients_datasets.csv file from Course Resources to


perform the required tasks
Lesson-End Project: Patient Diagnosis Report

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

SQL functions are basic subprograms used extensively to handle or


manipulate data.

Aggregate functions allow performing the calculation on a set of


values to return a single scalar value.

Scalar functions return a single value from an input value. It works


on each record independently.

String functions are used for string manipulation.

Duplicate records can be handled by using the keywords- DISTINCT,


COUNT, and GROUP BY.

You might also like