IT Elective I Advance Database System
IT Elective I Advance Database System
Introduction
Learning Outcomes
1
process of synthesis (creating a new database design) or decomposition (improving an
existing database design). In general, is the process of efficiently organizing data in a
database.
Update anomaly
Employee’s Skill
Employee_ID Employee_Address Skill
110 Borongan City Programmer
110 Borongan City Programmer
111 Arteche, Eastern Samar Website Developer
111 Dolores, Eastern Samar Programmer
Employee 111 is shown as having different addresses on different records.
2
Insertion anomaly
There are situations in which certain facts cannot be recorded at all. For
example, each record in a "Faculty and Their Courses" relation might contain a Faculty
ID, Faculty Name, Faculty Hire Date, and Course Code. Therefore, we can record the
details of any faculty member who teaches at least one course, but we cannot record a
newly hired faculty member who has not yet been assigned to teach any courses,
except by setting the Course Code to null. This phenomenon is known as an insertion
anomaly.
?
120 Prof. Baltazar 10-Mah-2020
Until the new faculty member, Prof. Baltazar, is assigned to teach at least
one course, his details cannot be recorded.
Deletion anomaly
3
Table 3: A Deletion Anomaly
DELETE
A. First normal form (1NF). As per the rule of first normal form, an attribute
(column) of a table cannot hold multiple values. It should hold only atomic values.
Example: Suppose a company wants to store the names and contact details of its
employees. It creates a table that looks like this:
+639352989168
+639657777777
Two employees (Prof. Borata & Prof. Baje) are having two mobile numbers so
the company stored them in the same field as you can see in the table above.
4
This table is not in 1NF as the rule says “each attribute of a table must have
atomic (single) values”, the emp_mobile values for employees Prof. Borata & Prof. Baje
violates that rule.
To make the table complies with 1NF we should have the data like this:
5
Table 6: 2NF Example A
111 Math 38
111 Physics 38
222 Biology 38
333 Physics 40
333 Chemistry 40
Candidate Keys : {teacher_id, subject }
Non -prime attribute : teacher_age
Teacher_Id Teacher_age
111 38
222 38
333 40
Table 8: 2NF Example B (teacher Subject)
Teacher_Id Subject
111 Math
111 Physics
222 Biology
333 Physics
333 Chemistry
6
C. Third Normal form (3NF). A table design is said to be in 3NF if both the following
conditions hold:
In other words, 3NF can be explained like this: A table is in 3NF if it is in 2NF and
for each functional dependency X-> Y at least one of the following conditions
hold:
Non-prime attributes: all attributes except Emp_ID are non-prime as they are not
part of any candidate keys.
7
Emp_City & Emp_Municipality) transitively dependent on super key (Emp_Id). This
violates the rule of 3NF.
We will use the 3NF to break the table into two tables to eliminate the transitive
dependency:
- Evaluate PK Assignments
8
- Refine Primary Keys as Required for Data Granularity
Example: Suppose there is a company wherein employees work in more than one
department. They store the data like this:
9
Purchasing
1002 American D134 600
department
To make the table comply with BCNF we can break the table in three tables
like this:
Emp_Id Emp_Nationality
1001 Austrian
1002 American
10
Table 16: BCNF Example B(Emp_Dept_Mapping Table)
Emp_Id Emp_Dept
1001 Production and planning
1001 stores
1002 design and technical support
1002 Purchasing department
Functional dependencies:
Candidate keys:
This is now in BCNF as in both the functional dependencies left side part
is a key.
The 4NF was introduced by Ronald Fagin in 1977, it comes after 1NF,
2NF, 3NF, and BCNF. To be in 4NF, a relation should be in Boyce-Codd Normal
Form and may not contain more than one multi-valued attribute.
11
Forever Philippine Drama
NOTE: Table above is not in 4NF, since one movie can have the same
listing and many shooting locations can have the same movie.
Movie_Name Shooting_Location
Forever Philippine
Movie_Name Listing
Forever Drama
Now, the violation is removed and the tables are in 4NF.
One of the most important steps in designing a database is ensuring that the
data is properly distributed among in the tables. With proper data structures, illogically
or inconsistently stored data can cause a number of problems.
The objective of normalization process is to ensure that each table conforms to
the concept of well-informed relations, that is, tables that have the following
characteristics:
12
▪ No data item will be unnecessarily stored in more than one table.
▪ All nonprime attributes in a table are dependent on the primary key.
To accomplish the objectives, the normalization process takes you through the
steps that lead to successively higher normal forms.
Student Class
1022 101-07
1022 143-01
1022 159-02
13
4123 201-01
4123 211-02
4123 214-01
Student Advisor Adv_room
1022 Jones 412
4123 Smith 216
Student: Registration:
Table 24: Third Normal Form: Eliminate Data Not Dependent on Key
Student: Faculty:
Introduction
Learning Outcomes
14
3. Understand the SQL RDBMS Concepts.
4. Understand the broad categories of SQL functions and the Basic SQL select
statement
Lesson 1: SQL Overview
Why SQL?
When you are executing an SQL command for any RDBMS, the system
determines the best way to carry out your request and SQL engine figures out how to
interpret the task. There are various components included in this process.
15
▪ SQL Query Engine, etc.
A classic query engine handles all the non-SQL queries, but a SQL query
engine won't handle logical files.
www.tutorialspoint.com/sql/sql_tutorial.pdf
What is RDBMS?
What is a table?
16
www.tutorialspoint.com/sql/sql_tutorial.pdf
What is a field?
Every table is broken up into smaller entities called fields. The fields in the
CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY.
A record is also called as a row of data is each individual entry that exists in
a table. For example, there are 7 records in the above CUSTOMERS table.
www.tutorialspoint.com/sql/sql_tutorial.pdf
A record is a horizontal entity in a table.
What is a column?
www.tutorialspoint.com/sql/sql_tutorial.pdf
17
What is a NULL value?
SQL Constraints
Following are some of the most commonly used constraints available in SQL:
▪ NOT NULL Constraint: Ensures that a column cannot have a NULL value.
▪ UNIQUE Constraint: Ensures that all the values in a column are different.
▪ CHECK Constraint: The CHECK constraint ensures that all values in a column
satisfy certain conditions.
▪ INDEX: Used to create and retrieve data from the database very quickly.
Data Integrity
18
▪ Referential integrity: Rows cannot be deleted, which are used by other records.
▪ User-Defined Integrity: Enforces some specific business rules that do not fall
into entity, domain or referential integrity.
There are many popular RDBMS available to work with. The following are a
brief overview of few most popular RDBMS. This would help users to compare basic
features of RDBMS.
19
SQL includes commands to create database objects such as tables, indexes
and views, as well as commands to define access rights to those database
objects.
Command Description
CREATE Creates a new table, a view of a table, or other object in
database
ALTER Modifies an existing database object, such as a table.
Deletes an entire table, a view of a table or other object in
DROP
the database.
Syntax:
Creating a Table
Syntax Example
) Title char(50),
AuthorID Integer,
Price
float)
20
Creates a table with four columns
Data Types
▪ Occupies the same length of space in memory no matter how much data is
stored in them. ▪ Syntax:
▪ If the variable stored for name is ‘Sanjay’ the extra 43 fields are padded with
blanks
Variable Length string is specified with maximum length of characters possible
in the string, however, the allocation is sized to the size of the data stored in
memory. ▪ Syntax:
▪ There may be a restriction in the maximum length of the data that you can
specify in the declaration which will vary according to the database.
▪ All character data has to be enclosed in single quotes during specification.
2. Numeric Data
▪ Store all the data related to purely numeric data.
▪ Some numeric data may also be stored as a character field e.g. zip codes ▪
Common Numeric Types:
1. Decimal Floating point number
2. Float Floating point number
3. Integer(size) Integer of specified length
4. Money A number which contains exactly two digits after the
decimal point
5. Number A standard number field that can hold a floating point
data
Note: Different databases name their numeric fields differently and may not
support all numeric types. They may also support additional numeric types.
21
3. Temporal Data- These represent the dates and time
Three basic types are supported:
a. Dates
b. Times
c. Date-Time Combinations
4. Large Objects- These are used for storing data objects
like files and images There are two types:
a. Character Large Objects (clobs)
b. Binary Large Objects (blobs)
22
▪ Here both name & city/state combination are declared as candidate keys
city varchar(50),
state char(2),
PRIMARY KEY (studio_id),
UNIQUE (name),
UNIQUE(city, state)
)
Example:
CREATE TABLE Movies
(movie_title varchar(40),
Modifying Records
Insert Statement
23
Notes 1: If the columns are not specified as in the first example the data
goes in the order specified in the table
▪ If the field has a default value of Null, you can use an Insert
statement that ignores the column where the value is to be Null.
▪ You can specify the column in the column list specification and
assign a value of Null to the corresponding value field.
A select query can be used in the insert statement to get the values for the
insert statement
This selects the corresponding fields from the studios table and inserts them
into the city_state table.
Example:
INSERT INTO city_state
SELECT Distinct studio_city, studio_state FROM studios
This selects the corresponding fields from the studios table, deletes the
duplicate fields and inserts them into the city_state table. Thus, the final
table has distinct rows.
Delete Statement:
Used to remove records from a table of the database. The where clause in
the syntax is used to restrict the rows deleted from the table otherwise all the
rows from the table are deleted.
Example:
DELETE FROM City_State WHERE
state = ‘TX’
Deletes all the rows where the state is Texas keeps all the other rows.
24
Update Statement:
Used to make changes to existing rows of the table. It has three parts.
First, you, must specify which table is going to be updated. The second part of
the statement is the set clause, in which you should specify the columns that
will be updated as well as the values that will be inserted. Finally, the where
clause is used to specify which rows will be updated.
Example:
UPDATE studios
studio_state = ‘NY’
WHERE studio_id = 1
Notes1: If the condition is dropped then all the rows are updated.
Truncate Statement:
Used to delete all the rows of a table. Delete can also be used to delete all
the rows from the table. The difference is that delete performs a delete
operation on each row in the table and the database performs all attendant
tasks on the way. On the other had the Truncate statement simply throws
away all the rows at once and is much quicker. The note of caution is that
truncate does not do integrity checks on the way which can lead to
inconsistencies on the way. If there are dependencies requiring integrity
checks we should use delete.
25
Drop Statement:
Command Description
SELECT Retrieves certain records from one or more tables.
INSERT Creates a record
UPDATE Modifies records.
DELETE Deletes records.
Select Command
Clause Description
WHERE It specifies which rows to retrieve.
GROUP BY It is used to arrange the data into groups.
HAVING It selects among the groups defined by the GROUP BY
clause.
26
ORDER BY It specifies an order in which to return the rows.
Syntax: Example
OR
▪ Using this command, you can add one or more records to any single table in a
database.
Syntax
INSERT INTO <table_name> (`column_name1` <datatype>,
`column_name2` <datatype>, . . . , `column_name_n` <database>) VALUES
(`value1`, `value2`, . . . , `value n`);
Example:
INSERT INTO employee (`eid` int, `ename` varchar(20), `city` varchar(20))
VALUES (`1`, `ABC`, `PUNE`);
Update Command
Syntax: Example:
27
Delete Command
▪ DELETE command is used to delete some or all records from the existing
table.
▪ It deletes all the records from a table.
Syntax: Example
DELETE FROM <table_name> where <condition>;DELETE FROM employee
If users do not write the WHERE condition, then all rows will get deleted.
The SQL SELECT Statement
SELECT Syntax
Here, column1, column2, ... are the field names of the table you want to
select data from. If you want to select all the fields available in the table,
use the following syntax:
SELECT * FROM table_name;
28
FROM table_name;
Introduction
In this chapter students will learn the advanced data definition commands. Data
definition commands are used to create, modify and remove database objects
such as schemas, tables, views, indexes etc. Learn the different clauses to
change the behavior of the SELECT statement. Like, displaying the number of
rows in the table, removing duplicate rows, ordering SELECT results (ascending
and descending), and using WHERE in your queries. Creating view and joining
tables.
Learning Outcomes
All changes are made by using ALTER command. MySQL ALTER command
is very useful when you want to change a name of your table, any table field or if you
want to add or delete an existing column in a table.
29
sec) mysql> SHOW COLUMNS FROM
testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
|i | int(11) | YES | | NULL | |
|c | char(1) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Suppose you want to drop an existing column i from above MySQL table then
you will use DROP clause along with ALTER command as follows:
A DROP will not work if the column is the only one left in the table.
To add a column, use ADD and specify the column definition. The following statement
restores the i column to testalter_tbl:
After issuing this statement, testalter will contain the same two columns that it had
when you first created the table, but will not have quite the same structure. That's
because new columns are added to the end of the table by default. So even
though i originally was the first column in mytbl, now it is the last one.
30
To indicate that you want a column at a specific position within the table, either use
FIRST to make it the first column or AFTER col_name to indicate that the new
column should be placed after col_name. Try the following ALTER TABLE
statements, using SHOW COLUMNS after each one to see what effect each one
has:
The FIRST and AFTER specifiers work only with the ADD clause. This means that
if you want to reposition an existing column within a table, you first must DROP it
and then ADD it at the new position.
With CHANGE, the syntax is a bit different. After the CHANGE keyword, you name
the column you want to change, then specify the new definition, which includes the
new name. Try out the following example:
If you now use CHANGE to convert j from BIGINT back to INT without changing
the column name, the statement will be as expected: mysql> ALTER TABLE
testalter_tbl CHANGE j j INT;
When you MODIFY or CHANGE a column, you can also specify whether or not
the column can contain NULL values and what its default value is. In fact, if you
don't do this, MySQL automatically assigns values for these attributes.
Here is the example, where NOT NULL column will have value 100 by default.
31
mysql> ALTER TABLE testalter_tbl
-> MODIFY j BIGINT NOT NULL DEFAULT 100;
If you don't use above command, then MySQL will fill up NULL values in all the
columns.
You can change a default value for any column using ALTER command. Try out the
following example.
You can remove default constraint from any column by using DROP clause along with
ALTER command.
32
You can use a table type by using TYPE clause along with ALTER command. Try out
the following example to change testalter_tbl to MYISAM table type.
To find out the current type of a table, use the SHOW TABLE STATUS statement.
Renaming a Table:
To rename a table, use the RENAME option of the ALTER TABLE statement.
Try out the following example to rename testalter_tbl to alter_tbl.
33
rows, ordering SELECT results (ascending and descending), limiting your results,
and using WHERE in your queries.
We can use the COUNT() function to return the number of rows that
matches a specified criteria. For example, to display the number of all rows in a
table, we can use the following command:
Sometimes, when querying data from a table, you might get duplicate rows. To
remove these duplicate rows, you use the DISTINCT clause in
the SELECT statement. For example, let’s say that we want a list of all first name in
our table. If we select just the name column from a table, we will get duplicate results:
34
| name |
+------+
| Sarah |
| Angel |
| Angel |
| Anne |
+------+
4 rows in set (0.00 sec)
Notice how the name Angel appears twice. To remove multiple entries, we can use
the DISTINCT clause:
Filter records
You can narrow down queries by returning only those where a certain expression is
true. To do that, the WHERE clause is used.
35
• BETWEEN operator, which is useful with integer or data
comparisons because it searches for results between a minimum
and maximum value.
SELECT column_name FROM table_name WHERE column_name operator value
Here is an example. Let’s say that we want to select all rows with the value Sarah in
the name column:
Note: Make sure to use the single quotes around text values when working with
strings.
Here is another example. Let’s say that we want to select all rows where the birth_year
column is between 1980 and 1995:
mysql> SELECT * FROM test_table WHERE birth_year between 1980 and 1995;
+------+-----------+------+
| name | surname | birth_year |
+------+-----------+------+
36
| Sarah | Geronimo | 1991 |
| Angel | Locsin | 1982 |
| Anne | Curtis | 1985 |
+------+-----------+------+
3 rows in set (0.00 sec)
37
+------+-------------+------+
| name | surname | birth_year |
+------+-------------+------+
| Angel | Aquino | 1991 |
| Anne | Curtis | 1982 |
| Sarah | Geronimo | 1975 |
| Angel | Locsin | 1985 |
+------+-------------+------+
4 rows in set (0.00 sec)
Note: A view always shows up-to-date data! The database engine recreates the data,
using the view's SQL statement, every time a user queries a view.
Example
38
Lesson 4: Joining Database Tables
▪ Joining tables is the most important distinction between relational database and
other databases
▪ Join is performed when data are retrieved from more than one table at a time o
Equally comparison between foreign key and primary key of related tables.
▪ Join tables by listing tables in FROM clause of SELECT statement.
Model Tables
suppliers
+-------------+---------------+-------------------+------------------+
| supplier_id | supplier_name | supplier_address | supplier_contact |
+-------------+---------------+-------------------+------------------+
| 1 | Microsoft | 1 Microsoft Way | Bill Gates |
| 2 | Apple, Inc. | 1 Infinite Loop | Steve Jobs |
| 3 | EasyTech | 100 Beltway Drive | John Williams |
| 4 | WildTech | 100 Hard Drive | Alan Wilkes | +-------------
+---------------+-------------------+------------------+
product
+-----------+----------------------------+-----------------------------+-------------+
| prod_code | prod_name | prod_desc | supplier_id |
+-----------+----------------------------+-----------------------------+-------------+
| 1 | CD-RW Model 4543 | CD Writer | 3|
| 2 | EasyTech Mouse 7632 | Cordless Mouse | 3|
| 3 | WildTech 250Gb 1700 | SATA Disk Drive | 4|
| 4 | Microsoft 10-20 Keyboard | Ergonomic Keyboard | 1|
| 5 | Apple iPhone 8Gb | Smart Phone | 2 | +-----------
+----------------------------+-----------------------------+-------------+
39
Performing a Cross-Join
Joining tables involves combining rows from two tables. The most basic of
join types is the cross-join. The cross-join simply assigns a row from one table to
every row of the second table. This is of little or no use in real terms, but for the
purposes of completeness, the syntax for a cross-join is as follows:
+----------------------------+---------------+
| prod_name | supplier_name |
+----------------------------+---------------+
| CD-RW Model 4543 | Microsoft |
| CD-RW Model 4543 | Apple, Inc. |
| CD-RW Model 4543 | EasyTech |
| CD-RW Model 4543 | WildTech |
| EasyTech Mouse 7632 | Microsoft |
| EasyTech Mouse 7632 | Apple, Inc. |
| EasyTech Mouse 7632 | EasyTech |
| EasyTech Mouse 7632 | WildTech |
| WildTech 250Gb 1700 | Microsoft |
| WildTech 250Gb 1700 | Apple, Inc. |
| WildTech 250Gb 1700 | EasyTech |
| WildTech 250Gb 1700 | WildTech |
| Microsoft 10-20 Keyboard | Microsoft |
| Microsoft 10-20 Keyboard | Apple, Inc. |
| Microsoft 10-20 Keyboard | EasyTech |
| Microsoft 10-20 Keyboard | WildTech |
| Apple iPhone 8Gb | Microsoft |
| Apple iPhone 8Gb | Apple, Inc. |
| Apple iPhone 8Gb | EasyTech |
| Apple iPhone 8Gb | WildTech |
+----------------------------+---------------+
40
Equi-Join (aka the Inner Join)
The Equi-Join joins rows from two or more tables based on comparisons
between a specific column in each table. The syntax for this approach is as follows:
For example, to extract the product name and supplier name for each row in
our product table we would use the following command:
Note that we have to use what is known as the fully qualified name for the
supplier_id column in each table since both tables contain a supplier_id. A fully
qualified column name is defined by specifying the table name followed by a dot (.)
and then the column name.
The result of the above command is to produces a list of products and the name and
address of the supplier for each product:
+--------------------------+---------------+-------------------+
| prod_name | supplier_name | supplier_address |
+--------------------------+---------------+-------------------+
| Microsoft 10-20 Keyboard | Microsoft | 1 Microsoft Way |
| Apple iPhone 8Gb | Apple, Inc. | 1 Infinite Loop |
| CD-RW Model 4543 | EasyTech | 100 Beltway Drive |
| EasyTech Mouse 7632 | EasyTech | 100 Beltway Drive |
| WildTech 250Gb 1700 | WildTech | 100 Hard Drive |
+--------------------------+---------------+-------------------+
Another way to join tables is use a LEFT JOIN in the select statement.The
LEFT JOIN causes the tables to be joined before any WHERE clause is used. The
syntax for this type of join is: SELECT column names FROM table1 LEFT JOIN
table2 ON (table1.column = table2.column);
41
Therefore, we can perform a LEFT JOIN that gives us the same result as our EquiJoin:
One key different with the LEFT JOIN is that it will also list rows from the
first table for which there is no match in the second table. For example, suppose
we have product in our product table for which there is no matching supplier in the
supplier table. When we run our SELECT statement, the row will still be displayed,
but with NULL values for the supplier columns since no such supplier exists:
+----------------------------+---------------+-------------------+
| prod_name | supplier_name | supplier_address |
+----------------------------+---------------+-------------------+
| CD-RW Model 4543 | EasyTech | 100 Beltway Drive |
| EasyTech Mouse 7632 | EasyTech | 100 Beltway Drive |
| WildTech 250Gb 1700 | WildTech | 100 Hard Drive |
| Microsoft 10-20 Keyboard | Microsoft | 1 Microsoft Way |
| Apple iPhone 8Gb | Apple, Inc. | 1 Infinite Loop |
| Moto Razr | NULL | NULL |
+----------------------------+---------------+-------------------+
The opposite effect can be achieved using a RIGHT JOIN, whereby all the
rows in the second table (i.e. our supplier table) will be displayed regardless of
whether that supplier has any products in our product table:
42
SELECT prod_name, supplier_name, supplier_address FROM product RIGHT JOIN
suppliers
ON (product.supplier_id = suppliers.supplier_id);
+--------------------------+-----------------+------------------------+
| prod_name | supplier_name | supplier_address |
+--------------------------+-----------------+------------------------+
| Microsoft 10-20 Keyboard | Microsoft | 1 Microsoft Way |
| Apple iPhone 8Gb | Apple, Inc. | 1 Infinite Loop |
| CD-RW Model 4543 | EasyTech | 100 Beltway Drive |
| EasyTech Mouse 7632 | EasyTech | 100 Beltway Drive |
| WildTech 250Gb 1700 | WildTech | 100 Hard Drive |
| NULL | Hewlett Packard | 100 Printer Expressway |
+--------------------------+-----------------+------------------------+
Creating Joins with WHERE and USING
The next step is to incorporate some WHERE clauses into our LEFT and
RIGHT joins. Say, for example, that we wish to list only products supplied by Microsoft:
The USING clause further simplifies the tasks of creating joins. The
purpose of USING is to avoid the use of fully qualified names (such as
product.supplier_id and supplier.supplier_id) when reference columns that reside
in different tables but have the names. For example, to perform the same join
above based on the values of product.supplier_id and supplier.supplier_id we can
simply use the following syntax:
43
SELECT prod_name, supplier_name, supplier_address FROM product
LEFT JOIN suppliers USING (supplier_id) WHERE
supplier_name='Microsoft';
+--------------------------+---------------+------------------+
| prod_name | supplier_name | supplier_address |
+--------------------------+---------------+------------------+
| Microsoft 10-20 Keyboard | Microsoft | 1 Microsoft Way |
+--------------------------+---------------+------------------+
1 row in set (0.00 sec)
44
ASSESSMENT:
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
2. Identify the problems that you may encountered without normalization in designing
your database and discuss briefly each modification anomaly.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
3. The table below shows an unnormalized data. Improve the data by normalization in
first normal form.
Table Product
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
45
4. Explain what Structured Query Language is.
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_____________________________________________________
______________________________________________________________ 5.
Identify and explain briefly the Structured Query Language process.
______________________________________________________________
_________________________________________________________________
_________________________________________________________________
________________________________________________________
______________________________________________________________
46
▪ Provide at least 5 sample records for each table.
▪ Student_table:
o Address
o Contact No.
o Gender
▪ Book_table:
Prog_id Description
1 BSIT
2 BSED
3 BEED
4 BSA
▪ Join two tables above using inner join, use the prog_id to join the
tables.
47
Module 4: ADVANCED SQL FUNCTIONS
Introduction
SQL functions are simply sub-programs, which are commonly used and reused
throughout SQL database applications for processing or manipulating data. All SQL
database systems have DDL (data definition language) and DML (data manipulation
language) tools to support the creation and maintenance of databases.
Learning Outcomes
5. Understand how to use the SQL LENGTH function to get the number of characters
in a string.
6. Understand how to use the SQL UPPER function to convert a string into uppercase.
7. Understand how to use the LOWER function to convert a string into lowercase.
8. Understand how to use the SQL SUBSTRING function to extract a substring from a
string.
In SQL, dates are complicated for newbies, since while working with a database, the
format of the date in the table must be matched with the input date in order to insert. In
various scenarios instead of date, datetime (time is also involved with date) is used.
Date and Time Function formats are different various database. we are going to discuss
most common functions used in Oracle database.
48
• Century
• Year
• Month
• Day
• Hour
• Minute
• Second
Extract ():
Oracle helps you to extract Year, Month and Day from a date using Extract()
Function.
Output:
CURRENT_DATE_TIME ONLY_CURRENT_YEAR
Explanation:
Useful to retrieve only year from the System date/Current date or particular specified
date.
CURRENT_DATE_TIME ONLY_CURRENT_MONTH
49
Explanation:
Useful to retrieve only month from the System date/Current date or particular specified
date.
CURRENT_DATE_TIME ONLY_CURRENT_DAY
05.Feb.2019 07:29:24 5
Explanation:
Useful to retrieve only day from the System date/Current date or particular specified
date.
Using this method in PL/SQL you can add as well as subtract number of months(n)
to a date. Here ‘n’ can be both negative or positive.
FROM Dual
Output:
50
Explanation:
ADD_MONTHS function has two parameters one is date, where it could be any
specified/particular date or System date as current date and second is ‘n’, it is an
integer value could be positive or negative to get upcoming date or previous date.
LAST_DAY(date):
Using this method in PL/SQL you can get the last day in the month of specified date.
• Example-5
LAST_DAY(SYSDATE)+1 AS FIRST_DAY_OF_NEXT_MONTH
FROM Dual
Output:
Explanation:
In above example, we are getting current date using SYSDATE function and last
date of the month would be retrieved using LAST_DAY function and this function
be also helpful for retrieving the first day of the next month.
DAYS_LEFT_IN_MONTH
FROM Dual
Output:
51
CURRENT_DATE DAYS_LEFT_IN_MONTH
02.Feb.2019 09:32:00 26
Using this method in PL/SQL you can calculate the number of months between
two entered dates date1 and date2. if date1 is later than date2 then the result
would be positive and if date1 is earlier than date2 then result is negative.
Note:
FROM Dual
Output:
NUMBER_OF_MONTHS
3.58
Explanation:
Here date1 and date2 are not on the same day of the month that’s why we are
getting the value in fractions, as well as date1 is later than date2 so the resulting
value is in integers.
Eneterd date should be in particular date format, that is the reason of using TO_DATE
function while comparison within MONTHS_BETWEEN function.
Let’s select the number of months an employee has worked for the company.
• Example-8
NUMBER_OF_MONTHS
52
FROM Employees
Input:
SYSTEM_DATE DATE_OF_HIRE
02-02-2019 31-10-2017
02-02-2019 03-12-2017
02-02-2019 24-09-2018
02-02-2019 22-12-2016
02-02-2019 18-06-2018
Output:
NUMBER_OF_MONTHS
15.064
13.967
4.290
25.354
7.483
NEXT_DAY(date, day_of_week):
It will return the upcoming date of the first weekday that is later than the entered
date. It has two parameters first date where, system date or specified date can be
entered; second day of week which should be in character form.
• Example-9:
FROM Dual
53
Output:
NEXT_SUNDAY
17-FEB-2019
Explanation:
It will help to provide the next upcoming date corresponding to the day, return type is
always DATE regardless of datatype date. The second parameter must be a day of the
week either full name or abbreviated.
The CONCAT function concatenates by taking two VARCHAR2 strings and returning
those strings appended together in the order specified. The syntax of the function looks
like as follows:
The CONCAT function at least requires two parameters and this function can accept a
maximum of 254 parameters.
In this example, we will join Think and green strings with the CONCAT function:
SELECT CONCAT('Think','green') AS 'FullString'
54
As we can see clearly in this first example, the CONCAT function joined these two
strings and we obtained the Thinkgreen string.
In this second example, we will join 7 strings:
SELECT CONCAT('If' , ' you' , ' save', ' a', ' tree' , ' you' , ' save' ,' a' ,' life') AS 'FullStr
ing'
In this second example, the CONCAT function concatenated more than two strings
and the result was If you save a tree you save a life.
ring
CONCAT function also has the capability to join the numeric values. In the following
example, we will join three different integer values:
55
As we can see, we did not use any CAST or CONVERT function to join these
numerical expressions with the function. On the other hand, if we want to
concatenate these expressions with (+) plus sign, we need to convert them to
string data types. Otherwise, the result of the concatenation operation will be
incorrect:
The following example demonstrates the concatenating numerical expressions with (+)
plus without any data conversion so the output will be a mathematical addition:
Now, let’s research and try to understand what is happening behind the scene while
the numerical expressions concatenation process with CONCAT function.
Firstly, we will create a test table in order to insert some numerical expressions. The
following script will create a Test_NumericValue table:
56
CREATE TABLE Test_NumericValue (Number_1 INT , Number_2 INT , Number_3INT)
9)
Now, we will execute the below SELECT statement in the ApexSQL Plan:
ericValue
How to use line feed (\n) and carriage return (\r) with CONCAT function
CHAR function enables to convert ASCII numbers to character values. The following
ASCII codes can be used to get a new line with CHAR function in SQL:
10 LF Line Feed
13 CR Carriage Return
We can get a new line when we concatenate the strings with the following CHAR
functions:
For example, the following query results in the concatenated string line by line with
CHAR(13) function:
R(13),'water',CHAR(13), 'count')
57
AS Result
Now, we will replace CHAR(13) expression with CHAR(10) expression and re-
execute the same query:
'count') AS Result
At the same time, we can use CHAR(13) and CHAR(10) together. This usage type
could be a good option when we want to generate a line break. Now, we will make
a demonstration of it:
58
SELECT CONCAT('Make',CHAR(10),CHAR(13),'every' ,CHAR(10),CHAR(13),'drop',
CHAR(10),CHAR(13), 'of',CHAR(10),CHAR(13),'water',CHAR(10),CHAR(13),'count')
AS Result
Conclusion
In this lesson, we have learned the CONCAT function in SQL using various examples.
CONCAT function is a very useful option to concatenate the expressions in the SQL.
The SQL LENGTH function returns the number of characters in a string. The
LENGTH function is available in every relational database systems. Some
database systems use the LEN function that has the same effect as the LENGTH
function.
LENGTH(string)
If the input string is empty, the LENGTH returns 0. It returns NULL if the input string
is NULL.
The number of characters is the same as the number of bytes for the ASCII strings.
For other character sets, they may be different.
The LENGTH function returns the number of bytes in some relational database
systems such as MySQL and PostgreSQL. To get the number of characters in a
string in MySQL and PostgreSQL, you use the CHAR_LENGTH function instead.
59
SQL LENGTH examples
The following statement uses the LENGTH function to return the number of
characters the string SQL :
SELECT LENGTH ('SQL');
length
--------
3
(1 row)
The following statement returns the top five employees with the longest names.
SELECT
employee_id,
CONCAT (first_name, ' ', last_name) AS full_name,
LENGTH (CONCAT (first_name, ' ', last_name)) AS len
FROM
employees
ORDER BY len DESC
LIMIT 5;
60
How the query works.
• First, use the CONCAT function to construct the full name of the employee by
concatenating the first name, space, and last name.
• Second, apply the LENGTH function to return the number of characters of the
full name of each employee.
• Third, sort the result set by the result of the LENGTH function and get five rows
from the sorted result set.
The SQL UPPER function converts all the letters in a string into uppercase. If you
want to convert a string to lowercase, you use the LOWER function instead.
UPPER(string);
If the input string is NULL, the UPPER function returns NULL, otherwise, it returns a
new string with all letters converted to uppercase.
Besides the UPPER function, some database systems provide you with an
additional function named UCASE which is the same as the UPPER function. It is
“there is more than one way to do it”.
UCASE(string);
61
The following statement converts the string sql upper to SQL UPPER:
UPPER
----------------------
SQL UPPER
(1 row)
The following query uses the UPPER function to convert last names of employees to
uppercase.
SELECT
UPPER(last_name)
FROM
employees
ORDER BY UPPER(last_name);
The query just read the data from the employees table and convert them on the fly.
The data in the table remains intact.To convert data to uppercase in the database
table, you use the UPDATE statement. For example, the following statement
updates the emails of employees to uppercase.
62
UPDATE employees
SET email =
UPPER(email);
When you query the data using the WHERE clause, the database systems often match
data case sensitively. For example, the literal string Bruce is different from bruce.
SELECT
employee_id,
first_name
FROM
employees
WHERE
first_name = 'BRUCE' ;
To match data case insensitively, you use the UPER function. For example, the
following query will return a row:
SELECT
employee_id,
first_name
FROM
employees
WHERE
UPPER (first_name) ='BRUCE';
Notice that the query above scans the whole table to find the matchingcase the
rơ. In
63
To overcome this, some database systems provide the function-based index that
allows you to define an index based on a function of one or more columns that
results in a better query performance.
The SQL LOWER function converts all the characters in a string into lowercase. If
you want to convert all characters in a string into uppercase, you should use the
UPPER function.
LOWER(string);
The LOWER function returns a string with all characters in the lowercase format. It
returns NULL if the input string is NULL.
Some database systems such as Oracle database and MySQL provide the LCASE
function that is equivalent to the LOWER function. LCASE(string);
64
See the following employees table in the sample database.
The following query uses the LOWER function to return the names of departments in
lowercase.
SELECT
LOWER(department_name)
FROM
departments
ORDER BY LOWER (department_name);
65
UPDATE employees
SET
email = LOWER (email);
Standard SQL performs matching case sensitive. It means that the literal
string Sarah is different from sarah when it comes to an input for a query.
To query data case-insensitive, you can use the LOWER function.
The following query returns an empty result set because there is no employee whose
Note that this query scans the whole table to get the result. For the big table, it will be
slow.
Some database systems support the function-based index e.g., Oracle database,
PostgreSQL, etc., You can create an index based on a specific function. If you
create a function-based index for the first_name column, the query will use the
index to find the row very fast.
The SUBSTRING function extracts a substring that starts at a specified position with a
given length.
66
The following illustrates the syntax of the SUBSTRING function.
• The source_string is the string from which you want to extract the substring.
• The position is the starting position where the substring begins. The first position
of the string is one (1).
• The length is the length of the substring. The length argument is optional.
Most relational database systems implement the SUBSTRING function with the same
functionality.
SELECT SUBSTRING('SQLTutorial.org'
,1,3);
substring
-----------
SQL
(1 row)
The followingstatement uses thePOSITION function to return the position of the dot
character (.) in the string.
The result of the POSITION function is passed to the SUBSTRING function to find the
extension of a domain:
67
SELECT
SUBSTRING ('SQLTutorial.org' ,
POSITION ('.' IN 'SQLTutorial.org' ));
substring
-----------
.org
(1 row)
The following query uses the SUBSTRING function to extract the first characters of
the employee’s first names (initials) and group employees by the initials:
68
SELECT
SUBSTRING (first_name, 1, 1) initial ,
COUNT (employee_id )
FROM
employees
GROUP BY initial ;
Assessment:
1. Write a query to display the current date. Label this column Date
2. Display the last name, hire date and day of the week on which the employee
started. Label the column Day. Order the results by the day of the week, starting
with Monday.
69
4. Write a code to return the length of the text in the “CustomerName” column, in
bytes.
70