Lab # 4: Sorting Data, Set Operators SWE-209
LAB # 4
SORTING DATA, SET OPERATORS
OBJECTIVE
Sort the rows that are retrieved by a query and use SET Operators
THEORY
SORTING ROWS WITH ORDER BY CLAUSE
The order of rows retrieved by a query result is undefined. You can use the ORDER
BY clause to display the rows in a specified order. The ORDER BY clause sorts query
results by one or more columns. The ORDER BY clause is placed last in the query.
You can specify and expression or an alias to sort. Sorting can be ascending (ASC) or
descending (DESC). By default, records are in ASC order. The sort limit is the number
of columns in the given table.
SYNTAX
SELECT expression
FROM table
WHERE condition(s)
ORDER BY {column, expression} [ASC|DESC]
Numeric values are shown with the lowest values first e.g. 1-10000.
Date values are shown with the earlier values first e.g. 1st Jan, 2009 before 1st
Feb, 2009.
Character values are shown in alphabetical order e.g. from A-Z.
The following query retrieves records from the employee table in an order of their
appointments.
select * from employee order by hiredate
Test different columns for ORDER BY clause by writing more queries yourself.
Sorting in Descending Order
To reverse the order of rows simply put DESC after the column name in the ORDER
BY clause.
26
Lab # 4: Sorting Data, Set Operators SWE-209
select * from employee order by hiredate desc
Results will be reversed by placing DESC
Sorting by Column Alias
You can use a column alias in the ORDER BY clause.
1. The following example illustrates this:
select ename,job,sal,sal*12 'Annual Income' from employee
order by 'Annual Income'
Sorting by Multiple Columns
You can sort by more than one column. Specify the columns, and separate the
columnname by commas. Columns names which are not present in the SELECT
statement can also be used in the ORDER BY clause.
1. Type this query:
select * from employee order by dno,sal desc
2. First ORDER BY clause orders the results thus obtained by department number.
3. Second ORDER BY clause then orders each ordered result on the basis
ofemployee salary.
4. Check the results yourself.
5. Test this query yourself.
select * from employee order by dno,sal
SET OPERATORS THEORY
Set operators operate on two result sets of queries, comparing complete rows between
the results. Depending on the result of the comparison and the set operator used, the
operator determines whether to return the row or not. T-SQL supports three set
operators: UNION, INTERSECT, and EXCEPT; it also supports one multiset operator:
UNION ALL.
The general form of code using a set operator is as follows.
<query 1>
<set operator>
<query 2>
[ORDER BY <order_by_list>]
28
Lab # 4: Sorting Data, Set Operators SWE-209
Working with set operators follows a number of guidelines
Because complete rows are matched between the result sets, the number of
columns in the queries has to be the same and the column types of
corresponding columns need to be compatible (implicitly convertible).
Set operators consider two NULLs as equal for the purpose of comparison. This
is quite unusual when compared to filtering clauses like WHERE and ON.
Because the operators are set operators and not cursor operators, the individual
queries are not allowed to have ORDER BY clauses.
You can optionally add an ORDER BY clause that determines presentation
ordering of the result of the set operator.
The column names of result columns are determined by the first query.
29
Lab # 4: Sorting Data, Set Operators SWE-209
UNION and UNION ALL
The UNION set operator unifies the results of the two input queries. As a set
operator, UNION has an implied DISTINCT property, meaning that it does not return
duplicate rows
As an example for using the UNION operator, the following query returns locations
that are employee locations or customer locations or both.
SELECT country, region, city FROM [Link]
UNION
SELECT country, region, city FROM [Link];
As an example, the following query unifies employee locations and customer
locations using the UNION ALL operator.
SELECT country, region, city FROM [Link]
UNION ALL
SELECT country, region, city FROM [Link];
INTERSECT
The INTERSECT operator returns only distinct rows that are common to both sets. In
other words, if a row appears at least once in the first set and at least once in the
second set, it will appear once in the result of the INTERSECT operator.
As an example, the following code uses the INTERSECT operator to return distinct
locations that are both employee and customer locations (locations where there’s at
least one employee and at least one customer).
SELECT country, region, city FROM [Link]
INTERSECT
SELECT country, region, city FROM [Link];
EXCEPT
The EXCEPT operator performs set difference. It returns distinct rows that appear in
the first query but not the second. In other words, if a row appears at least once in the
first query and zero times in the second, it’s returned once in the output.
As an example for using EXCEPT, the following query returns locations that are
employee locations but not customer locations.
SELECT country, region, city FROM [Link]
EXCEPT
SELECT country, region, city FROM [Link];
30
Lab # 4: Sorting Data, Set Operators SWE-209
With UNION and INTERSECT, the order of the input queries doesn’t matter.
However, with EXCEPT, there’s different meaning to
<query 1> EXCEPT <query 2> vs. <query 2> EXCEPT<query 1>
.
Finally, set operators have precedence: INTERSECT precedes UNION and EXCEPT,
and UNION and EXCEPT are considered equal. Consider the following set operators.
<query 1> UNION <query 2> INTERSECT <query 3>;
First, the intersection between query 2 and query 3 takes place, and then a union
between the result of the intersection and query 1. You can always force precedence
by using parentheses. So, if you want the union to take place first, you use the
following form.
(<query 1> UNION <query 2>) INTERSECT <query3>;
31
Lab # 4: Sorting Data, Set Operators SWE-209
LAB TASKS:
Employees(employee_id, first_name, last_name, email, phone_number, hire_date, job_id,
salary, commission_pct, manager_id, department_id)
1. From the following schema, write a SQL query to find those employees whose first
name contains the letters R, A, or N. Sort the result-set in ascending order by salary.
Return all fields.
2. From the following schema, write a SQL query to find those employees who earn
above 21000 or the fifth character in their phone number is 8.. Sort the result-set in
ascending order by last name. Return full name (first name and last name), hire date,
commission percentage, email, and telephone separated by '-', and salary.
Orders(ord_no, purch_amt, ord_date, customer_id, salesman_id)
Salesman (salesman_id, name, city, commission)
Customer (customer_id, cust_name, city, grade, salesman_id)
3. From the following table, write a SQL query to find those salespersons generated the
largest and smallest orders on each date. Return salesperson ID, name, order no.,
highest on/ lowest on, order date.
4. From the following tables, write a SQL query to find those salespersons who have
same cities where customer lives as well as do not have customers in their cities and
indicate it by ‘NO MATCH’. Sort the result set on 2nd column (i.e. name) in
descending order. Return salesperson ID, name, customer name, commission.
32