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

Lab 5 SQL SELECT With Functions, Aggregate Functions

This document provides an overview of SQL functions that can be used to manipulate and summarize data in a database. It discusses date functions, string functions, numeric functions, and aggregate functions. Date functions allow manipulation of date formats and calculations. String functions allow adding, changing, and finding parts of text. Numeric functions allow formatting or manipulating numbers. Aggregate functions summarize query results by calculating values like counts, averages, minimums, and maximums. The lab aims to help students learn and practice using these SQL functions to transform and analyze data in a database.

Uploaded by

Misbah Ullah
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

Lab 5 SQL SELECT With Functions, Aggregate Functions

This document provides an overview of SQL functions that can be used to manipulate and summarize data in a database. It discusses date functions, string functions, numeric functions, and aggregate functions. Date functions allow manipulation of date formats and calculations. String functions allow adding, changing, and finding parts of text. Numeric functions allow formatting or manipulating numbers. Aggregate functions summarize query results by calculating values like counts, averages, minimums, and maximums. The lab aims to help students learn and practice using these SQL functions to transform and analyze data in a database.

Uploaded by

Misbah Ullah
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Lab Manual for Introduction to Database Systems

Lab-04
SQL SELECT WITH FUNCTION
Lab 4: SQL SELECT WITH FUNCTION

Table of Contents
1. Introduction 60

2. Activity Time boxing 60

3. Objective of the experiment 60

4. Concept Map 61

4.1. Date/Time Functions 61

4.2. String Functions 61

4.2.1. Adding text to an existing value 61

4.2.2. Changing Part of a String 62

4.2.3. Finding a piece of text in a string. 62

4.3. Numeric Functions 63

4.4. Aggregate/Summarizing Functions 63

4.5.1. AVG() 64

4.5.2. MIN() and MAX() 64

4.5.3. SUM() 65

4. Homework before Lab 65

5.1. Problem Solution Modeling 65

5.1.1. Problem description: 65

5. Procedure& Tools 65

6.1. Tools 66

6.2. Setting-up and Setting up XAMPP (MySQL, Apache) [Expected time =


5mins] 66

6.3. Walkthrough Task [Expected time = 30mins] 66

6.3.1. String Functions 66

6.3.2. Date/Time Functions 66

Department of Computer Page 58


Science, C.U.S.T.
Lab 4: SQL SELECT WITH FUNCTION

6.3.3. Numeric Functions 67

6.3.4. Aggregate/Summarizing Functions 67

6. Practice Tasks 67

7.1. Practice Task 1 [Expected time = 40mins] 67

7. Evaluation Task (Unseen) [Expected time = 55mins for two tasks] 68

8. Evaluation criteria 68

9. Further Reading 68

10. Books 68

b) Slides 68

11. REFERENCES: 68

Department of Computer Page 59


Science, C.U.S.T.
Lab 4: SQL SELECT WITH FUNCTION

Lab4: SQL SELECT with functions


1. Introduction
This lab is a continuation of the last lab. So far, we have learned how to query subset of data
from the database using SELECT statement, we have simply displayed the results of any query.
MySQL can do more that this and has many built in functions that can transform data to meet our
requirements. These include:

 Date Functions are used to manipulate the display format of a date as well as calculate time.
i.e. Formatting the date using DATE_FORMAT() function, or getting year from date using
YEAR() function.
 String Functions can format or manipulate a text string. i.e. Adding text to an existing value
using CONCAT() function or getting a substring from text using RIGHT, LEFT, or MID
functions.
 Numeric Functions can format or manipulate figures/numbers. i.e. getting floor or ceiling
value using FLOOR() or CEILING() functions respectively.
 Aggregate/Summarizing Functions are used to get a summarized/aggregate result from a
query. i.e. counting the number of rows in the ResultSet of a query using COUNT() function.

There are also Control Functions that can be used to give conditionality to queries. In this lab,
you can learn about the select command using functions.

Relevant Lecture Material

a) Revise Lecture No. 7 and 8


b) Text Book: Java: Text Book: Database Systems, A practical approach to design,
implementation and management by Thomas Connolly, Carolyn Begg, Addison
Wesley, Fifth Edition,
1. Read URL: http://www.w3schools.com/sql/sql_having.asp
2. Revise the SQL SELECT with functions, GROUP BY, HAVING,
aggregate functions)

2. Activity Time boxing


Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
6.2 Setting-up and Setting Up 5mins 5mins
XAMPP (MySQL, Apache)
6.3 Walkthrough Tasks 30mins 60mins
7 Practice tasks 20 to 30mins for each task 50mins
8 Evaluation Task 40mins for all assigned task 40mins

3. Objective of the experiment


• To get basic understanding of MySQL functions i.e. DATE functions, String function,
Numeric functions, and Aggregate functions.

Department of Computer Page 60


Science, C.U.S.T.
Lab 4: SQL SELECT WITH FUNCTION

• To get familiar with querying a database using SELECT statement with functions.

4. Concept Map
In this section, a brief overview of the concepts is presented, those will be used in this lab
afterwards. MySQL has many built in functions that can transform data to meet our
requirements. These include:

 Date Functions
 String Functions
 Numeric Functions
 Aggregate/Summarizing Functions

The following sections describe each category one by one.

4.1. Date/Time Functions


MySQL provides these built-in functions for getting the current date, time and datetime:

 NOW: returns the current date and time in the format of 'YYYY-MM-DD HH:MM:SS'.
 CURDATE (or CURRENT_DATE(), or CURRENT_DATE): returns the current date in the
format of 'YYYY-MM-DD'.
 CURTIME (or CURRENT_TIME(), or CURRENT_TIME): returns the current time in the
format of 'HH:MM:SS'.

4.2. String Functions


String values are can be explained as 'bits of text' and much like the date functions, the string
functions allow us to manipulate these values before they are displayed. Although there are once
more many different functions, we are going to concentrate on the functions that fall into a few
broad categories.
 Adding text to an existing value
 Changing Part of a String
 Finding a piece of text in a string

4.2.1. Adding text to an existing value


There are two simple ways to add more text to an existing value - either at the start or end of the
text. Placing the text at either end is best achieved with the CONCAT() function.
Syntax:

CONCAT(string1,string2,...)

Thus we can take an existing value (say string2) and place a new value (string1) at the
beginning to get string1string2.
For example: concat employee name and job title of employees

Department of Computer Page 61


Science, C.U.S.T.
Lab 4: SQL SELECT WITH FUNCTION

Figure 1: Concat strings

4.2.2. Changing Part of a String


As well as add text we can replace it or overwrite it completely. To replace an instance of text
within a string we can use the REPLACE() function.
Syntax:

REPLACE(whole_string,to_be_replaced,replacement)

For Example: Replace the name of Salman to Hasnat then can use Replace Function for replace
the result set string.

Figure 2: Replace String

4.2.3. Finding a piece of text in a string.


In some of the string functions we have seen so far it has been necessary to provide a starting
position as part of the function This position can be found using the LOCATE() function
specifying the text to find (substring) as well as the string to search in.
Syntax:

LOCATE(substring,string)

For Example: locate the string “Salman” in employee name attribute so

Department of Computer Page 62


Science, C.U.S.T.
Lab 4: SQL SELECT WITH FUNCTION

Figure 3: Locate Function

4.3. Numeric Functions


Before talking about the specific numeric functions, it is probably worth mentioning that MySQL
can perform simple math functions using mathematical operators.

Operator Function
+ Add
- Subtract
* Multiply
/ Divide
Examples:

Figure 4: Numeric Function

4.4. Aggregate/Summarizing Functions


Aggregate function performs a calculation on a set of values and returns a single value.
MySQL provides many aggregate functions that include AVG, COUNT, SUM, MIN, MAX, etc.
An aggregate function ignores NULL values when it performs calculation except for the
COUNT function.COUNT()
This counts the number of times a row (or field) is returned.
Syntax:

COUNT(field)

For Example: If count the all rows of employee table then use count function

Department of Computer Page 63


Science, C.U.S.T.
Lab 4: SQL SELECT WITH FUNCTION

Figure 5: Count Function

4.5.1. AVG()
The next function we are going to look at is the AVG() which unsurprisingly is the average
function.
Syntax:

AVG(field)

For Example: Show the average salary of employees which is given in Figure 6

Figure 6: AVG Function

4.5.2. MIN() and MAX()


These functions are very similar and select the lowest and highest figure respectively from a
result set.
Syntax:

MIN(field)
MAX(field)

For Example: show the min and max salary of employee which is given in Figure 7

Department of Computer Page 64


Science, C.U.S.T.
Lab 4: SQL SELECT WITH FUNCTION

Figure 7: MIN MAX Function

4.5.3. SUM()
The final summary function that we will look at is the SUM() function which adds rows of one
field in the results set together.
Syntax:

SUM(field)

For Example: Show the sum of all salary which is given in Figure 8

Figure 8: SUM Function

4.1. SELECT Advanced


You have learned how to select a subset of data called Result Set in previous lab. To select data
according to the requirements There are more techniques available to retrieve the data according
to our need i.e. sorting the result set, limiting records, Grouping etc. In this lab, you will learn
three clauses i.e. ORDER BY, DISTINCT, and LIMIT for better selection of the records from a
database.

4.1.1. Sorting the ResultSet with ORDER BY Clause


You can order the rows selected using ORDER BY clause with SELECT statement, with the
following syntax:

SELECT column1,…,columnN FROM tableName


WHERE criteria
ORDER BY columnA ASC|DESC, columnB ASC|DESC, ...

The selected row will be ordered according to the values in columnA, in either ascending (ASC)
(default) or descending (DESC) order. If several rows have the same value in columnA, it will be

Department of Computer Page 65


Science, C.U.S.T.
Lab 4: SQL SELECT WITH FUNCTION

ordered according to columnB, and so on.

For Example, to select officeCode, city, and country of all offices and sort the result set by
country in ascending order, the following statement can be written:

SELECT officeCode, city, country


FROM offices
Order BY country

+------------+--------------+-----------+
| officecode | city | country |
+------------+--------------+-----------+
|6 | Sydney | Australia |
|4 | Paris | France |
|5 | Tokyo | Japan |
|7 | London | UK |
|2 | Boston | USA |
|3 | NYC | USA |
|1 | San Francisco | USA |
+------------+---------------+-----------+

4.1.2. Limiting the Result Set using LIMIT Clause


A SELECT query on a large database may produce many rows. The LIMIT clause can be used to
show specific number of records from a result set, the syntax is:

SELECT column1,…,columnN FROM tableName


[WHERE criteria]
[ORDER BY columnA ASC|DESC, columnB ASC|DESC, ...]
[LIMIT [offset,] no_of_rows ]

Offset is the index of record in the result set, indexes starts from zero (0).
For Example, to show office code, city, and country of first three offices of the result set, the
following statement can be written:

SELECT officeCode, city, country


FROM offices
LIMIT 3

+------------+-----------------+-----------+
| officecode | city | country |
+------------+-----------------+-----------+
|1 | San Francisco | USA |
|2 | Boston | USA |
|3 | NYC | USA |
+------------+-----------------+-----------+

Department of Computer Page 66


Science, C.U.S.T.
Lab 4: SQL SELECT WITH FUNCTION

To show office code, city, and country of 2 nd to 4th offices of the result set, an offset can be
defined along with required number of rows, the following statement can be written:

SELECT officeCode, city, country


FROM offices
LIMIT 1,3

+------------+-----------------+-----------+
| officecode | city | country |
+------------+-----------------+-----------+
|2 | Boston | USA |
|3 | NYC | USA |
|4 | Paris | France |
+------------+-----------------+-----------+

4.1.3. Listing distinct elements of a column using DISTINCT keyword


A column may have duplicate values, DISTINCT keyword can be used to select only distinct
values.
For examples,

The following statement gives price of all products.


SELECT price FROM products;
+-------+
| price |
+-------+
| 1.23 |
| 1.25 |
| 1.25 |
| 0.48 |
| 0.49 |
+-------+

We can see duplicated in price column price. To get only the unique elements write the
following statement.

Department of Computer Page 67


Science, C.U.S.T.
Lab 4: SQL SELECT WITH FUNCTION

SELECT DISTINCT price AS `Distinct Price` FROM products;


+----------------+
| Distinct Price |
+----------------+
| 1.23 |
| 1.25 |
| 0.48 |
| 0.49 |
+----------------+

4. Homework before Lab

You must solve the following problems at home before the lab.

5.1. Problem Solution Modeling


After reading the reference material mentioned in the introduction, now you are ready to perform
homework assigned to you.

5.1.1. Problem description:


Describe the date functions, string functions, numeric functions, aggregate/summarizing
functions and its purpose. You must create at least 10 examples of group by and having clause
other than your practice tasks, submit to lab teacher in hard form.

5. Procedure& Tools
In this section, you will study how to make and run a customized exception.

6.1. Tools

In this section tools installation and setup is defined.

6.2. Setting-up and Setting up XAMPP (MySQL, Apache) [Expected time =


5mins]

Refer to Lab 1 sec 6.2.

6.3. Walkthrough Task [Expected time = 30mins]


6.3.1. String Functions
String Functions can format or manipulate a text string. You can concatenate a few columns as
one (e.g., joining the last name and first name) using function CONCAT (). For example,

Department of Computer Page 68


Science, C.U.S.T.
Lab 4: SQL SELECT WITH FUNCTION

Figure 9: CONCAT Function

6.3.2. Date/Time Functions

Figure 10: Date Time Function

6.3.3. Numeric Functions

Figure 11: Numeric Function

6.3.4. Aggregate/Summarizing Functions


If count the all rows of employee table then use count function

Department of Computer Page 69


Science, C.U.S.T.
Lab 4: SQL SELECT WITH FUNCTION

Figure 12: Aggregate Function

6. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the
following folder:
\\dataserver\assignments$\Teacher Name\Introduction To Databases\Lab4

7.1. Practice Task 1 [Expected time =


40mins]
Consider the schema given in Lab01 (7.1 Practice Task), write down following SQL queries.
1. Show all the products ordered by product name and quantity of products
2. Show all the products whose half price is greater than 500
3. Show total price of all products.
4. Show order number, total products ordered, and total price for order number “10103”
5. Show name, and job title of all employees who reports directly to 1002.
6. What is the minimum payment received?
7. Which orders have a value greater than 5,000?
8. List the product lines that contain 'Cars' and concatenation with product code.
9. List the products in each product line.

7. Evaluation Task (Unseen) [Expected time = 55mins for two tasks]


The lab instructor will give you unseen task depending upon the progress of the class.

8. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks
1 6 Procedures and Tools 05
2 7 Practice tasks and Testing 15
3 8 Evaluation Tasks (Unseen) 80

Department of Computer Page 70


Science, C.U.S.T.
Lab 4: SQL SELECT WITH FUNCTION

9. Further Reading
This section provides the references to further polish your skills.

10. Books
a) Text Book:
 Database Systems, A practical approach to design, implementation and management
by by Thomas Connolly, Carolyn Begg, Addison Wesley , Fifth Edition,

b) Slides
 The slides and reading material can be accessed from the folder of the class instructor
available at \\dataserver\jinnah$\

11. REFERENCES:
SQL-99 Complete, Really, by Peter Gulutzan & Trudy Pelzer.
 More examples for the SELECT command:
http://dev.mysql.com/doc/mysql/en/select.html
 MySQL operators:
http://dev.mysql.com/doc/mysql/en/non-typed_operators.html
 Built-in functions:
http://dev.mysql.com/doc/mysql/en/functions.html
 Joining tables:
http://www.melonfire.com/community/columns/trog/article.php?id=148
 Using subqeries:
http://www.melonfire.com/community/columns/trog/article.php?id=204

Department of Computer Page 71


Science, C.U.S.T.

You might also like