Lab 6: Views and SQL Functions
Lab 6: Views and SQL Functions
Lab 6: Views and SQL Functions
6.1 Views
A view is a virtual table based on a SELECT query. The query can contain columns, computed
columns, aliases, and aggregate functions from one or more tables. The tables on which the
view is based are called base tables. You can create a view by using the CREATE VIEW
command:
The CREATE VIEW statement is a data definition command that stores the subquery
specification—the SELECT statement used to generate the virtual table—in the data
dictionary. For example, to create a view to display the employees first and last name
(EMP_FNAME and EMP_LNAME), the attraction number (ATTRACT_NO) and the date
ON E.EMP_NUM = H.EMP_NUM;
1
SELECT * FROM EMP_WORKED;
• You can use the name of a view anywhere a table name is expected in a SQL
statement
• Views are dynamically updated. That is, the view is re-created on demand each
time it is invoked.
• Views provide a level of security in the database because the view can restrict users
to only specified columns and specified rows in a table
To remove the view EMP_WORKED you could issue the following command
DROP VIEW EMP_WORKED;
2
6.2 Views – using the WITH CHECK OPTION
It is possible to perform referential integrity constraints through the use of a view so that database
constraints can be enforced. The following view DISPLAYS employees who work in Theme Park
FR1001 using the WITH CHECK OPTION clause. This clause ensures that INSERTs and
UPDATEs cannot be performed on any rows that the view has not selected. The results of creating
this view can be seen in Figure 79.
SELECT *
FROM EMPLOYEE
So for example if employee ‘Emma Caulderdale’ was to leave the park and move to park
‘UK3452’, we would want to update her information with the following query:
3
UPDATE EMPFR
However running this update gives the errors shown in Figure 80. This is because if the
update was to occur, the view would no longer be able to see this employee.
Advantages of Views:
I. Simplify complex Query:
Views help simplify complex queries. If you have any frequently used complex query,
you can create a view based on it so that you can reference to the view by using a
simple SELECT statement instead of typing the query all over again.
4
5
SQL Functions:
There are many types of SQL functions, such as arithmetic, trigonometric, string, date, and
time functions. Lab 6 will cover a selection of these SQL functions that are implemented in
MySQL in detail. Functions always use a numerical, date, or string value. The value may be
part of the command itself (a constant or literal) or it may be an attribute located in a table.
important to briefly look at the main date and time types are available to MySQL. These are
As you can see from Table 6.1, the DATE type is stored in a special internal format that
includes just the year, month and day whilst the DATETIME data type also stores the
hours, minutes, and seconds. If you try to enter a date in a format other than the Year-
Month-Day format then it might work, but it won't be storing them as you expect!
Task 6.1 Enter the following query and examine how the date is displayed.
SELECT DISTINCT(SALE_DATE )
FROM SALES;
6
It is possible to change the format of the date using the DATE_FORMAT() function. The
DATE_FORMAT(date,format)
The function formats the date value according to the format string.
For example, the following query formats the date as 18th May 2007 using ‘ date
FROM SALES;
Table 6.2 taken directly from the MySQL Manual 5.0 shows a complete list of specifiers
7
Specifier Description
%a Abbreviated weekday name (Sun..Sat)
%b Abbreviated month name (Jan..Dec)
%c Month, numeric (0..12)
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, …)
%d Day of the month, numeric (00..31)
%e Day of the month, numeric (0..31)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
%I Hour (01..12)
%i Minutes, numeric (00..59)
%j Day of year (001..366)
%k Hour (0..23)
%l Hour (1..12)
%M Month name (January..December)
%m Month, numeric (00..12)
%p AM or PM
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
%S Seconds (00..59)
%s Seconds (00..59)
%T Time, 24-hour (hh:mm:ss)
%U Week (00..53), where Sunday is the first day of the week
%u Week (00..53), where Monday is the first day of the week
%V Week (01..53), where Sunday is the first day of the week; used with %X
%v Week (01..53), where Monday is the first day of the week; used with %x
%W Weekday name (Sunday..Saturday)
%w Day of the week (0=Sunday..6=Saturday)
%X Year for the week where Sunday is the first day of the week, numeric, four
digits; used with %V
%x Year for the week, where Monday is the first day of the week, numeric, four
digits; used with %v
%Y Year, numeric, four digits
%y Year, numeric (two digits)
%% A literal ‘%’ character
%x x, for any ‘x’ not listed above
You will now explore some of the main MySQL date / time functions.
CURRENT DATE and CURRENT TIME
8
Task 6.3 Enter the following query to display today’s date and time. Notice that in
MySQL the functions are called using the SELECT statement but no FROM clause is
needed.
Note
MySQL provides functions for extracting the month, day or year from any given date.
DAYOFMONTH(date) returns the day of the month for date, in the range 0 to 31.
YEAR(date) returns the year for date, in the range 1000 to 9999, or 0 for the “zero” date.
The following query shows how these three functions can be used to display different
parts of an employee’s date of birth. The output of this query is shown in Figure 57.
9
SELECT DAYOFMONTH(EMP_DOB) AS “Day”, MONTH(EMP_DOB) AS “Month”,
YEAR(EMP_DOB) AS “Year”
FROM EMPLOYEE;
Task 6.4 Write a query that displays all employees who were born in November. Your
10
DATEDIFF
The DATEDIFF function subtracts two dates and returns a value in days from one date to the
other. The following example calculates the number of days between the 1st January 2008
SELECT DATEDIFF(‘2008-12-25’,‘2008-01-01’);
Task 6.5 Enter the query above and see how many days it is until the 25th December. Then
modify the query to see how many days it is from today’s date until 25th December 2009.
The DATE_ADD and DATE_SUB functions both perform date arithmetic and allow you to
either add or subtract two dates from one another. The syntax of these functions is:
Where expr is an expression specifying the interval value to be added or subtracted from the
starting date and unit is a keyword indicating the units in which the expression should be
interpreted.
For example, the following query adds 11 months to the date 1st January 2008 to display a
new date of 1st December 2008. The output for this query is shown in Figure 59.
11
SELECT ADDDATE(‘2008-01-01’, INTERVAL 11 MONTH );
A full list of the different interval types can be found in the MySQL Reference Manual
5.0.
Task 6.6 Enter the following query which lists the hire dates of all employees along with
the date of their first work appraisal (one year from the hiredate). Check that the output is
correct.
FROM EMPLOYEE;
LAST_DAY
The function LAST_DAY returns the date of the last day of the month given in a date.
The syntax is
LAST_DAY(date_value).
12
Task 6.7 Enter the following query which lists all sales transactions that were made in
SELECT *
FROM SALES
In this section, you will learn about MySQL single row numeric functions. Numeric
functions take one numeric parameter and return one value. A description of the functions
Note
Do not confuse the SQL aggregate functions you saw in the previous chapter with
the numeric functions in this section. The first group operates over a set of values
(multiple rows—hence, the name aggregate functions), while the numeric functions
Function Description
ABS Returns the absolute value of a number
Syntax: ABS(numeric_value)
ROUND Rounds a value to a specified precision (number of digits)
13
Syntax: ROUND(numeric_value, p) where p = precision
TRUNCATE Truncates a value to a specified precision (number of
digits)
Syntax: TRUNC(numeric_value, p) where p = precision
MOD Returns the remainder of division.
Syntax MOD(m.n) where m is divided by n.
The following example displays the individual LINE_PRICE from the sales line table,
rounded to one and zero places and truncated where the quantity of tickets purchased on
ROUND(LINE_PRICE,0) AS “LINE_PRICE1”,
FROM SALES_LINE
14
Task 6.8 Enter the following query and execute it. Can you explain the results of this
query?
FROM SALES_LINE
Table 5 shows a subset of the most useful string manipulation functions in MySQL.
Function Description
CONCAT Concatenates data from two different character columns and returns a single
column.
Syntax: CONCAT(strg_value, strg_value)
UPPER/LOWER Returns a string in all capital or all lowercase letters
Syntax: UPPER(strg_value) , LOWER(strg_value)
SUBSTR Returns a substring or part of a given string parameter
Syntax:
SUBSTR(strg_value, p, l) where p = start position and l = length of
characters
LENGTH Returns the number of characters in a string value
Syntax: LENGTH(strg_value)
15
CONCAT
The following query illustrates the CONCAT function. It lists all employee first and last
names concatenated together. The output for this query can be seen in Figure 61.
UPPER/LOWER
The following query lists all employee last names in all capital letters and all first names
in all lowercase letters. The output for the query is shown in Figure 62.
SELECT CONCAT(UPPER(EMP_LNAME),LOWER(EMP_FNAME)) AS
16
SUBSTR
The following example lists the first three characters of all the employees’ first name.
FROM EMPLOYEE;
LENGTH
The following example lists all attraction names and the length of their names; ordered
descended by attraction name length. The output of this query is shown in Figure 65.
17
Figure 65 Displaying the length of attraction names.
Conversion functions allow you to take a value of a given data type and convert it to the
equivalent value in another data type. In MySQL, some conversions occur implicitly. For
example, MySQL automatically converts numbers to strings when needed, and vice versa.
SELECT 10 + ‘10’
MySQL would give you an answer of 20 as it would automatically convert the string
If you want to explicitly convert a number to a string then you can use either the CAST or
CONVERT function. However MySQL 5.0 recommends only the CAST function is used.
Let’s look at an example. The following query produces the output shown in Figure 66.
18
Note
The MySQL Reference Manual 5.0 provides a set of rules that allow us to determine
how the coversion will occur when using the CONVERT function on different data
types.
IFNULL
The IFNULL function lets you substitute a value when a null value is encountered in the
IFNULL(expr1,expr2)
equivalent to Oracle’s NVL function. It is useful for avoiding errors caused by incorrect
CASE
The CASE function compares an attribute or expression with a series of values and
returns an associated value or a default value if no match is found. There are two versions
19
CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]
The first version returns the result where value=compare_value. The second version
returns the result for the first condition that is true. If there was no matching result
value, the result after ELSE is returned, or NULL if there is no ELSE part.
Let’s now look at the following example, which compares the country code in the
PARK_COUNTRY field and decodes it into the name of the country. If there is no
match, it returns the value ‘Unknown’. The output is shown in Figure 68.
THEN 'United Kingdom' WHEN 'FR' THEN 'France' WHEN 'NL' THEN 'The
Netherlands' WHEN 'SP' THEN 'Spain' WHEN 'ZA' THEN 'South Africa' WHEN 'SW'
FROM THEMEPARK;
20
It is worth noting that the above decode statement is equivalent to the following
IF-THEN-ELSE statement:
21
Exercises
E6.1 Create the view EMPFR (as created in section 6.2) and update the Theme Park that
employee number 101 works in. (Update the employee number 101 information in the
EMPFR view).
E6.2 Employee Emma Cauderdale (EMP_NUM =100) has now changed her phone number to
324-9652. Update her information in the EMPFR view. Write a query to show her new phone
number has been updated and then Remove the EMPFR view.
E6.3 Create a view of only those Theme Parks where tickets have been sold and then display the
contents of this view. Your output should match that shown in Figure E-6.4.
E6.4 The Theme Park managers want to create a view called EMP_DETAILS which
only be read only. Check that the view works, by displaying its contents.
22
Figure 2 Output for E-6.4
E6.5 Using your view EMP_DETAILS, write a query that displays all employee first and
E6.6 Create a view called TICKET_SALES which contains details of the min, max and
average sales at each Theme Park. The name of the theme park should also be displayed.
(Hint 1: you will need to join three tables). Once you have created your view, write a query
E6.7 Using the date specifiers in Table 7.2, modify the query shown in Figure 55 to
23
E 6.8 Write a query which generates a list of employee user IDs, using the born month,
first day of the month they were born and the first six characters of last name in UPPER
case. Your query should return the results shown in Figure 64.
USER ID format (MDName) here M= month, D= first day of month, Name= Employee
E6.9 Write a query which lists the names and dates of births of all employees born on the
14th day of the month.
E6.10 Write a query which generates a list of employee user passwords, using the first
three digits of their phone number, and the first two characters of first name in lower case.
Label the column USER_PASSWORD;
References:
https://www.mysqltutorial.org/mysql-views-tutorial.aspx/
https://dev.mysql.com/doc/refman/8.0/en/sql-function-reference.html
24