Professional Documents
Culture Documents
Information-Management Unit 3
Information-Management Unit 3
Unit 3
Structured Query Language (SQL)
Introduction
Are you aware that there is only one language for relational databases? In this
unit, you will be learning the language for relational databases which is the
Structured Query Language (SQL). Specifically, you will be learning the
different SQL Clauses, Relational or Comparison Operators, and the different
Logical Operators. For you to understand better, examples of SQL statements
with sample query results are also included. This unit will also serve as a
tutorial for beginners in SQL using Microsoft Office Access. We hope that
after completing this unit, something will be added to your body of knowledge
and your IT skill will be enhanced particularly in using SQL.
Learning Objectives
After completing this topic, the students should be able to demonstrate basic
skill in SQL such as the use of different Clauses, Data Definition Language
and Data Manipulation Language.
Presentation of Contents
The SQL language may be considered one of the major reasons for the
commercial success of relational databases because it became a standard for
relational databases. The name SQL is presently expanded as Structured
Query Language. Originally, SQL was called SEQUEL (Structured English
QUEry Language) and was designed and implemented at IBM Research as
the interface for an experimental relational database system called
1
Unit 3: Structured Query Language
SYSTEM R. SQL is now the standard language for commercial relational
DBMSs. A joint effort by the American National Standards Institute (ANSI)
and the International Standards Organization (ISO) has led to a standard
version of SQL, called SQL-86 or SQL1 (Elmasri & Navathe, 2011).
SQL Clauses
As mentioned above that Clauses are in some cases optional and are basic
components of statements. This time, let’s describe each clause and use some
examples. We will start from the basic queries until we have complex queries.
where
In addition, the SELECT clause lists the attributes to be retrieved, and the
FROM clause specifies all relations (tables) needed in the simple query. The
2
Unit 3: Structured Query Language
WHERE clause identifies the conditions for selecting the tuples from these
relations, including join conditions if needed (Elmasri, et al., 2011).
Now, let us try to use the basic SQL form using Microsoft Access (MS
Access). You need to create a table for books (tblBooks) using the table
structure below.
Let us also add at least five (5) records in our newly created table. You may
use the same records below or you may want to insert your preferred records.
Using a query, let’s try to retrieve records applying the basic SQL form. On
the CREATE table of your MS Access application, click Query Design menu
(see figure below).
As you click Query Design button, a Show Table dialog appears displaying the
tables in your database. Just close the dialog box because we do not need to
select any table from the list (see figure below).
3
Unit 3: Structured Query Language
After closing the Show Table dialog, right click on the clear area of the query
and select SQL View (see figure on the left). You can also click the SQL View
button under the Design tab (see figure on the right).
We are now ready to write our first basic SQL statement. Let us retrieve all
books which price is 2,500 using the statement below. Always remember that
unlike string values, numeric values do not need to be enclosed with a pair of
single quote (‘ ’). Also, SQL statements are case insensitive which means that
you can use either upper case and lower case letters or combination of upper
case and lower case letters; however, for readability’s sake of this tutorial, we
shall use upper case letters for clauses.
4
Unit 3: Structured Query Language
Let us run the SQL statement above by clicking the Run button under Design
Tab as shown in the figure below.
As you have observed in the result, there are only two records displayed by the
query. In addition, only the books having 2,500 as the price were retrieved as
the price matched with our condition (price = 2500).
Let us try another SQL statement. This time, we will select a book based on its
title. But before that, we shall return or query to SQL View. You may want to
click right on the tab of the query and select SQL View (see figure on the left
below) or you may click the View menu under the Home tab and select SQL
View (see figure on the left below).
5
Unit 3: Structured Query Language
Based on the result of the query, it only displays one record with the book title
‘SQL Basics’ since there is only one book that matched with the condition.
Based on the two examples, you have observed that we used asterisk (*) on
the attribute list of our statements which indicates or represents that we are
displaying all columns. The next examples will demonstrate how to retrieve
specific columns.
We will use the previous examples; however, we will try to specify the desired
columns to be displayed by the query. The SQL statement below will only
display the columns Title, Author and Price.
Based on the result of the query below, only the enumerated table fields or
columns (attribute list) were displayed.
Let’s have another example where the column Author will serve as the criteria
in searching specific record as shown below.
As you can see in the result of the query below, one record matched with the
specified condition. In addition, only two columns (Title, Author) were
displayed.
If you want to retrieve all records without condition, you just have to exclude
the WHERE clause in the SQL statement. The sample SQL statement and
sample result of the query is shown below.
6
Unit 3: Structured Query Language
Elmasri, et al. (2011) said that ORDER BY clause specifies an order for
displaying the results of a query. In addition, it is use to sort the selected
records in either ascending (ASC) or descending (DESC) order based on the
specified column or columns. Below is an example and result of SQL
statement with ORDER BY clause in ascending order (ASC) based on the
Title of books.
Our next example shows the records in descending order (DESC) based on the
Title of books.
7
Unit 3: Structured Query Language
The example below shows the records in descending order (DESC) based on
the Price of books. In addition, WHERE clause was also used to retrieve
record based on the price (Price > 2000). As you have observed in the SQL
Statement below, it uses a formula Price * 0.06 with alias Sales_Tax. You can
always include a formula as part of the SQL statement. You just have to use
the keyword AS to indicate the column name to be displayed in the result of
the query. If the alias does not contain a space like our alias Sales_Tax
(preferred alias), there is no need to enclose it with a pair of single quote
otherwise, you must enclose it with a pair of single quote (example: ‘Sales
Tax’); however, MS Access will also display the single quotation in the
column header of the result but if you use other DBMS such as MS SQL
Server and MySQL or if you integrate the SQL statement in a program using a
programming language, the pair of single quote will no longer appear.
This time, we will also learn the use of GROUP BY clause. According to
Elmasri, et al. (2011), GROUP BY clause specifies the grouping attributes,
which should also appear in the SELECT clause. The GROUP BY clause will
only group records and columns having exactly the same value. Below is an
example on how to use GROUP BY clause with its sample output.
8
Unit 3: Structured Query Language
Based on the example above, the query groups the price with exactly the same
value. In our records, there two books with price of 2,500 and two books with
price of 2,000. After running our SQL statement with group by clause, it only
displays three records because the two similar price were already grouped as
one. We can also count how many record were grouped by adding the
COUNT (*) function in our SQL statement. The COUNT function simply
counts the number of rows or records (see figure below).
The last clause in this topic is the HAVING clause. SQL provides a HAVING
clause, which can appear in conjunction with a GROUP BY clause. HAVING
provides a condition on the summary information regarding the group of
tuples associated with each value of the grouping attributes. Only the groups
that satisfy the condition are retrieved in the result of the query (Elmasri, et al.,
2011) as shown in the example below.
Based on the example above, we used the result of the function COUNT (*) as
the condition of the HAVING clause. As a result of the query, only the two
grouped price of books were retrieved. You can use any of the relational
operators in creating the condition of your query which will be discussed in
Topic 3.
9
Unit 3: Structured Query Language
CREATE Command
The main SQL command for data definition is the CREATE statement, which
can be used to create schemas and tables. The following example shows how
to create a table using the CREATE command.
10
Unit 3: Structured Query Language
ALTER Command
The next command is the ALTER command which is use to change the
definition or structure of tables such as adding and dropping of columns
(attributes), changing column name or adding and dropping of table
constraints. The following example shows how to add new column in
tblStudents. After running the ALTER command, a new column Address has
been added in the table structure (see figures below).
The next command is the DROP command which can be used to drop named
schema elements, such as tables. The example below shows how to delete the
table tblStudents using DROP command.
The last command is the TRUNCATE command which is use to delete all
rows in a table and it will also recreate the table. An example of truncate
command is shown below. Unfortunately, this command is not supported in
MS Access.
11
Unit 3: Structured Query Language
Alternatively, we can also use the DELETE statement to delete all rows in a
table; however, it does not recreate the table. This statement will be discussed
in the next sub-topic.
INSERT Command
Now, let us discuss and use the INSERT command. In its simplest form,
INSERT is used to add a single tuple (row or record) to a relation (table). We
must specify the relation name and a list of values for the tuple. The values
should be listed in the same order in which the corresponding attributes were
specified in the CREATE TABLE command. For example, to add a new tuple
to tblBooks table, we need to insert five (5) values because there are five (5)
attributes or columns in our table (see figure below).
If you try to run the statement, a confirmation dialog box will appear, asking
you to append (add) the new row (see figure below). You just have to click the
Yes button to continue.
Now, you can check the newly added record in tblBooks (see figure below).
12
Unit 3: Structured Query Language
Another form of the INSERT statement allows the user to specify explicit
attribute names that correspond to the values provided in the INSERT
command. This is useful if a relation has many attributes but only a few of
those attributes are assigned values in the new tuple. In the example below, the
values are not in the same order with that of the columns; however, we
specified the order of the columns in the statement (Title, Author, BookID,
YearPublished, Price).
UPDATE Command
If there are existing records and you need to modify for some reasons, you can
always do that using the UPDATE command. The UPDATE command is used
to modify attribute values of one or more selected tuples. A WHERE clause in
the UPDATE command selects the tuples to be modified from a single
relation. An additional SET clause in the UPDATE command specifies the
attributes to be modified and their new values. The example below shows how
to change the author of a book.
The example above uses the column BookID to select a specific book (BookID
= ‘CB-006’). Check the updated record and you can see that the author of the
book with BookID CB-006 has been changed. You can also modify multiple or
all columns in a single UPDATE command by using a comma (,) to separate
each column as shown below.
13
Unit 3: Structured Query Language
DELETE Command
If have entered a wrong data, you can delete it by using the DELETE
command. The DELETE command removes tuples (records) from a relation.
It includes a WHERE clause, similar to that used in an SQL query, to select
the tuples to be deleted. Tuples are explicitly deleted from only one table at a
time. A missing WHERE clause specifies that all tuples in the relation are to
be deleted; however, the table remains in the database as an empty table
(Elmasri, et al., 2011). The following example shows how to delete a record in
tblBooks.
Application
Sample
14
Unit 3: Structured Query Language
Learning Objectives
After completing this topic, the students should be able to demonstrate basic
skill in using the different relational or comparison operators to retrieve
records.
Presentation of Contents
Relational Operators or Comparison Operators are the operators which are
used for comparison between two values. To understand the comparison
operator better, we will take example of tblBooks table as shown below. Some
examples are also presented in the next topic.
15
Unit 3: Structured Query Language
or not, if values Output:
are not equal then Fundamentals of DBMS
condition becomes SQL Basics
true. Adobe Photoshop CS3
Checks if the value SELECT Title FROM tblBooks
of left operand is WHERE Price > 2000;
greater than the
>
value of right Output:
(Greater Than)
operand, condition Fundamentals of DBMS
becomes true if it SQL Basics
is yes. Adobe Photoshop CS3
Checks if the value SELECT Title FROM tblBooks
of left operand is WHERE Price < 2000;
< less than the value
(Less Than) of right operand, Output:
condition becomes There is no output because is no
true if it is yes. book with price less than 2000.
SELECT Title FROM tblBooks
WHERE Price >= 2000;
Output:
Checks if the value
Fundamentals of DBMS
of left operand is
SQL Basics
>= greater than or
Introduction to Database
(Greater than or equal to the value
SQL: Concepts and Applications
Equal To) of right operand,
Advanced SQL
condition becomes
Adobe Photoshop CS3
true if its yes.
*All records were retrieved
because all the price is greater or
equal to 2000.
Checks if the value SELECT Title FROM tblBooks
of left operand is WHERE Price <= 2000;
<= less than or equal
(Less than or to the value of Output:
Equal To) right operand, Introduction to Database
condition becomes SQL: Concepts and Applications
true if it is yes. Advanced SQL
Application
Sample
16
Unit 3: Structured Query Language
Learning Objectives
After completing this topic, the students should be able to demonstrate skill in
using the different logical operators in SQL such as AND, OR, and NOT.
Logical OR
True True
True False
False True
False False
Logical NOT
True
False
Presentation of Contents
SQL Logical Operators such as AND, OR, and NOT are used to combine
multiple conditions to filter the result of the query (JournalDev, n.d.). In
addition, these Operators are used to specify conditions in an SQL statement
and to serve as conjunctions for multiple conditions in a statement
(TutorialsPoint, n.d.). This happens when a single condition is not enough to
filter the desired result.
AND
SQL AND operator are used when we want to combine multiple conditions as
part of the WHERE clause. The result set will be filtered based on the
satisfaction of both the condition. So, if both the conditions are true then only
the result will be filtered. To combine multiple conditions, we can use more
than one AND as part of the WHERE clause (JournalDev, n.d.). The following
example shows how to filter records using the AND Operator.
17
Unit 3: Structured Query Language
In the example above, we intend to select books which price is greater than
2000 and the year published is less than 2019 (earlier than 2019). As a result,
the query will only display two records where both conditions result to TRUE
as shown below. You can observe that both books have publication year
earlier than 2019 (YearPublished < 2019) and price is higher or greater than
2000 (Price > 2000). You can use as many conditions as needed to filter the
desired record.
OR
OR operator is used when we want to combine multiple conditions as part of
the WHERE clause. The result set will be filtered based on satisfaction of at
least one of the conditions. So, if at least one of the conditions are true than
only the result will be filtered. To combine multiple conditions, we can use
more than one OR as part of the WHERE clause (JournalDev, n.d.). The
example below shows how to retrieve records using OR operator.
Based on the sample statement above, you have observed that only the first
condition is true (there are records which Price is 2000) and the second
condition is false (there are no records which YearPublished is less than
2015). Again, unlike the AND logical operator, OR statement will give a
result as long as there is at one of the conditions results to true.
This time, we will have another example of the OR logical operator. You will
observe in the example below that both of the conditions are true.
18
Unit 3: Structured Query Language
Based on the statement above, you have observed that the first condition is
looking for records with the Price of 2000 and YearPublished of greater than
2018. In the result below, the Price of the books is 2000; this means that the
first condition is true to the first three records even if the YearPublished of the
first record is FALSE to the second condition. Likewise, the YearPublished of
the fourth record is greater than 2018; this means the second condition is true
while the second condition is false to the fourth record. You have further
observed that even if the other conditions are false as long as there is at least
one true among the conditions, the records will still be retrieved.
NOT
SQL NOT operator is used when we want to filter result set when the
condition is not satisfied in the WHERE clause (JournalDev, n.d.). In other
words, it tries to reverse the result of the condition (true becomes false, and
false becomes true). For you to understand better, below is a statement with
NOT operator.
Based on the example above, the condition looks for records which Price is
2000; however, the not reversed it. In other words, the statement is selecting
records which Price is NOT EQUAL to 2000.
19
Unit 3: Structured Query Language
Application
Sample
Feedback References
Elmasri, R., & Navathe, S. (2011). Fundamentals of Database Systems (6th
ed.). USA: Addison-Wesley.
JournalDev. (n.d.). SQL AND, OR, NOT – SQL Logical Operators. Retrieved
August 6, 2020, from JournalDev:
https://www.journaldev.com/19147/sql-and-or-not-sql-logical-
operators
TutorialsPoint. (n.d.). SQL Operators. Retrieved August 6, 2020, from
TutorialsPoint: https://www.tutorialspoint.com/sql/sql-operators.htm
20