Faculty of Computing
CS220: Database Systems
Class: BSCS-14
Lab08: Single Row Functions
Date: April 19th (Makeup class: March 20th ), 2025
Time: 9:00-12:00
Instructor: Ms. Hirra Anwar
Lab Engineer: Sundas Dawood
SUBMITTED BY:NOOR FATIMA
CMS ID:520191
CS-14B
CS220: Database Systems Page 1
Lab 8: Single Row Functions
Introduction
Structured Query Language (SQL) is a high level query language which has inbuilt operators and
functions for different presentation/manipulation of the data that is retrieved.
Objectives
After performing this lab students should be able to:
1. Design SQL queries to retrieve data using SELECT clause and using logical operators, SQL
operator precedence.
2. Explore and learn various inbuilt single row functions of SQL.
Tools/Software Requirement
MySQL Community Server
MySQL Workbench
Sakila Database
Description
The SQL SELECT DISTINCT Statement
In a table, a column may contain many duplicate values; and sometimes you only want to list
the different (distinct) values.
The DISTINCT keyword can be used to return only distinct (different) values.
SQL SELECT DISTINCT Syntax
SELECT DISTINCT column_name,column_name
FROM table_name;
CS220: Database Systems Page 2
The SQL WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified criterion.
SQL WHERE Syntax
SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
Example
The following SQL statement selects all the customers from the country "Mexico", in the
"Customers" table
SELECT * FROM Customers
WHERE Country='Mexico';
Text Fields vs. Numeric Fields
SQL requires single quotes around text values (most database systems will also allow double
quotes). However, numeric fields should not be enclosed in quotes
Example
SELECT * FROM Customers
WHERE CustomerID=1;
Single Row Functions
What is a function?
A function is similar to an operator in operation. A function is a name that performs a specific task. A
function may or may not take values (arguments) but it always returns a value as the result. If
function takes values then these values are to be given within parentheses after the function name.
The following is the general format of a function.
function [(argument-1, argument-2,...) ]
If the function doesn’t take any value then function name can be used alone and even parentheses are
not required.
Single-row functions return a single result row for every row of a queried table or view. These
functions can appear in select lists, WHERE clauses, START WITH and CONNECT BY clauses, and
HAVING clauses.
CS220: Database Systems Page 3
Arithmetic functions perform take numeric data; date functions take date type data and string
functions take strings. Conversion functions are used to convert the given value from one type to
another. Miscellaneous functions perform operations on any type of data. Group functions are used to
perform operations on the groups created by GROUP BY clause.
Character Functions
Character functions operate on values of dataype CHAR or VARCHAR.
Function Description
CHARACTER_LENGTH Returns the length of a string (in characters)
CONCAT Adds two or more expressions together
CONCAT_WS Adds two or more expressions together with a
separator
INSERT Inserts a string within a string at the specified
position and for a certain number of characters
LCASE Converts a string to lower-case
LEFT Extracts a number of characters from a string
(starting from left)
CS220: Database Systems Page 4
LOWER Converts a string to lower-case
LPAD Left-pads a string with another string, to a certain
length
LTRIM Removes leading spaces from a string
MID Extracts a substring from a string (starting at any
position)
POSITION Returns the position of the first occurrence of a
substring in a string
REPEAT Repeats a string as many times as specified
REPLACE Replaces all occurrences of a substring within a
string, with a new substring
REVERSE Reverses a string and returns the result
RIGHT Extracts a number of characters from a string
(starting from right)
RPAD Right-pads a string with another string, to a
certain length
RTRIM Removes trailing spaces from a string
CS220: Database Systems Page 5
SPACE Returns a string of the specified number of space
characters
STRCMP Compares two strings
SUBSTR Extracts a substring from a string (starting at any
position)
SUBSTRING Extracts a substring from a string (starting at any
position)
SUBSTRING_INDEX Returns a substring of a string before a specified
number of delimiter occurs
TRIM Removes leading and trailing spaces from a string
UCASE Converts a string to upper-case
UPPER Converts a string to upper-case
LOWER
Returns a given string in lower case.
select LOWER(first_name)
from actor;
CS220: Database Systems Page 6
UPPER
Returns a given string in UPPER case.
select UPPER(first_name)
from actor;
LENGTH
Returns the length of a given string.
select length(first_name)
from actor;
CONCAT(str1,str2,...)
Returns the string that results from concatenating the arguments. May have one or more arguments.
SELECT CONCAT('My', 'S', 'QL');
+---------------------------------------------------------+
| CONCAT('My', 'S', 'QL') |
+---------------------------------------------------------+
MySQL
CONCAT_WS(separator,str1,str2,...)
CONCAT_WS() stands for Concatenate With Separator and is a special form of CONCAT(). The
first argument is the separator for the rest of the arguments. The separator is added between the
strings to be concatenated. The separator can be a string, as can the rest of the arguments. If the
separator is NULL, the result is NULL.
SELECT CONCAT_WS(',','First name','Last Name' );
+---------------------------------------------------------+
| CONCAT_WS(',','First name','Last Name' ) |
+---------------------------------------------------------+
| First name, Last Name |
CS220: Database Systems Page 7
LPAD(str,len,padstr)
Returns the string str, left-padded with the string padstr to a length of len characters. If str is longer
than len, the return value is shortened to len characters.
SELECT LPAD('hi',4,'??');
+---------------------------------------------------------+
| LPAD('hi',4,'??') |
+---------------------------------------------------------+
| ??hi |
+---------------------------------------------------------+
RPAD(str,len,padstr)
Returns the string str, right-padded with the string padstr to a length of len characters. If str is longer
than len, the return value is shortened to len characters.
SELECT RPAD('hi',5,'?');
+---------------------------------------------------------+
| RPAD('hi',5,'?') |
+---------------------------------------------------------+
| hi??? |
+---------------------------------------------------------+
LTRIM(str)
Returns the string str with leading space characters removed.
SELECT LTRIM(' lecture');
+---------------------------------------------------------+
| LTRIM(' lecture') |
+---------------------------------------------------------+
| lecture |
+---------------------------------------------------------+
CS220: Database Systems Page 8
REPEAT(str,count)
Returns a string consisting of the string str repeated count times. If count is less than 1, returns an
empty string. Returns NULL if str or count are NULL.
SELECT REPEAT('MySQL', 3);
+---------------------------------------------------------+
| REPEAT('MySQL', 3) |
+---------------------------------------------------------+
| MySQLMySQLMySQL |
+---------------------------------------------------------+
RTRIM(str)
Returns the string str with trailing space characters removed.
SELECT RTRIM('barbar ');
+---------------------------------------------------------+
| RTRIM('barbar ') |
+---------------------------------------------------------+
| barbar |
+---------------------------------------------------------+
SUBSTRING(str,pos)
SUBSTRING(str FROM pos)
SUBSTRING(str,pos,len)
SUBSTRING(str FROM pos FOR len)
The forms without a len argument return a substring from string str starting at position pos. The
forms with a len argument return a substring len characters long from string str, starting at position
pos. The forms that use FROM are standard SQL syntax. It is also possible to use a negative value
for pos. In this case, the beginning of the substring is pos characters from the end of the string, rather
than the beginning. A negative value may be used for pos in any of the forms of this function.
CS220: Database Systems Page 9
SELECT SUBSTRING('Quadratically',5);
+---------------------------------------------------------+
| SSUBSTRING('Quadratically',5) |
+---------------------------------------------------------+
| ratically |
+---------------------------------------------------------+
> SELECT SUBSTRING('foobarbar' FROM 4);
+---------------------------------------------------------+
| SUBSTRING('foobarbar' FROM 4) |
+---------------------------------------------------------+
| barbar |
+---------------------------------------------------------+
> SELECT SUBSTRING('Quadratically',5,6);
+---------------------------------------------------------+
| SUBSTRING('Quadratically',5,6) |
+---------------------------------------------------------+
| ratica |
+---------------------------------------------------------+
MySQL Numeric Functions
Function Description
ABS Returns the absolute value of a number
ACOS Returns the arc cosine of a number
ASIN Returns the arc sine of a number
CS220: Database Systems Page 10
ATAN Returns the arc tangent of one or two numbers
ATAN2 Returns the arc tangent of two numbers
AVG Returns the average value of an expression
CEIL Returns the smallest integer value that is >= to a
number
CEILING Returns the smallest integer value that is >= to a
number
COS Returns the cosine of a number
COT Returns the cotangent of a number
COUNT Returns the number of records returned by a select
query
DEGREES Converts a value in radians to degrees
DIV Used for integer division
EXP Returns e raised to the power of a specified number
FLOOR Returns the largest integer value that is <= to a
number
CS220: Database Systems Page 11
GREATEST Returns the greatest value of the list of arguments
LEAST Returns the smallest value of the list of arguments
LN Returns the natural logarithm of a number
LOG Returns the natural logarithm of a number, or the
logarithm of a number to a specified base
LOG10 Returns the natural logarithm of a number to base 10
LOG2 Returns the natural logarithm of a number to base 2
MAX Returns the maximum value in a set of values
MIN Returns the minimum value in a set of values
MOD Returns the remainder of a number divided by another
number
PI Returns the value of PI
POW Returns the value of a number raised to the power of
another number
POWER Returns the value of a number raised to the power of
another number
CS220: Database Systems Page 12
RADIANS Converts a degree value into radians
RAND Returns a random number
ROUND Rounds a number to a specified number of decimal
places
SIGN Returns the sign of a number
SIN Returns the sine of a number
SQRT Returns the square root of a number
SUM Calculates the sum of a set of values
TAN Returns the tangent of a number
TRUNCATE Truncates a number to the specified number of decimal
places
MySQL Date Functions
Function Description
ADDDATE Adds a time/date interval to a date and then
CS220: Database Systems Page 13
returns the date
ADDTIME Adds a time interval to a time/datetime and then
returns the time/datetime
CURDATE Returns the current date
CURRENT_DATE Returns the current date
CURRENT_TIME Returns the current time
CURRENT_TIMESTAMP Returns the current date and time
CURTIME Returns the current time
DATE Extracts the date part from a datetime
expression
DATEDIFF Returns the number of days between two date
values
DATE_ADD Adds a time/date interval to a date and then
returns the date
DATE_FORMAT Formats a date
DATE_SUB Subtracts a time/date interval from a date and
then returns the date
CS220: Database Systems Page 14
DAY Returns the day of the month for a given date
DAYNAME Returns the weekday name for a given date
DAYOFMONTH Returns the day of the month for a given date
DAYOFWEEK Returns the weekday index for a given date
DAYOFYEAR Returns the day of the year for a given date
EXTRACT Extracts a part from a given date
FROM_DAYS Returns a date from a numeric datevalue
HOUR Returns the hour part for a given date
LAST_DAY Extracts the last day of the month for a given
date
LOCALTIME Returns the current date and time
LOCALTIMESTAMP Returns the current date and time
MAKEDATE Creates and returns a date based on a year and
a number of days value
MAKETIME Creates and returns a time based on an hour,
CS220: Database Systems Page 15
minute, and second value
MICROSECOND Returns the microsecond part of a time/datetime
MINUTE Returns the minute part of a time/datetime
MONTH Returns the month part for a given date
MONTHNAME Returns the name of the month for a given date
NOW Returns the current date and time
PERIOD_ADD Adds a specified number of months to a period
PERIOD_DIFF Returns the difference between two periods
QUARTER Returns the quarter of the year for a given date
value
SECOND Returns the seconds part of a time/datetime
SEC_TO_TIME Returns a time value based on the specified
seconds
STR_TO_DATE Returns a date based on a string and a format
SUBDATE Subtracts a time/date interval from a date and
then returns the date
CS220: Database Systems Page 16
SUBTIME Subtracts a time interval from a datetime and
then returns the time/datetime
SYSDATE Returns the current date and time
TIME Extracts the time part from a given
time/datetime
TIME_FORMAT Formats a time by a specified format
TIME_TO_SEC Converts a time value into seconds
TIMEDIFF Returns the difference between two
time/datetime expressions
TIMESTAMP Returns a datetime value based on a date or
datetime value
TO_DAYS Returns the number of days between a date and
date "0000-00-00"
WEEK Returns the week number for a given date
WEEKDAY Returns the weekday number for a given date
WEEKOFYEAR Returns the week number for a given date
YEAR Returns the year part for a given date
CS220: Database Systems Page 17
YEARWEEK Returns the year and week number for a given
date
CS220: Database Systems Page 18
Structure Query Language has been supported with many built-in functions. These functions
facilitate the developers for efficient query designing and retrieving data as per specific
requirement to build required reports.
LAB TASKS
Consider the given list of functions from different categories, analyze their working
and test them on sakila data.
CS220: Database Systems Page 19
FUNCTION 1:
LPAD:
INPUT:
SELECT LPAD(last_name, 10, first_name)
from customer;
OUTPUT:
FUNCTION 2:
RTRIM:
INPUT:
SELECT rtrim(city)
from city;
CS220: Database Systems Page 20
OUTPUT:
FUNCTION3 :
CONCAT:
INPUT:
select concat(first_name,' ',last_name)
from actor;
OUTPUT:
CS220: Database Systems Page 21
Revision Tasks
Write SQL queries for the following information needs. You should execute your
attempt
and make necessary corrections if needed.
Information needs:
a) Retrieve unique first and last names of actors.
INPUT:
select distinct first_name, last_name
from actor;
OUTPUT:
CS220: Database Systems Page 22
b) Retrieve all payments over and above $10 made during 14-22 August 2005.
INPUT:
select *
from payment
where amount>10 and payment_date between '2005-08-14' and
'2005-08-22';
OUTPUT:
c) Find all films of more than two and half hour length and not rated PG-13.
INPUT:
select *
from film
where length>'150' and rating <> 'PG-13';
CS220: Database Systems Page 23
OUTPUT:
d) Find ten lengthiest films featuring “Behind the Scenes”.
INPUT:
select film_id, title, special_features
from film
where special_features like 'Behind the Scenes'
order by film_id
limit 10;
OUTPUT:
e) List id, title, rental rate, and replacement cost of all films below $1 rental value.
Sort the list on descending order of replacement cost.
INPUT:
CS220: Database Systems Page 24
select film_id, rental_rate , replacement_cost
from film
where rental_rate<1
order by replacement_cost DESC;
OUTPUT:
Given is the Scenario for ERD: A University contains many Faculties. The Faculties in turn
are divided into several Schools. Each School offers numerous programs and each program
contains many courses. Lecturers can teach many different courses and even the same course
numerous times. Courses can also be taught by many lecturers. A student is enrolled in only
one program but a program can contain many students. Students can be enrolled in many
courses at the same time and the courses have many students enrolled.
NOTE: ERD concepts
Entities (strong and weak entities), attributes (composite, derived, multivalued, key attributes)
Relationships (1:1, 1:M, M:M) with cardinality and modality using crowfoot notation
SCENARIO 1: UNIVERSITY MANAGEMENT SYSTEM
A university wants to develop a system to manage its academic operations. The system will
store information about students, instructors, courses, and enrollments. Each student has a
unique student ID, name, email, and date of birth, while each instructor has an instructor ID,
name, and department. Students enroll in various courses, and each course is taught by one
instructor. In the enhanced ERD, students are further specialized into undergraduate and
graduate students. Undergraduate students are associated with a specific program and year,
while graduate students have a thesis topic and a supervisor. To simplify management, both
CS220: Database Systems Page 25
students and instructors are generalized into a common superclass called Person, which
includes shared attributes like name, email, and date of birth.
ENTITIES:
Student
Instructor
Courses
ATTRIBUTES:
ATTRIBUTES OF STUDENT:
Student_Id(PK)
Name(Composite attribute)
Email
Date of Birth
ATTRIBUTES OF INSTRUCTOR:
Instructor_id(PK)
Name(Composite Attribute)
Email
Date of Birth
ATTRIBUTES OF COURSES:
Course_id
CourseName
RELATIONSHIPS:
Student-Enrolls in-Courses(M:N)
Instructor-Takes-Courses(1:M)
ERD:
CS220: Database Systems Page 26
SCENARIO 3: E-COMMERCE SYSTEM
An e-commerce company is building a platform to manage online shopping activities. The system
tracks customers, products, orders, and payments. Each customer has a unique ID, name, and
email, and can place multiple orders. Products are identified by a product ID, name, and price,
and can appear in multiple orders. Each order includes a date and total amount and is associated
with a payment. In the enhanced ERD, payments are specialized into CreditCardPayments and
PayPalPayments. Credit card payments include card number and expiry date, while PayPal
payments include a PayPal email. Furthermore, both customers and admin users are generalized
under a single User entity with common attributes like name, email, and address.
ERD:
CS220: Database Systems Page 27
Deliverable
Submit a PDF document including the SQL queries to answer above-mentioned information needs as
well as snapshot of their outcome when executed over MySQL using the Workbench.
CS220: Database Systems Page 28
Rubrics
Assessment Does not Meets Exceeds
meet Expectations expectations
expectations
(3/4) (5)
(1/2)
How well the student The student The student has The student has
is able to describe the poorly fair knowledge of in depth
problem and develop
describes the the tool and understanding of
solution using tools
for database problem and describes the the tools and use
design methods problem with appropriate tool
with poor logically to describe logical
understanding developed design methods
of the tool. methods. for databases.
Ethics and Adherence The student does The student partially The student clearly
to Laboratory Safety not demonstrate demonstrates demonstrates
Rules commitment to commitment to commitment to
professional ethics professional ethics by professional ethics by
by following following ethical following ethical
ethical norms norms applicable to norms applicable to
applicable to the the software industry the software industry
software industry such as referencing such as referencing
such as and and
referencing and acknowledgement acknowledgement
acknowledgement while using publicly while using publicly
while using available data/ code. available data/ code.
publicly available Does not disturb the Encourages others to
data/ code. lab environment, maintain lab
Disturbs the lab takes care of safety decorum, and alerts
environment, measures, and is them to follow safety
doesn’t take care punctual. measures.
of safety
measures, and/or
isn’t punctual.
CS220: Database Systems Page 29