0% found this document useful (0 votes)
8 views36 pages

Unit 3 - Learn To Restrict and Sort Data

The document outlines SQL techniques for restricting and sorting data, focusing on the use of the WHERE clause, comparison operators, and logical conditions. It explains how to sort results with the ORDER BY clause and limit the number of returned rows using SQL row limiting clauses. Additionally, it covers the use of substitution variables and commands like DEFINE and VERIFY to enhance query flexibility.

Uploaded by

alin.dobre
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)
8 views36 pages

Unit 3 - Learn To Restrict and Sort Data

The document outlines SQL techniques for restricting and sorting data, focusing on the use of the WHERE clause, comparison operators, and logical conditions. It explains how to sort results with the ORDER BY clause and limit the number of returned rows using SQL row limiting clauses. Additionally, it covers the use of substitution variables and commands like DEFINE and VERIFY to enhance query flexibility.

Uploaded by

alin.dobre
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/ 36

Course code: BCT048

3 Learn to Restrict and Sort Data


Agenda
• Limiting rows with:
• The WHERE clause
• The comparison operators using =, <=,
BETWEEN, IN, LIKE, and NULL conditions
• Logical conditions using AND, OR, and NOT
operators
• Rules of precedence for operators in an expression
• Sorting rows using the ORDER BY clause
• SQL Row limiting clause in a query
• Substitution variables
• DEFINE and VERIFY commands

Restrict and Sort Data


Agenda
• Limiting rows with:
• The WHERE clause
• The comparison operators using =, <=,
BETWEEN, IN, LIKE, and NULL conditions
• Logical conditions using AND, OR, and NOT
operators
• Rules of precedence for operators in an expression
• Sorting rows using the ORDER BY clause
• SQL Row limiting clause in a query
• Substitution variables
• DEFINE and VERIFY commands

Restrict and Sort Data


Limiting Rows Using a Selection
EMPLOYEES

All EMPLOYEES in department 90

• This method of restriction is the basis of the WHERE clause in


SQL

Restrict and Sort Data


Limiting Rows Using a Selection
• Restrict the rows that are returned by using the WHERE clause:

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


FROM table
[WHERE logical expression(s)];

• A WHERE clause contains a condition that must be met and it


directly follows the FROM clause. If the condition is true, the row
meeting the condition is returned
• The WHERE clause can compare values in columns, literal,
arithmetic expressions, or functions. It consists of three elements:
• Column name
• Comparison condition
• Column name, constant, or list of values

Restrict and Sort Data


Using the WHERE Clause

SELECT employee_id, last_name, job_id, department_id


FROM employees
WHERE department_id = 90;

In the example, the SELECT statement retrieves the employee ID, last
name, job ID, and department number of all employees who are in
department 90.

• You cannot use column alias in the WHERE clause

Restrict and Sort Data


Character Strings and Dates

• 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-YY.

SELECT last_name, job_id, department_id


FROM employees
WHERE last_name = 'King';

SELECT last_name
FROM employees
WHERE hire_date = '17-OCT-03';

Restrict and Sort Data


Comparison Operators

• OPERATORS:
• = Equal to
• > Greater than
• >= Greater than or equal to
• < Less than
• <= Less than or equal to
• <>, !=, ^= Not equal to
• BETWEEN … AND … Between two values (inclusive)
• IN(set) Match any of a list of values
• LIKE Match a character pattern
• IS NULL Is a null value
• NOT Negation of a condition

Restrict and Sort Data


Using Comparison Operators
SELECT last_name, salary
FROM employees
WHERE salary <= 3000;

Use the BETWEEN operator to display rows based on a range

SELECT last_name, salary


FROM employees
WHERE salary BETWEEN 2500 AND 3500;

Use the IN operator to test for values in a list


SELECT employee_id, last_name, salary, manager_id
FROM employees
WHERE manager_id IN (100, 101, 201);

Restrict and Sort Data


Pattern Matching Using the LIKE Operator
• Use the LIKE operator to perform wildcard searches of valid search
string values
• Search conditions can contain either literal characters or numbers
• % denotes zero or more characters
• _ denotes one character
SELECT first_name
FROM employees
WHERE first_name LIKE 'S%';

SELECT last_name, hire_date


FROM employees
WHERE hire_date LIKE '%05';

Restrict and Sort Data


Combining Wildcard Characters
• You can combine the two wildcard characters (%, _) with literal
characters for pattern matching
SELECT last_name
FROM employees
WHERE last_name LIKE '_o%';

• You can use the ESCAPE identifier to search for the actual % and _
symbols

SELECT employee_id, last_name, job_id


FROM employees WHERE job_id LIKE '%SA\_%' ESCAPE '\';

• The ESCAPE identifies the backslash (\) as the escape character. This
causes the Oracle server to interpret the underscore literally

Restrict and Sort Data


Using the NULL Conditions
• Test for nulls with the IS NULL operator

SELECT last_name, manager_id


FROM employees
WHERE manager_id IS NULL;

• The NULL conditions include the IS NULL condition and the IS NOT
NULL condition
Example: Display the last name, job ID, and commission for all employees
who don’t have a commission

SELECT last_name, job_id, commission_pct


FROM employees
WHERE commission_pct IS NULL;

Restrict and Sort Data


Using the Logical Operators
• The Logical Operators are:

• AND – Returns TRUE if both component conditions are true


• OR – Returns TRUE if either component condition is true
• NOT – Returns TRUE if NOT the condition is false

• You can use several conditions in a single WHERE clause using the
AND and OR operators

SELECT employee_id, last_name, job_id, salary


FROM employees
WHERE salary >= 10000 AND job_id LIKE '%MAN%';

• AND requires both the component conditions to be true

Restrict and Sort Data


Using the Logical Operators
SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary >= 10000 OR job_id LIKE '%MAN%';

• OR requires either component condition to be true

SELECT last_name, job_id


FROM employees
WHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP');

• This example displays the last name and job ID of all employees whose
job ID is not IT_PROG, ST_CLERK, or SA_REP
• The NOT operator can also be used with other SQL operators, such as
BETWEEN, LIKE, and NULL
Restrict and Sort Data
Agenda
• Limiting rows with:
• The WHERE clause
• The comparison operators using =, <=,
BETWEEN, IN, LIKE, and NULL conditions
• Logical conditions using AND, OR, and NOT
operators
• Rules of precedence for operators in an expression
• Sorting rows using the ORDER BY clause
• SQL Row limiting clause in a query
• Substitution variables
• DEFINE and VERIFY commands

Restrict and Sort Data


Rules of Precedence
The rules of precedence determine the order in which expressions are
evaluated and calculated

The default order of precedence:


• Arithmetic operators 1
• Concatenation operator 2
• Comparison conditions 3
• IS [NOT] NULL, LIKE, [NOT] IN 4
• [NOT] BETWEEN 5
• Not equal to 6
• NOT logical operator 7
• AND logical operator 8
• OR logical operator 9

Restrict and Sort Data


Rules of Precedence

SELECT last_name, job_id, salary


FROM employees
WHERE job_id = 'SA_REP‘ OR job_id = 'AD_PRES'
AND salary > 15000;

SELECT last_name, job_id, salary


FROM employees
WHERE (job_id = 'SA_REP‘ OR job_id = 'AD_PRES‘)
AND salary > 15000;

• You can override the default order by using parentheses around the
expressions that you want to calculate first

Restrict and Sort Data


Agenda
• Limiting rows with:
• The WHERE clause
• The comparison operators using =, <=,
BETWEEN, IN, LIKE, and NULL conditions
• Logical conditions using AND, OR, and NOT
operators
• Rules of precedence for operators in an expression
• Sorting rows using the ORDER BY clause
• SQL Row limiting clause in a query
• Substitution variables
• DEFINE and VERIFY commands

Restrict and Sort Data


Using the ORDER BY Clause
• Sort the retrieved rows with the ORDER BY clause
• ASC: Ascending order, default
• DESC: Descending order

• The ORDER BY clause comes last in the SELECT statement


SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date ;

Syntax
SELECT expr
FROM table
[WHERE condition(s)]
[ORDER BY {column, expr, numeric_position} [ASC|DESC]];

Restrict and Sort Data


Using the ORDER BY Clause
• Use the keywords NULLS FIRST or NULLS LAST to specify whether
returned rows containing null values should appear first or last in the
ordering sequence
• 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 ;
• The default sort order is ascending
• You can also sort by a column that is not in the SELECT list

Restrict and Sort Data


Using the ORDER BY Clause
• Sorting by using the column’s numeric position

SELECT last_name, job_id, department_id, hire_date


FROM employees
ORDER BY 3;

• Sorting by multiple columns:

SELECT last_name, department_id, salary


FROM employees
ORDER BY department_id, salary DESC;

Restrict and Sort Data


Agenda
• Limiting rows with:
• The WHERE clause
• The comparison operators using =, <=,
BETWEEN, IN, LIKE, and NULL conditions
• Logical conditions using AND, OR, and NOT
operators
• Rules of precedence for operators in an expression
• Sorting rows using the ORDER BY clause
• SQL Row limiting clause in a query
• Substitution variables
• DEFINE and VERIFY commands

Restrict and Sort Data


SQL Row Limiting
• You can specify the row_limiting_clause in the SQL SELECT statement
by placing it after the ORDER BY clause. ORDER BY clause is not
required

Syntax:
...
[ order_by_clause ]
[OFFSET offset { ROW | ROWS }]
[FETCH { FIRST | NEXT } [{ row_count | percent PERCENT
}] { ROW | ROWS }
{ ONLY | WITH TIES }]

Restrict and Sort Data


SQL Row Limiting
• The row_limiting_clause allows you to limit the rows that are returned
by the query
• Queries that order data and then limit row output are widely used and
are often referred to as Top-N queries
• You can specify the number of rows or percentage of rows to return
with the FETCH_FIRST keywords
• You can use the OFFSET keyword to specify that the returned rows
begin with a row after the first row of the full result set
• The WITH TIES keyword includes additional rows with the same
ordering keys as the last row of the row-limited result set (you must
specify ORDER BY in the query)

Restrict and Sort Data


SQL Row Limiting
• OFFSET: Use this clause to specify the number of rows to skip before
row limiting begins. The value for offset must be a number. If you
specify NULL or a number greater than or equal to the number of rows
that are returned by the query, 0 rows are returned
• ROW | ROWS: Use these keywords interchangeably
• FETCH: Use this clause to specify the number of rows or percentage of
rows to return
• FIRST | NEXT: Use these keywords interchangeably
• row_count | percent PERCENT: Use row_count to specify the number
of rows to return. Use percent PERCENT to specify the percentage of
the total number of selected rows to return. Percent must be a number
• ONLY | WITH TIES: Specify ONLY to return exactly the specified
number of rows or percentage of rows. Specify WITH TIES to return all
rows that have the same sort keys as the last row of the row-limited
result set (WITH TIES requires an ORDER BY clause)

Restrict and Sort Data


SQL Row Limiting Examples

SELECT employee_id, first_name


FROM employees
ORDER BY employee_id
FETCH FIRST 5 ROWS ONLY;

SELECT employee_id, first_name


FROM employees
ORDER BY employee_id
OFFSET 5 ROWS FETCH
NEXT 5 ROWS ONLY;

Restrict and Sort Data


Agenda
• Limiting rows with:
• The WHERE clause
• The comparison operators using =, <=,
BETWEEN, IN, LIKE, and NULL conditions
• Logical conditions using AND, OR, and NOT
operators
• Rules of precedence for operators in an expression
• Sorting rows using the ORDER BY clause
• SQL Row limiting clause in a query
• Substitution variables
• DEFINE and VERIFY commands

Restrict and Sort Data


Substitution Variables
• By using a substitution variable in place of the exact values you can run
the same query for different values
• A variable can be thought of as a container in which values are
temporarily stored. When the statement is run, the stored value is
substituted
• 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

Restrict and Sort Data


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;

• With the single ampersand, the user is prompted every time the
command is executed if the variable does not exist

Restrict and Sort Data


Single-Ampersand Substitution Variable
• Use single quotation marks for date and character values

SELECT last_name, department_id, salary*12


FROM employees
WHERE job_id = '&job_title';

• Column Names, Expressions, and Text

SELECT employee_id, last_name, job_id,&column_name


FROM employees
WHERE &condition
ORDER BY &order_column ;

• A substitution variable can be used anywhere in the SELECT


statement, except as the first word entered at the command prompt
Restrict and Sort Data
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;

• SQL Developer stores the value that is supplied by using the DEFINE
command. After a user variable is in place, you need to use the
UNDEFINE command to delete it: UNDEFINE column_name;

ACCEPT col_name PROMPT 'Please specify column name:‘


SELECT &&col_name FROM employees
ORDER BY &col_name;
UNDEFINE col_name;

Restrict and Sort Data


Agenda
• Limiting rows with:
• The WHERE clause
• The comparison operators using =, <=,
BETWEEN, IN, LIKE, and NULL conditions
• Logical conditions using AND, OR, and NOT
operators
• Rules of precedence for operators in an expression
• Sorting rows using the ORDER BY clause
• SQL Row limiting clause in a query
• Substitution variables
• DEFINE and VERIFY commands

Restrict and Sort Data


The DEFINE Command
• Use the DEFINE command to create and assign a value to a variable
• Use the UNDEFINE 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;

Restrict and Sort Data


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;

Restrict and Sort Data


Quiz

• Which of the following are not valid operators for the WHERE clause?.

a. >=
b. IS NULL
c. !=
d. IS LIKE
e. IN BETWEEN
f. <>

Restrict and Sort Data


Practice 3
This practice covers the following topics:

• Selecting data and changing the order of the rows that are displayed

• Restricting rows by using the WHERE clause

• Sorting rows by using the ORDER BY clause

• Using substitution variables to add flexibility to your SQL SELECT


statements

Restrict and Sort Data

You might also like