0% found this document useful (0 votes)
30 views58 pages

03 Restricting and Sorting Data

This document covers SQL concepts related to restricting and sorting data, including the use of WHERE clauses, comparison operators, logical operators, and the ORDER BY clause. It also discusses the FETCH clause for limiting rows and substitution variables for dynamic queries. The document includes examples and exercises to reinforce understanding of these SQL functionalities.

Uploaded by

Wan Sabrina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views58 pages

03 Restricting and Sorting Data

This document covers SQL concepts related to restricting and sorting data, including the use of WHERE clauses, comparison operators, logical operators, and the ORDER BY clause. It also discusses the FETCH clause for limiting rows and substitution variables for dynamic queries. The document includes examples and exercises to reinforce understanding of these SQL functionalities.

Uploaded by

Wan Sabrina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

03 – Restricting and

Sorting Data
Lesson Objectives
After completing this lesson, you should be able to:
• Applying Rules of precedence for operators in an expression
• Limiting Rows Returned in a SQL Statement
• Sorting Data
• Using Substitution Variables
• Using the DEFINE and VERIFY commands
Limiting Rows Using a WHERE clause
Limiting Rows Using a Selection
• Restrict the rows that are returned by using the WHERE clause
SELECT *|{[DISTINCT] column|expression [alias],...}
FROM table
[WHERE condition(s)];
• Where clause is optional, condition can include column names, character strings,
expressions, constants and comparison operator
• Character strings and date values are enclosed with single quotation marks.
• Character values are case-sensitive and date values are format-sensitive.
• The default date display format is DD-MON-RR
Limiting Rows Using a Selection
SELECT employee_id, last_name, job_id, department_id
FROM employees
WHERE department_id = 90;

SELECT last_name, job_id, department_id


FROM employees
WHERE last_name = 'Whalen';

SELECT last_name
FROM employees
WHERE hire_date = '17-FEB-96';
Limiting Rows Using a Selection – Comparison
Operator
Operator Function
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> or != Not equal to
Between … AND … Between two values inclusive
In (Set) Match any of the list of values
Like Match a character pattern
Is Null Is a null value
Limiting Rows Using a Selection – Comparison
Operator
• Display employees whose salary is less than or equal to 3000;
SELECT last_name, salary
FROM employees
WHERE salary <= 3000 ;

• Display employees whose salary between 2500 and 3500

SELECT last_name, salary


FROM employees
WHERE salary BETWEEN 2500 AND 3500 ;

Lower limit Upper limit


Limiting Rows Using a Selection – Comparison
Operator
• Display employees whose manager id is either 100, 101 or 201
SELECT employee_id, last_name, salary, manager_id
FROM employees
WHERE manager_id IN (100, 101, 201) ;
Limiting Rows Using a Selection – Comparison
Operator
• Display employees whose manager id is either ST_MAN or HR_RE
SELECT employee_id, last_name, salary, manager_id
FROM employees
WHERE job_id IN ('ST_MAN', 'HR_RE');
Limiting Rows Using a Selection – Comparison
Operator (Wildcard character)
• You may not always know the exact value to search for, you can perform a search
that match by using the LIKE operator → wildcard searches
Character Symbol Function
Percentage Sign _ Matches exactly one character
Underscore % Matches any number of characters including 0 or more characters

• You can combine the two wildcard characters (%, _) with literal characters for pattern
matching
• The Like operator can also be used without wildcard characters, but it is nonsense
because it will be equal to ( = ) operator and Like is slower than ( = ) operator
Limiting Rows Using a Selection – Comparison
Operator (Wildcard character)
• Search conditions can contain either literal characters or numbers:
• % denotes zero or many characters

SELECT first_name
FROM employees
WHERE first_name LIKE 'S%';

• _ denotes one character.

SELECT last_name
FROM employees
WHERE last_name LIKE '_o%';
Limiting Rows Using a Selection – Comparison
Operator (Wildcard character)
• Search for employees whose job_id contain the character sequence “SA_”:

SELECT employee_id, last_name, job_id


FROM employees
WHERE job_id LIKE '%SA\_%’ EXCAPE ’\’;
Limiting Rows Using a Selection - NULL
• Either to include the IS NULL or IS NOT NULL, null value cannot be equal or
unequal to any value
• Null value = unavailable, unassigned, unknown or inapplicable,

SELECT last_name, manager_id


FROM employees
WHERE manager_id IS NULL ;
Conditions Using the Logical Operators
• Logical conditions are used to combine two or more conditions to produce a
single result based on them

Operator Function
AND Returns True is both component conditions are true
OR Returns True if either component conditions are true
NOT Return True if the following condition is false
Conditions Using the Logical Operators - AND
• Both the component conditions must be true for any record to be selected
• Truth Table AND TRUE FALSE NULL
TRUE TRUE FALSE NULL
FALSE FALSE FALSE FALSE
NULL NULL FALSE NULL

SELECT employee_id, last_name, job_id, salary


FROM employees
WHERE salary >= 10000
AND job_id LIKE '%MAN%' ;
Conditions Using the Logical Operators - OR
• Either component condition can be true for any record to be selected
• Truth Table OR TRUE FALSE NULL
TRUE TRUE TRUE TRUE
FALSE TRUE FALSE FALSE
NULL TRUE FALSE NULL

SELECT employee_id, last_name, job_id, salary


FROM employees
WHERE salary >= 10000
OR job_id LIKE '%MAN%' ;
Conditions Using the Logical Operators - NOT
• The NOT operator can also be used with other SQL operators, such as
BETWEEN, LIKE, and NULL
• Truth Table NOT TRUE FALSE NULL
FALSE TRUE NULL

SELECT last_name, job_id


FROM employees
WHERE job_id
NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;
Rules of Precedence
• Determine the order in which Order Operator

expressions are evaluated first 1 Arithmetic operators


2 Concatenation operator
• You can override the default order
3 Comparison conditions
by using parentheses around the
4 IS [NOT] NULL, LIKE, [NOT] IN
expressions
5 NOT equal to
6 [NOT] BETWEEN
7 NOT logical condition
8 AND logical condition
9 OR logical condition
Rules of Precedence

NOT USING PARENTHESES USING PARENTHESES


SELECT last_name, job_id, salary SELECT last_name, job_id, salary
FROM employees FROM employees
WHERE job_id = 'SA_REP' WHERE (job_id = 'SA_REP'
OR job_id = 'AD_PRES' OR job_id = 'AD_PRES')
AND salary > 15000; AND salary > 15000;
Sorting rows using the ORDER BY clause
Using the ORDER BY Clause
• Sort retrieved rows with the ORDER BY clause:
• ASC: Ascending order, default
• DESC: Descending order

• NULL values are displayed last in ascending order


• The ORDER BY clause comes last in the SELECT statement:

SELECT *|{[DISTINCT] column|expression [alias],...}


FROM table
[WHERE condition(s)]
[ORDER BY {column, expr, alias} [ASC|DESC]] ;
Using the ORDER BY Clause

SELECT last_name, job_id, department_id, hire_date


FROM employees
ORDER BY hire_date ;
Using the ORDER BY Clause
• Sorting in descending order:
SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date DESC ;

• Sorting by column alias:

SELECT employee_id, last_name, salary*12 annsal


FROM employees
ORDER BY annsal ;
Using the ORDER BY Clause
• Can also be used with the column position in the SELECT list or the column
order in the database

SELECT last_name, job_id,


department_id, hire_date
FROM employees
ORDER BY 1;
Using the ORDER BY Clause
• Column order in the database, but NOT RECOMMENDED
SELECT *
FROM employees
ORDER BY 3 desc;
Using the ORDER BY Clause
• Sorting by multiple columns
SELECT last_name, department_id, salary
FROM employees
ORDER BY department_id, salary DESC;

• Sorting by multiple columns using aliases


SELECT last_name, department_id, salary s
FROM employees
ORDER BY department_id, s DESC;
Using the ORDER BY Clause
• The NULLS FIRST or NULLS LAST operates are used for changing the order of
the NULL values

SELECT last_name, manager_id, department_id, salary


FROM employees
ORDER BY manager_id NULLS FIRST;
Using the ORDER BY Clause
• Another example on NULLS LAST
SELECT first_name, last_name, commission_pct c
FROM employees
ORDER BY commission_pct desc;

SELECT first_name, last_name, commission_pct c


FROM employees
ORDER BY commission_pct desc NULLS LAST;
Row Limiting Clause – Fetch Clause
• The FETCH clause is used in conjunction with the SELECT and ORDER BY
clauses to limit the rows and retrieve a portion of the returning rows

SELECT *|{[DISTINCT] column|expression [alias],...}


FROM table
[WHERE condition(s)]
[ORDER BY {column, expr, alias} [ASC|DESC]]
[OFFSET offset {ROW | ROWS}]
[FETCH {FIRST | NEXT} [{row_count | percent PERCENT}] {ROW|ROWS}
{ONLY | WITH TIES}];
Row Limiting Clause – Fetch Clause
• OFFSET: the number of rows to skip before starting to return rows
• ROW | ROWS: Both of them can be used based on the returning rows in order to increase the semantic clarify
• FETCH: specifies the number of rows or percentage of rows to return
• FIRST | NEXT: You can use any of them based on the situation
• row_count | percent PERCENT:
• the row_count to specify the number of rows to return,
• the PERCENT specifies the percentage of the total number of selected rows to return

• ONLY | WITH TIES:


• ONLY is used to return exactly the specified number of rows or percentage of row
• The WITH TIES returns extra rows with the same value (if exists) as the last row fetched, if you specific the WITH
TIES, then you must specify ORDER BY clause, else no additional rows will be returned
Row Limiting Clause – Fetch Clause
SELECT FIRST_NAME, LAST_NAME, SALARY SELECT first_name, last_name, salary
FROM employees
FROM EMPLOYEES
ORDER BY salary DESC
ORDER BY SALARY DESC OFFSET 1 ROW;
Row Limiting Clause – Fetch Clause
SELECT FIRST_NAME, LAST_NAME, SALARY SELECT first_name, last_name, salary
FROM EMPLOYEES FROM employees
ORDER BY SALARY DESC ORDER BY salary DESC
OFFSET 1 ROW OFFSET 1 ROW
FETCH FIRST 10 ROWS ONLY; FETCH FIRST 10 ROWS WITH TIES;
Row Limiting Clause – Fetch Clause
SELECT first_name, last_name, salary
SELECT FIRST_NAME, LAST_NAME, SALARY
FROM employees
FROM EMPLOYEES
ORDER BY salary DESC
OFFSET 1 ROW
OFFSET 1 ROW
FETCH FIRST 10 ROWS WITH TIES;
FETCH FIRST 10 ROWS WITH TIES;

If you don’t specify the


ORDER BY clause, no
additional rows will be
returned
Substitution variables
Substitution Variables
• Use substitution variables to:
• Temporarily store values with single-ampersand (&) and double-ampersand (&&)
substitution
• Use substitution variables to supplement the following:
• WHERE conditions
• ORDER BY clauses
• Column expressions
• Table names
• Entire SELECT statements
Using the Single-Ampersand Substitution Variable
• Use a variable prefixed with an ampersand (&) to prompt the user for a value:

SELECT employee_id, last_name, salary, department_id


FROM employees
WHERE employee_id = &employee_num;
Using the Single-Ampersand Substitution Variable
Character and Date Values with Substitution
Variables
• Use single quotation marks for date and character values

SELECT last_name, department_id, salary*12


FROM employees
WHERE job_id = '&job_title';
Specifying Column Names, Expressions, and Text
SELECT employee_id, last_name, job_id,&column_name
FROM employees
WHERE &condition
ORDER BY &order_column;
Using the Double-Ampersand Substitution Variable
• Use double ampersand (&&) if you want to reuse the variable value without
prompting the user each time:

SELECT employee_id, last_name, job_id, &&column_name


FROM employees
ORDER BY &column_name;
Substitution variables –
DEFINE and VERIFY commands
Using the DEFINE Command
• Use the DEFINE command to create and assign a value to a variable.
• Use the UNDEFINE or UNDEF command to remove a variable.

DEFINE employee_num = 200

SELECT employee_id, last_name, salary, department_id


FROM employees
WHERE employee_id = &employee_num ;

UNDEFINE employee_num
Using the VERIFY Command
• Use the VERIFY command to toggle the display of the substitution variable, both
before and after SQL Developer replaces substitution variables with values:
SET VERIFY ON
SELECT employee_id, last_name, salary
FROM employees
WHERE employee_id = &employee_num;
Substitution variables –
ACCEPT/PROMPT
Using the ACCEPT/PROMPT Command
• Most reliable and robust method for getting input from the user
• The ACCEPT command takes the input from the user and stores it in a user variable
• While the PROMPT command is used to display a message to the user for supplying
a brief explanation of what your script is going to accomplish

ACCEPT emp_id Prompt 'Please enter a valid Employee ID:';


Using the ACCEPT/PROMPT Command
ACCEPT emp_id Prompt 'Please enter a valid Employee ID:’;
Select employee_ID, first_name, last_name, salary
from employees
where employee_id = &emp_id;

• To undefine the value, you are require to issue the UNDEFINE command
Using the ACCEPT/PROMPT Command
ACCEPT min_salary PROMPT 'Please enter the MINIMUM salary';
ACCEPT max_salary PROMPT 'Please enter the MAXIMUM salary';
Select employee_ID, first_name, last_name, salary
from employees
where salary BETWEEN &min_salary and &max_salary;
Exercise
1. Which two statements are true regarding the ORDER BY clause? (Choose two.)
A. It is executed first in the query executionSELECT name, address FROM customers;
B. It must be the last clause in the SELECT statement
C. It cannot be used in a SELECT statement containing a HAVING clause
D. You cannot specify a column name followed by an expression in this clause
E. You can specify a combination of numeric positions and column names in this
clause
Exercise
2. The STUDENT_GRADES table has these columns:

STUDENT_ID NUMBER(12)
SEMESTER_END DATE
GPA NUMBER(4, 3)

The registrar requested a report listing the students' grade point averages (GPA) sorted from highest grade point
average to lowest. Which statement produces a report that displays the student ID and GPA in the sorted order
requested by the registrar?

A. SELECT student_id, gpa FROM student_grades ORDER BY gpa ASC;


B. SELECT student_id, gpa FROM student_grades SORT ORDER BY gpa ASC;
C. SELECT student_id, gpa FROM student_grades SORT ORDER BY gpa;
D. SELECT student_id, gpa FROM student_grades ORDER BY gpa;
E. SELECT student_id, gpa FROM student_grades SORT ORDER BY gpa DESC;
F. SELECT student_id, gpa FROM student_grades ORDER BY gpa DESC;
Exercise
3. The PRODUCTS table has these columns:

PRODUCT_ID NUMBER(4)
PRODUCT_NAME VARCHAR2(45)
PRICE NUMBER(8, 2)

Evaluate this SQL statement:

SELECT *
FROM PRODUCTS
ORDER BY price, product_name;

What is true about the SQL statement?

A. The results are not sorted.


B. The results are sorted numerically.
C. The results are sorted alphabetically.
D. The results are sorted numerically and then alphabetically.
Exercise
4. You need to extract details of those products in the SALES table where the
PROD_ID column contains the string '_D123'. Which WHERE clause could be
used in the SELECT statement to get the required output?

A. WHERE prod_id LIKE '%_D123%' ESCAPE ‘_’


B. WHERE prod_id LIKE '%\_D123%' ESCAPE '\’
C. WHERE prod_id LIKE '%_D123%' ESCAPE '%_'
D. WHERE prod_id LIKE '%\_D123%' ESCAPE '\_'
Exercise
5. The CUSTOMERS table has these columns:

CUSTOMER_ID NUMBER(4) NOT NULL


CUSTOMER_NAME VARCHAR2(100) NOT NULL
STREET_ADDRESS VARCHAR2(150)
CITY_ADDRESS VARCHAR2(150)
STATE_ADDRESS VARCHAR2(50)
PROVINCE_ADDRESS VARCHAR2(50)
COUNTRY_ADDRESS VARCHAR2(50)
POSTAL_CODE VARCHAR2(12)
CUSTOMER_PHONE VARCHAR2(20)

A promotional sale is being advertised to the customers in France. Which WHERE clause identifies customers that are located in
France?
A. WHERE lower(country_address) = "france"
B. WHERE lower(country_address) = 'france'
C. WHERE lower(country_address) IS 'france'
D. WHERE lower(country_address) = '%france%'
E. WHERE lower(country_address) LIKE %france%
Exercise
6. Which substitution variable would you use if you want to reuse the variable without
prompting the user each time?

A. &
B. ACCEPT
C. PROMPT
D. &&
Summary
• In this lesson, you should have learned how to:
• Use the WHERE clause to restrict rows of output:
• Use the comparison conditions
• Use the BETWEEN, IN, LIKE, and NULL operators
• Apply the logical AND, OR, and NOT operators
• Use the ORDER BY clause to sort rows of output:
• Use ampersand substitution and ACCEPT to restrict and sort output at
run time
Assignment – HR Schema
1. Display the job and salary for all employees where the salary is less than 5,000
2. Display the names and salaries of people working in department 80 who earn
a salary of more than 10000
3. Display a list of employees who were hired during or after the year 2002 order
by employee name descending
4. Display a list of departments that do not start with the letter R
5. Display a list of employees whose commission is greater than 0.5
Assignment – HR Schema
6. Display a list of employees in sequence of their hire date, with the most
recently hired employee showing at the top of the list
7. Display the names of all employees whose salary is between 2500 and 3850
inclusive.
8. Display the name and job all employees who haven’t been assigned a
department
9. Display the name and salary of employees earning more than 5000
Assignment – HR Schema
10. Display the employee name and department number for the employee number
151
11. Display the employee name and salary for all employees whose salary is not in the
range 3000 to 11000
12. Display the employee name and department number of all employees in
department 20 or 50 in alphabetical order by name
13. List the name and salary of employees who earn between 1250 and 3000 and are
in department 20 or 10. Label the columns Employees and Monthly Salary
respectively
Assignment – HR Schema
14. Display name and hiredate of all employees who was hired in 1981
15. Display the name and job title of all employees who do not have a manager
16. Display the name, salary and commission for all employees who earn
commissions. Sort data in descending order of salary and commissions

You might also like