0% found this document useful (0 votes)
0 views13 pages

1.3 - Restricting and Sorting Data - Lecture Note

This document provides an overview of SQL data restriction and sorting techniques, focusing on the use of the WHERE clause to limit query results. It covers various comparison conditions, logical operators, and the ORDER BY clause for sorting data. Additionally, it discusses substitution variables in SQL*Plus for user input during query execution.

Uploaded by

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

1.3 - Restricting and Sorting Data - Lecture Note

This document provides an overview of SQL data restriction and sorting techniques, focusing on the use of the WHERE clause to limit query results. It covers various comparison conditions, logical operators, and the ORDER BY clause for sorting data. Additionally, it discusses substitution variables in SQL*Plus for user input during query execution.

Uploaded by

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

ITE 014 | INFORMATION MANAGEMENT

1.3 RESTRICTING AND SORTING DATA method of restriction is the basis of the WHERE
clause in SQL.
Objectives
After completing this lesson, you should be able to
do the following: Limiting the Rows That Are Selected
 Execute a SQL SELECT statement in solving Restrict the rows that are returned by using the
problems. WHERE clause:
The WHERE clause follows the FROM clause.
 Use the WHERE clause function to limit the
rows of output.

Introduction
Overview
You can restrict the rows that are returned from the
When retrieving data from the database, you may query by using the WHERE clause. A WHERE clause
need to do the following: contains a condition that must be met, and it
directly follows the FROM clause. If the condition is
 Restrict the rows of data that are displayed
true, the row meeting the condition is returned.
 Specify the order in which the rows are
Syntax:
displayed
 WHERE: Restricts the query to rows that
This lesson explains the SQL statements that you
meet a condition.
use to perform these actions.
 Condition: Composed of column names,
expressions, constants, and a comparison
Limiting Rows Using a Selection operator.
The WHERE Clause Can Compare:
 Values in columns
 Literal values
 Arithmetic expressions
 Functions
It consists of three elements:
1. Column name
2. Comparison condition
3. Column name, constant, or list of values

In the example in the slide, assume that you want


to display all the employees in department 90. The
rows with a value of 90 in the DEPARTMENT_ID
column are the only ones that are returned. This
ITE 014 | INFORMATION MANAGEMENT
Using the WHERE Clause

Date Storage in Oracle Databases:


 Dates are stored in an internal numeric
format, which represents century, year,
month, day, hours, minutes, and seconds.
 The default date display is DD-MON-RR.
In the example, the SELECT statement retrieves the Note: For details about the RR format and changing
employee ID, name, job ID, and department the default date format, see the lesson titled
number of all employees who are in department "Using Single-Row Functions to Customize
90. Output."

Character Strings and Dates Comparison Conditions


 Character strings and date values are
enclosed in single quotation marks ('').
 Character values are case-sensitive, and
date values are format-sensitive.
 The default date format is DD-MON-RR.

Example:
Character strings and dates in the WHERE clause
must be enclosed in single quotation marks ('').
However, number constants should not be Comparison conditions are used to compare one
enclosed in single quotation marks. expression to another value or expression. They are
commonly used in the WHERE clause in the
All character searches are case-sensitive. following format:
In the following example, no rows are returned Syntax:
because the EMPLOYEES table stores all last names
in mixed case:
ITE 014 | INFORMATION MANAGEMENT
Examples:  The BETWEEN condition specifies a lower
limit and an upper limit.
 The SELECT statement returns rows from
the EMPLOYEES table for employees whose
salary is between $2,500 and $3,500.
 Values specified with BETWEEN are
 An alias cannot be used in the WHERE inclusive. The lower limit must be specified
clause. first.
 The symbols != and ^= can also represent You can also use the BETWEEN condition with
the not equal to condition. character values:

Using Comparison Conditions

Using the IN Condition


Use the IN membership condition to test for values
in a list.
In the example, the SELECT statement retrieves the
last name and salary from the EMPLOYEES table
for any employee whose salary is less than or equal
to $3,000.
 The WHERE clause contains an explicit value
(3000).
 This value is compared to the salary in the
SALARY column of the EMPLOYEES table.

Using the BETWEEN Condition  The IN condition is used to check if a value


exists within a specified set of values.
 It is also known as the membership
condition.
 The example retrieves employee numbers,
last names, salaries, and manager IDs for
employees whose manager ID is 100, 101,
or 201.
The IN condition works with any data type.

Use the BETWEEN condition to display rows based Example:


on a range of values.
ITE 014 | INFORMATION MANAGEMENT

LIKE Condition as a Shortcut for BETWEEN


The LIKE condition can sometimes be used instead
of the BETWEEN condition.
 If characters or dates are used in the list,
they must be enclosed in single quotation Example: Retrieve employees hired between
marks (' '). January 1995 and December 1995:

Using the LIKE Condition


The LIKE condition is used to perform wildcard
searches for valid search string values.
Search Conditions  The pattern %95 selects any date that ends
in '95', which covers the entire year 1995.
 Conditions can contain either literal
characters or numbers.
 Wildcard symbols used in the LIKE Combining Pattern-Matching Characters
condition:  The % and _ symbols can be combined in a
o % → Represents zero or more search pattern.
characters.  Example: Retrieve employees whose last
o _ → Represents a single character. names have 'o' as the second character:

Since you may not always know the exact value to


search for, the LIKE condition allows you to match
patterns using these wildcard characters.
This operation is known as a wildcard search.

Example: Searching for Names Beginning with 'S'


The following SELECT statement retrieves the first
names of employees whose names begin with  _o% → Ensures that the second character is
uppercase 'S': 'o', while the rest of the name can be
anything.

ESCAPE Option: Searching for % and _ Symbols


Literally
Sometimes, you need to search for % or _ as actual
 The uppercase S is used, so names starting characters rather than wildcards.
with lowercase 's' are not returned. Use the ESCAPE option to specify an escape
character.
Example: Search for job IDs containing ‘SA_’,
treating _ as a normal character:
ITE 014 | INFORMATION MANAGEMENT

 The ESCAPE option defines ‘\’ as the escape


character. Example: Employees Without a Commission

 The underscore (_) is now interpreted To retrieve employees who are not entitled to
literally instead of as a wildcard. receive a commission, use:

Using the NULL Conditions


The NULL conditions include:
 IS NULL → Tests for null values. WHERE commission_pct IS NULL;
 IS NOT NULL → Tests for non-null values.  This returns employees where
commission_pct is NULL.

Logical Conditions

Understanding NULL Values


 A NULL value means the value is
unavailable, unassigned, unknown, or A logical condition combines multiple conditions to
inapplicable. produce a single result or inverts the result of a
 NULL cannot be tested using = or != condition.
because NULL is not equal or unequal to  A row is returned only if the overall
any value. condition is TRUE.
 SQL provides three logical operators:
Example: Employees Without a Manager
o AND
The following query retrieves the last names and
o OR
managers of employees who do not have a
manager: o NOT
You can use several conditions in one WHERE
clause using the AND and OR operators.
ITE 014 | INFORMATION MANAGEMENT
Using the OR Operator
Using the AND Operator  The OR operator requires either condition
to be true for a row to be selected.
 The AND operator requires both conditions
to be true for a row to be selected.

Example: Employees with a Specific Job Title and


Salary
Example: Employees with a Specific Job ID or High
Salary

 Only employees whose job title contains


'MAN' and earn $10,000 or more are
selected.  Employees are selected if they either have a
 Character searches are case-sensitive (e.g., job ID containing 'MAN' or earn $10,000 or
'MAN' must be uppercase). more.

 Character strings must be enclosed in OR Truth Table


quotation marks.
OR TRUE FALSE NULL

TRUE TRUE TRUE TRUE


AND Truth Table
FALSE TRUE FALSE NULL
AND TRUE FALSE NULL
NULL TRUE NULL NULL
TRUE TRUE FALSE NULL

FALSE FALSE FALSE FALSE

NULL NULL FALSE NULL

Using the NOT Operator


ITE 014 | INFORMATION MANAGEMENT
 The NOT operator negates a condition,
selecting rows where the condition is false.
Rules of Precedence
 Parentheses can be used to override
default precedence rules.

Example: Employees Without Certain Job Titles

Understanding Precedence in SQL


 This query excludes employees with job IDs
IT_PROG, ST_CLERK, or SA_REP.  The order of precedence determines how
SQL evaluates expressions.
NOT Truth Table
 Operators with higher precedence are
NOT TRUE FALSE NULL evaluated first unless parentheses are used
to change the order.
FALSE TRUE NULL

Additional Examples Using NOT


Note: The NOT operator can also be used with
other SQL operators, such as BETWEEN, LIKE,
and NULL.

Example 1: Precedence of the AND Operator


Query without Parentheses
ITE 014 | INFORMATION MANAGEMENT
 The parentheses force SQL to process the
OR condition first, ensuring that only
presidents and sales representatives are
selected before filtering salaries.
🔹 Query Meaning:
Explanation: "Select employees who are either presidents or
sales representatives, but only if they earn more
 Two conditions are evaluated: than $15,000."
1. Condition 1: Employee has job ID
'AD_PRES' AND earns more than
$15,000. Using the ORDER BY Clause

2. Condition 2: Employee has job ID  Sort retrieved rows using ORDER BY.
'SA_REP'.  Sorting order options:
 Since AND has a higher precedence than o ASC (Ascending order, default).
OR, the query first checks if the employee is
a president earning more than $15,000. o DESC (Descending order).

 Then, it includes all employees who are  The ORDER BY clause must be the last
sales representatives (SA_REP), regardless clause in the SELECT statement.
of salary.
🔹 Query Meaning:
"Select employees who are presidents earning
more than $15,000 OR employees who are sales
representatives."

Example 2: Using Parentheses to Change


Precedence
Query with Parentheses

Syntax:

Explanation:
 Two conditions are evaluated: Components:
1. Condition 1: Employee has job ID  ORDER BY → Specifies the sorting order of
'AD_PRES' OR 'SA_REP' (evaluated the result set.
first due to parentheses).
 ASC → Sorts rows in ascending order
2. Condition 2: Employee earns more (default).
than $15,000.
 DESC → Sorts rows in descending order.
ITE 014 | INFORMATION MANAGEMENT
Key Notes:  Reverse the default sort order using DESC:
 If ORDER BY is not used, the order of rows
is undefined.
 The Oracle server may fetch rows in
different orders for the same query if
sorting is not explicitly defined.
🔹 Result: Sorts employees by most recent hire date
first.
Sorting
Default Sort Order (Ascending)
2. Using Column Alias in ORDER BY Clause
 Numeric Values → Sorted from smallest to
largest (1 to 999).
 Date Values → Earliest dates first (01-JAN-
92 before 01-JAN-95).
🔹 Result: Sorts employees by annual salary in
 Character Values → Alphabetical order (A descending order.
first, Z last).
 Null Values →
3. Sorting by Multiple Columns
o Last in ascending order (ASC).
o First in descending order (DESC).
 Sorting on Non-Selected Columns → You
can sort by a column that is not in the
SELECT list. 🔹 Result:
 Primary Sort: Ascending by department_id.
 Secondary Sort: Descending by salary
within each department.

💡 Sorting Limit → You can sort using all available


columns in a table.
💡 To reverse the order of a column, specify DESC
after its name.

Substitution Variables in SQL*Plus


In a finished application, the user triggers the
report, which runs without further prompting. The
range of data is predetermined by the fixed WHERE
Examples clause in the SQL*Plus script file.

1. Sorting in Descending Order (DESC)


ITE 014 | INFORMATION MANAGEMENT
Using SQL*Plus, you can create reports that prompt  Reporting on data relevant only to the user
users to supply their own values to restrict the requesting the report.
range of data using substitution variables. These
 Displaying personnel only within a given
variables can be embedded in a command file or a
department.
single SQL statement, temporarily storing values
that are substituted when the statement runs. Other Interactive Effects:
 Obtaining input values from a file rather
than from a person.
 Passing values from one SQL statement to
another.
 Note: SQL*Plus does not support validation
checks (except for data type) on user input.

Using the & Substitution Variable


Use a variable prefixed with an ampersand (&) to
prompt the user for a value:

Using the & Substitution Variable


 A variable prefixed with an ampersand (&)
prompts the user for a value.
 When SQL*Plus detects an ampersand in
the statement, it asks the user for input
before executing. Single-Ampersand Substitution Variable
You can predefine variables in SQL*Plus by using (continued)
the DEFINE command. DEFINE creates and assigns a When SQL*Plus detects that the SQL statement
value to a variable. contains an ampersand, you are prompted to enter
a value for the substitution variable that is named
Example: in the SQL statement.
After you enter a value and click the Continue
button, the results are displayed in the output area
of your SQL*Plus session.

 The user is prompted to enter a job title


before the query executes.
Examples of Restricted Data Ranges:
 Reporting figures only for the current
quarter or specified date range.
ITE 014 | INFORMATION MANAGEMENT

Using Substitution Variables for Column Names,


Expressions, and Text

Character and Date Values with Substitution


Variables  Substitution variables can replace column
names, expressions, or text in SQL
statements.
 If a substitution variable is used in a SELECT
statement, the user is prompted for input.
 If no value is entered, an error occurs when
executing the statement.
 Note: A substitution variable cannot be the
first word in a SQL statement.
Example:

 In a WHERE clause, date and character


values must be enclosed in single
quotation marks (').
 The user is prompted for a column name
 When using substitution variables for
and its value is used in both the SELECT and
character and date values, enclose them in
ORDER BY clauses.
single quotes within the SQL statement.
Example:
Using the && Substitution Variable

 The user must enter a date in the correct


format, e.g., '01-JAN-2020'.
ITE 014 | INFORMATION MANAGEMENT
Example:

S
 The value 100 is used for employee_num,
 Double ampersand (&&) is used when you and the user is not prompted.
want to reuse a variable without prompting
To remove the variable:
the user multiple times.
 The user is prompted once, and the entered
value is used throughout the statement.
Example: Using the VERIFY Command
 The VERIFY command toggles the display of
the substitution variable before and after
iSQL*Plus replaces it with a value.

 The user is prompted once for


column_name, and it is used multiple times.

Using the iSQL*Plus DEFINE and UNDEFINE


Commands

 Setting SET VERIFY ON forces SQL*Plus to


display:
o The original SQL statement (before
substitution).
o The modified SQL statement (after
 The DEFINE command is used to create and substitution).
assign a value to a variable.
 The UNDEFINE command is used to remove
a defined variable. Summary

 If a variable is created using DEFINE, the  Use the WHERE clause to restrict output
user is not prompted for input; instead, the rows:
pre-assigned value is used in the query. o Apply comparison conditions (=, >, <,
 The variable remains in the session until the >=, <=, !=)
user undefines it or exits SQL*Plus.
ITE 014 | INFORMATION MANAGEMENT
o Use BETWEEN, IN, LIKE, and IS NULL
conditions
o Apply logical operators (AND, OR,
NOT)
 Use the ORDER BY clause to sort output
rows.
 Use ampersand (&) substitution in
SQL*Plus to:
o Restrict and sort output at runtime.
o Allow user input in SQL statements
dynamically.

You might also like