Week 4 Practical Activity 1
Week 4 Practical Activity 1
Goals Extract the desired subset of data from a table and present in
a given order.
General tasks SELECT rows using basic syntax structure, including WHERE
clause and ORDER BY clause.
Use comparison operators with the search condition.
Use logical operators AND, OR, and NOT to query data.
Use LIKE for pattern matching, BETWEEN for range filtering,
and IN for list filtering.
Sometimes you will want to see only records meeting certain conditions, which is a
process known as selection. In addition if the data is displayed in a sorted order, then
the output will be easier to read. The SELECT statement includes a WHERE clause that
is used to specify a search condition and also an ORDER BY clause that is used to
display results in a specific sequence. Both the WHERE clause and the ORDER BY
clause are optional as shown in the SELECT statement syntax below:
A WHERE clause identifies a condition or requirement that must be met for a record to
be included in the results. For example, to display a list containing the last name of
every customer living in NSW, you use the SQL statement shown below:
In the WHERE clause, WHERE is the keyword, state is the name of the column to be
searched, the comparison operator “equal to” (=) means the record must contain the
exact value specified, and that is NSW. Note also the single quotation marks around
NSW, which designate it as a string literal. Also the value NSW is in uppercase letters to
match the format in which data is entered in the State field.
Check the data type of the table by using the Object List browser (Alt+3). It the field is
not numeric, for example VARCHAR2, then single quotation marks will be required for
the search condition.
SELECT *
FROM books
WHERE pubdate = '21-JAN-2011';
Comparison Operators
Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> , != Not equal to
LIKE Used for pattern matching
BETWEEN Used for range filtering
IN Used for list filtering
IS NULL Used when testing for NULL values
Table 1: SQL Comparison Operators
Note that a dollar sign is not included. The dollar sign is treated as a formatting
character, so $55 is not equivalent to 55.
SELECT title
FROM books
WHERE title > 'HO';
You can also use arithmetic expressions in the WHERE clause as shown by the
following example that lists all books having a profit of less than 20% of the book’s cost.
The following example uses the “not equal to” comparison operator to list customers who
do not live in NSW:
The following example lists all orders place before July 2011:
The following example shows use of the BETWEEN conditional operator to match items
where the salary is between 2000 and 3000:
The following statement lists all books published between 1-JAN-10 and 31-DEC-10:
The next example shows how an alphabetical list of book titles can be returned with the
BETWEEN ... operator:
SELECT title
FROM books
WHERE title BETWEEN 'A' AND 'D';
IN Operator
The IN operator returns records matching one of the values listed in the condition. The
list must be separated by commas and the entire list enclosed in parenthesis.
The following example shows use of the IN conditional operator to match items within a
given list:
The following example lists all customers located in NSW or VIC. State names are
delimited in single quotation marks because they are string literals.
The logic can be reversed by using NOT operator with the comparison operators. For
example, if you want all customers in states other than NSW or VIC, then add NOT to
the query as shown below:
Like only works with character strings, not numeric values or datetimes.
SELECT lastname
FROM customers
WHERE lastname LIKE 'P%';
A like condition can be negated by using NOT LIKE as shown by the following example:
SELECT lastname
FROM customers
WHERE lastname NOT LIKE 'P%';
The following example lists customers with a four character lastname ending in RD:
The following example searches with the LIKE operator and a combination of wildcard
characters to return as list of books where the ISBN starts with any character, the
second character is the number 4, followed by any characters, and ending with a zero.
For example: the following SQL statement returns incidents of 50% from the named
column:
Logical operators are used when you need to search for records based on two or more
conditions. The logical operators AND and OR are used to combine search conditions.
The NOT operator is used to reverse the logic of the search conditions.
When more than one operator is used in a statement, the order of precedence is:
NOT
AND
OR
The following example lists books published by Publisher Id = 3 and books in the
COMPUTER Category (Only books matching both conditions will be listed):
Whereas, the following example lists all books that are published by Publisher Id = 3 or
books in the COMPUTER Category (Books matching one or the other search condition
will be listed):
The following example uses both AND and OR in the WHERE clause:
SELECT *
FROM books
WHERE category = 'COMPUTER' OR pub_Id = 4
AND cost > 15;
If you want to find any book costing more than $15.00 that is published by Publisher 4 or
is in the COMPUTER category, then you must use parenthesis to identify any books
published by Publisher 4 or COMPUTER category first. After books meeting the
Category or Publisher condition are found, then the cost condition is evaluated, and only
those records with a cost higher than $15.00 are displayed. The following query will
return different results to the example shown previously:
SELECT *
FROM books
WHERE (category = 'COMPUTER' OR pub_Id = 4)
AND cost > 15;
Note that it is best not to rely on the evaluation order when mixing AND and OR. It
is recommended that you use parentheses to control the order and to make it
more explicit.
When you are performing arithmetic operations or search conditions, NULL values can
cause unexpected results. A NULL value means no value has been stored, that is, a
NULL is the absence of data in a field. Consequently, when searching for NULL values,
you cannot use the equal sign (=) because there is no value to use for comparison in the
search condition. When checking for NULL values, you are actually checking the status
of the column; does data exist or not? If you need to identify records that have NULL
value, you must use the IS NULL comparison operator.
For example, when an order is shipped to a customer, the shipping date is entered in the
Orders table. If a date does not appear in the ship_date field, then the order has not
been shipped yet. The following example will display all orders that do not have a
ship_date:
When searching for orders that have shipped (that is, the ship_date column contains an
entry), then simply add the logical operator NOT. The following example returns orders
which have a ship_date:
When you enter a SELECT statement the order of rows is not defined. You may want to
see the rows in a specific order based on a column or columns. It is not necessary to
display a sort column in the result of the SELECT statement.
The ORDER BY clause, used to display query results in a sorted order, is listed at the
end of the SELECT statement, as shown below:
SELECT *
FROM publisher
ORDER BY name;
In the syntax ASC stands for ascending order. The default order is ascending, so there
is no need to type ASC for ascending order. The keyword DESC stands for descending
or reverse order.
When sorting in ascending order, numeric values are displayed from the smallest to the
largest value, character values are displayed in alphabetical order, and date values are
displayed with the earliest date first. The NULL values are displayed last in ascending
order. In descending order, the effect is reversed for all data types and NULL values are
displayed at the top in descending order.
The following example sorts the list of publishers in descending order by the publisher
name:
SELECT *
FROM publisher
ORDER BY name DESC;
If a column alias is given to a field in the SELECT statement, you can reference the field
in the ORDER BY clause with the column alias, as shown by the following example:
You can also use the ORDER BY clause with the optional NULLS FIRST or NULLS
LAST keywords to change the order for listing NULL values. By default NULL values are
listed last when results are sorted in ascending order and first when sorted in
descending order. The following example lists the last and first name of each customer
from NSW and the customer number of the person who referred the customer. The
Secondary Sort
Secondary sort allows you to specify a second field to sort by if an exact match occurs
between two or more rows in the primary sort. For example, when listing customers the
following example sorts first by the state and then sub sorts by the city name:
The following example sorts orders by shipping date in descending order so that the
most recent will appear first and a secondary sort by order number:
Oracle also provides an abbreviated method for referencing the sort column if the
column name is used in the SELECT clause. The following example will produce the
same result as the previous one above.
This will sort first by the state name in descending order and then by the city name. It is
generally better to specify the column names used with the ORDER BY clause.
Exercise Overview
Detailed Instructions
You are going to use MySQL to create a new database called books for this lab.
24. List the type and price of all Oracle Server books over 1000 pages to verify the
update.
SELECT title, price
FROM books
WHERE category = 'Oracle Server'
Copyright 2010 One-To-One Computer Services Pty. Ltd 12
AND num_pages >1000;
- or-
The IN operator is easier to use when you need to match a number of values in a
list.
31. List all properties for rent where the property is not in Aberdeen or London.
SELECT * FROM PropertyForRent WHERE city NOT IN( 'Aberdeen' ,
'London');
Copyright 2010 One-To-One Computer Services Pty. Ltd 15
32. List all properties for rent where the property is not in Aberdeen or London and
the type is not a flat.
SELECT * FROM PropertyForRent WHERE city NOT IN( 'Aberdeen' ,
'London') AND type NOT IN( 'Flat');
33. List all properties for rent where the property is situated in a road.
SELECT * FROM PropertyForRent WHERE street LIKE '%rd%' ;
34. List all properties for rent where the property is is situated in a road or a street.
SELECT * FROM PropertyForRent WHERE street LIKE '%rd%' OR street
LIKE '%st%';
35. List all staff where the position is either Manager or Supervisor.
SELECT * FROM staff WHERE position ='manager' OR position =
'supervisor';
36. List all staff where the position is NOT Manager.
SELECT * FROM staff WHERE NOT position ='manager';
37. List all properties for staff where the sex is male and the branch is B003.
SELECT * FROM staff WHERE sex ='m' AND branchNo = 'B003';
38. List all staff where the sex is male and the position is manager or the sex is male
and the position is supervisor.
SELECT * FROM staff WHERE sex ='m' AND position = 'manager' OR sex
='m' AND position = 'supervisor';
39. List all staff where the salary is greater than or equal to 18000 and the branchNo
is B003, or staff located at branchNo B005 irrespective of salary.
SELECT * FROM staff WHERE salary >= 18000 AND branchNo = 'B003' OR
branchNo = 'B005';
40. List all staff where the branchNo is B003 or branchNo is B005 and the salary is
greater than or equal to 18000. Note how the parenthesis changes the result.
SELECT * FROM staff WHERE salary >= 18000 AND (branchNo = 'B003' OR
branchNo = 'B005');
41. List all records from the viewing table where no comment has been entered.
SELECT * FROM viewing WHERE comments IS NULL;
42. List all records from the viewing table where a comment has been entered.
SELECT * FROM viewing WHERE comments IS NOT NULL;
43. List all staff located at branchNo B003 and records ordered by last name and
then first name.
SELECT * FROM staff WHERE branchNo = 'B003' ORDER BY lName, fName;
44. List all staff located at branchNo B003 and records ordered by salary in
descending (highest to lowest) sort order.
SELECT * FROM staff WHERE branchNo = 'B003' ORDER BY salary DESC;
45. List all staff located records ordered by branchNo in ascending order (a to z) and
sub sorted in order of salary in descending (highest to lowest) sort order.
SELECT * FROM staff ORDER BY branchNo, salary DESC;
46. List all staff located records ordered by the second column specified (lName) and
sub sorted in order of the first column specified (fName).
SELECT fName, lName FROM staff ORDER BY 2, 1;
Note that you should get an error when you try to insert records with
propertyNo PG16. Try to work out why the error occurs or why the record
is not inserted. You will have to modify something in order to insert the
record. Hint: Check the propertyNo values in the PropertyForRent table.