Lab 07
Advanced Logical Operators and Sorting (ORDER BY, IN, BETWEEN)
Section 1: Concept Foundation
What are these operators?
In Experiment 6, we covered basic filtering with WHERE, AND, OR, and NOT. Experiment 7 extends that toolbox with three powerful operators that simplify and enhance conditional logic:
- ORDER BY: Sorts the result set.
- IN / NOT IN: Tests a value against a list of values (alternative to multiple
ORconditions). - BETWEEN / NOT BETWEEN: Tests a value within an inclusive range (numeric, text, or date).
Why were these features created?
- ORDER BY exists because raw query results are often unordered; sorting is essential for readability, reporting, and identifying top/bottom records.
- IN was created to avoid repetitive
ORclauses, making queries cleaner and more efficient. - BETWEEN simplifies range checks, especially for numeric and date ranges, ensuring inclusivity without manual boundary conditions.
Real-world Analogy
- ORDER BY: Like arranging a stack of papers alphabetically or by date.
- IN: Like checking if a student is in a specific list of names.
- BETWEEN: Like selecting employees whose hire date falls within a fiscal year.
Where are they used?
- ORDER BY: In every report, dashboard, and list view (e.g., customers sorted by name, products by price).
- IN: Filtering by a set of known values (e.g., statuses: 'Active', 'Pending', 'Closed').
- BETWEEN: Date ranges (e.g., sales between Jan 1 and Dec 31), salary bands, or alphabetical ranges.
Section 2: Visual Understanding
ORDER BY Execution Flow
IN Operator Logic
BETWEEN Operator Logic
Section 3: Syntax Breakdown and Oracle-Specific Rules
1. ORDER BY Clause
Purpose: Sorts the result set based on one or more columns.
General Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;Explanation:
ASC: Ascending order (lowest to highest, A to Z). This is the default.DESC: Descending order (highest to lowest, Z to A).- You can sort by multiple columns: first by
column1, then bycolumn2within equalcolumn1values.
Example:
SELECT * FROM Persons ORDER BY LastName ASC;2. IN Operator
Purpose: Checks if a value matches any value in a specified list.
General Syntax:
SELECT column_list
FROM table_name
WHERE column_name IN (value1, value2, value3, ...);Explanation:
- The list can be hardcoded values, a result of a subquery, or a combination.
- Equivalent to multiple
ORconditions:column = value1 OR column = value2 OR ...
Example:
SELECT * FROM Customers WHERE City IN ('Plano', 'Albany');3. NOT IN Operator
Purpose: Excludes rows where the column matches any value in the list.
Syntax:
WHERE column_name NOT IN (value1, value2, ...);Example:
SELECT * FROM Customers WHERE City NOT IN ('Sandnes');4. BETWEEN Operator
Purpose: Selects values within a range, inclusive of both endpoints.
General Syntax:
WHERE column_name BETWEEN value1 AND value2;Explanation:
- Works with numbers, text (alphabetical order based on collation), and dates.
- Inclusive:
column >= value1 AND column <= value2.
Example (Numbers):
SELECT * FROM Products WHERE Price BETWEEN 200 AND 300;Example (Text):
SELECT * FROM Persons WHERE LastName BETWEEN 'Hansen' AND 'Pettersen';Example (Dates):
SELECT * FROM Orders WHERE OrderDate BETWEEN '01-JAN-2024' AND '31-DEC-2024';5. NOT BETWEEN Operator
Purpose: Selects values outside the range.
Syntax:
WHERE column_name NOT BETWEEN value1 AND value2;Example:
SELECT * FROM Products WHERE Price NOT BETWEEN 200 AND 300;Section 4: Query Thinking Process (Professional Approach)
Requirement: "List all customers who live in either 'FL', 'TX', 'CA', or 'HI'."
Step 1: Identify table → Customer_T
Step 2: Identify columns → CustomerName, CustomerCity, CustomerState
Step 3: Identify filter condition → CustomerState must be one of those four values.
Step 4: Choose operator → IN (cleaner than multiple ORs).
Step 5: Write query:
SELECT CustomerName, CustomerCity, CustomerState
FROM Customer_T
WHERE CustomerState IN ('FL', 'TX', 'CA', 'HI');Step 6: Validate → Execute and check that results include only those states.
Section 5: Multiple Examples
Example 1: Easy (ORDER BY)
Requirement: List all products sorted by price from lowest to highest. Query:
SELECT * FROM Product_T ORDER BY ProductStandardPrice ASC;Example 2: Medium (IN with multiple values)
Requirement: Find all customers whose city is either 'Karachi', 'Lahore', or 'Islamabad'. Query:
SELECT * FROM Customers WHERE City IN ('Karachi', 'Lahore', 'Islamabad');Example 3: Exam-style (BETWEEN with dates)
Requirement: Find orders placed between 1-Oct-2010 and 24-Oct-2010 inclusive. Query:
SELECT OrderID, OrderDate FROM Order_T
WHERE OrderDate BETWEEN '01-OCT-2010' AND '24-OCT-2010';Example 4: Real-world (ORDER BY multiple columns)
Requirement: Show all products sorted by ProductFinish (alphabetical), and within the same finish, by price descending.
Query:
SELECT ProductDescription, ProductFinish, ProductStandardPrice
FROM Product_T
ORDER BY ProductFinish ASC, ProductStandardPrice DESC;Example 5: Tricky (NOT IN with NULL handling)
Requirement: Find customers who do not live in the states 'NY', 'CA', or 'TX'. (Note: If the column contains NULLs, NOT IN may exclude rows where the column is NULL because NULL comparisons are unknown.) Query:
SELECT * FROM Customers
WHERE CustomerState NOT IN ('NY', 'CA', 'TX');Explanation: If CustomerState is NULL, it will not be included because NULL NOT IN (list) evaluates to false. If you want to include NULLs, you need to add OR CustomerState IS NULL.
Section 6: Pattern Recognition
| Requirement Keyword | Think of | SQL Feature |
|---|---|---|
| "Sort by", "Order by" | ORDER BY | `ORDER BY column [ASC |
| "Highest", "lowest" | ORDER BY DESC / ASC | ORDER BY column DESC |
| "In a list", "either of these" | IN | WHERE column IN (val1, val2, ...) |
| "Not in the list" | NOT IN | WHERE column NOT IN (val1, ...) |
| "Between X and Y" | BETWEEN | WHERE column BETWEEN X AND Y |
| "Outside the range" | NOT BETWEEN | WHERE column NOT BETWEEN X AND Y |
| "Alphabetically between" | BETWEEN (text) | WHERE text BETWEEN 'A' AND 'M' |
Section 7: Common Mistakes
| Mistake | Wrong Query | Why Wrong | Correct Query |
|---|---|---|---|
| Forgetting ASC/DESC assumes ASC | ORDER BY column works as expected, but if you intend descending, omit DESC. | Not wrong, but incomplete. | ORDER BY column DESC |
Using IN with NULL values | WHERE column IN (1, 2, NULL) | The condition column = NULL is always false, so NULL is ignored. | Use OR column IS NULL if needed. |
Using BETWEEN for non-inclusive range | WHERE Price BETWEEN 200 AND 300 includes 200 and 300. If you want exclusive, use Price > 200 AND Price < 300. | Misunderstanding inclusivity. | Use > and < for exclusive. |
NOT IN with NULLs in subquery | WHERE column NOT IN (SELECT ...) if the subquery returns NULL, the whole condition becomes false because column NOT IN (NULL, ...) is unknown. | Avoid NOT IN with subqueries that may return NULL. | Use NOT EXISTS or filter out NULLs with WHERE column NOT IN (SELECT ... WHERE column IS NOT NULL). |
Using BETWEEN with text and case sensitivity | In Oracle, BETWEEN is case-sensitive. 'Hansen' and 'hansen' are different. | Use UPPER() or LOWER() for case-insensitive matching. | WHERE UPPER(LastName) BETWEEN 'HANSEN' AND 'PETTERSEN' |
Section 8: Exam Perspective
Frequently Asked Questions
- Write a query to sort employees by salary in descending order.
- Use
INto find products whose category is 'Electronics', 'Furniture', or 'Office Supplies'. - Write a query to select orders placed between 1-Jan-2023 and 31-Mar-2023.
- What is the difference between
BETWEENand using>=and<=? - Explain the behavior of
NOT INwhen the list contains a NULL.
Viva Questions
- Does
BETWEENinclude the endpoints? (Yes, inclusive.) - Can you use
ORDER BYwith a column alias? (Yes, you can use the alias inORDER BY.) - What happens if you sort by a column that contains NULLs? (NULLs are considered larger than any non-NULL value in ascending order in Oracle; they appear at the end in ASC, at the beginning in DESC.)
- How can you check if a value is not in a list but also include NULLs? (Use
WHERE column NOT IN (list) OR column IS NULL.) - Why is
INpreferred over multipleORs? (It is cleaner, easier to read, and may be optimized better by the database.)
MCQ
-
Which operator is used to sort the result set? a) SORT b) ORDER BY c) GROUP BY d) HAVING Answer: b
-
The
BETWEENoperator is __________ of the endpoints. a) Exclusive b) Inclusive c) Neither d) Depends on database Answer: b -
Which of the following is equivalent to
City IN ('Paris', 'London')? a)City = 'Paris' AND City = 'London'b)City = 'Paris' OR City = 'London'c)City LIKE 'Paris' OR 'London'd)City BETWEEN 'Paris' AND 'London'Answer: b
Section 9: Industry Perspective
How professionals use these operators
- ORDER BY is used extensively in pagination (e.g., with
OFFSETandFETCHin Oracle 12c+) to implement "next page" logic. - IN is common in dynamic filtering (e.g., from a user-selected checklist). It is often combined with subqueries to filter based on another table.
- BETWEEN is critical for date range queries in reporting and analytics. Performance-wise,
BETWEENcan leverage indexes if the column is indexed.
Best Practices
- Always explicitly state
ASCorDESCfor clarity. - When using
INwith a long list, consider using a temporary table or a join for better performance. - Be cautious with
NOT INif the subquery may contain NULL; useNOT EXISTSinstead. - For date ranges, use
TO_DATEwith explicit format to avoid ambiguity (e.g.,BETWEEN TO_DATE('01-JAN-2024','DD-MON-YYYY') AND ...). - Test
BETWEENwith text if the collation is case-sensitive; useUPPER/LOWERto standardize.
Section 10: Query Construction Framework
Use this framework for any query involving sorting or multi-value filtering:
- Understand requirement: What columns, what order, what filters?
- Identify table(s).
- Choose columns for
SELECT. - Apply
WHEREfilters using appropriate operators (IN,BETWEEN, etc.). - Determine sorting (
ORDER BY). - Write query.
- Validate by running on a sample.
Section 11: Practice Section
Beginner Exercises
- Sort the
Product_Ttable byProductStandardPricein ascending order. - Find all products whose
ProductFinishis either 'Cherry' or 'Walnut' usingIN. - List products with
ProductStandardPricebetween 250 and 500. - Display distinct
ProductLineIDvalues fromProduct_T. - Sort products by
ProductDescriptiondescending.
Intermediate Exercises
- Find all products whose
ProductDescriptioncontains the word 'Desk' and whose price is between 200 and 400. - List products where
ProductFinishis not 'Natural Ash' and not 'White Ash' usingNOT IN. - Show products sorted by
ProductFinishalphabetically, then by price descending. - Find products with price outside the range 300 to 700 using
NOT BETWEEN. - Write a query to find all customers who live in states ('FL', 'TX') and whose postal code is not '75094' (use
NOT IN).
Advanced Exercises
- Write a query to display the top 3 most expensive products (use
ORDER BY ... DESCandFETCH FIRST 3 ROWS ONLYin Oracle 12c+). - Using
INwith a subquery, find all products that have been ordered (i.e.,ProductIDexists inOrderLine_T). - Write a query to list all products whose price is between the average price minus 100 and average price plus 100 (use
BETWEENwith a subquery). - Sort the result of the previous query by
ProductStandardPricedescending. - Find all products whose
ProductFinishis alphabetically between 'Cherry' and 'Walnut' (inclusive).
Section 12: Challenge Section – Real-world Scenarios
Scenario 1: E-commerce Filtering
- A user wants to see products with price between 500, sorted by price low to high, and only in categories 'Furniture' and 'Decor'. Write the query.
Scenario 2: HR Reporting
- The HR department wants a list of employees whose hire date is between 1-Jan-2020 and 31-Dec-2023, sorted by last name. Write the query.
Scenario 3: Inventory Analysis
- You need to find all warehouses that have stock quantities outside the normal range (less than 10 or greater than 1000) for any product. Use
NOT BETWEENto identify those quantities.
Section 13: Interview Preparation
Conceptual Questions
-
Explain the difference between
INandBETWEEN.INchecks for equality against a list;BETWEENchecks for a range (inclusive).
-
Can you use
ORDER BYwith a column that is not in theSELECTlist?- Yes, you can sort by any column in the table, even if not displayed.
-
What happens if you use
ORDER BYwith a column that has NULL values?- In Oracle, NULLs are considered larger than any non-NULL value. Thus, in
ASC, NULLs appear at the end; inDESC, they appear at the beginning. UseNULLS FIRSTorNULLS LASTto control.
- In Oracle, NULLs are considered larger than any non-NULL value. Thus, in
-
Is
BETWEENinclusive or exclusive?- Inclusive.
-
Why might
NOT INreturn an unexpected empty result set?- If the subquery or list contains a NULL, the entire condition evaluates to false because
NULLcomparisons are unknown. UseNOT EXISTSinstead.
- If the subquery or list contains a NULL, the entire condition evaluates to false because
Practical SQL Interview Questions
Q1: Write a query to find all products with a price between 100 and 200, sorted by price descending. Answer:
SELECT * FROM Product_T
WHERE ProductStandardPrice BETWEEN 100 AND 200
ORDER BY ProductStandardPrice DESC;Q2: How do you list all customers who do not live in 'NY' or 'CA'? Answer:
SELECT * FROM Customers
WHERE State NOT IN ('NY', 'CA');Q3: Write a query to show the top 5 most expensive products. Answer:
SELECT * FROM Product_T
ORDER BY ProductStandardPrice DESC
FETCH FIRST 5 ROWS ONLY; -- Oracle 12c+Q4: Use IN to find employees whose department is in (10, 20, 30).
Answer:
SELECT * FROM Employees WHERE DepartmentID IN (10, 20, 30);Q5: Find orders placed in the first quarter of 2023 (Jan-Mar). Answer:
SELECT * FROM Orders
WHERE OrderDate BETWEEN '01-JAN-2023' AND '31-MAR-2023';Section 14: Topic Summary – Cheat Sheet
Key Operators and Clauses
| Operator / Clause | Syntax Example | Description |
|---|---|---|
| ORDER BY | ORDER BY col ASC / DESC | Sorts result set |
| IN | WHERE col IN (val1, val2) | Matches any value in list |
| NOT IN | WHERE col NOT IN (val1, val2) | Excludes values in list |
| BETWEEN | WHERE col BETWEEN low AND high | Inclusive range |
| NOT BETWEEN | WHERE col NOT BETWEEN low AND high | Exclusive of range |
Important Points
ORDER BYdefault isASC.BETWEENincludes both endpoints.INis a shorthand for multipleORs.- Be cautious with
NOT INand NULLs. - All these operators can be combined with
AND,OR,NOTto form complex conditions.
Final Professional Advice
Mastering these operators is fundamental to writing efficient and readable SQL. They are used daily in data retrieval tasks. Always test your queries with sample data and be aware of the nuances of NULL handling and inclusivity. Practice with the Product_T table and the lab tasks below to solidify your understanding.
Lab Tasks from the PDF (with solutions)
Lab Task 1: Product_T Table Queries
We have the Product_T table as shown. Run these queries and examine outputs:
-
Display all customers for whom we do not know their postal code.
- (Assuming
Customer_ThasPostalCodecolumn)
SELECT * FROM Customer_T WHERE PostalCode IS NULL; - (Assuming
-
Which orders have been placed since 10/24/2010?
SELECT OrderID, OrderDate FROM Order_T WHERE OrderDate > '24-OCT-2010'; -
What furniture does Pine Valley carry that isn't made of cherry?
SELECT ProductDescription, ProductFinish FROM Product_T WHERE ProductFinish != 'Cherry'; -
Which products have a standard price between 300?
SELECT ProductDescription, ProductStandardPrice FROM Product_T WHERE ProductStandardPrice BETWEEN 200 AND 300;Or using
>=and<=:WHERE ProductStandardPrice >= 200 AND ProductStandardPrice <= 300; -
What order numbers are included in the OrderLine table?
SELECT OrderID FROM OrderLine_T; -
What are the distinct order numbers included in the OrderLine table?
SELECT DISTINCT OrderID FROM OrderLine_T; -
What are the unique combinations of order number and order quantity?
SELECT DISTINCT OrderID, OrderedQuantity FROM OrderLine_T; -
List all customers who live in warmer states (FL, TX, CA, HI).
SELECT CustomerName, CustomerCity, CustomerState FROM Customer_T WHERE CustomerState IN ('FL', 'TX', 'CA', 'HI');
Lab Task 2: Practice Queries on Product_T
-
Sort the table Product_T in descending order according to ProductDescription.
SELECT * FROM Product_T ORDER BY ProductDescription DESC; -
Select records where productstandardprice is not equal to 275 and ProductDescription is not equal to 'Dining Table'.
SELECT * FROM Product_T WHERE ProductStandardPrice != 275 AND ProductDescription != 'Dining Table'; -
Display all distinct ProductDescription from Product_T.
SELECT DISTINCT ProductDescription FROM Product_T; -
Which products have a standard price not between 200 and 300?
SELECT * FROM Product_T WHERE ProductStandardPrice NOT BETWEEN 200 AND 300; -
Which products have a ProductFinish between Cherry and Walnut? (Alphabetical range)
SELECT * FROM Product_T WHERE ProductFinish BETWEEN 'Cherry' AND 'Walnut';This will include 'Cherry', 'Natural Ash'? (Note: 'Natural Ash' alphabetically between 'Cherry' and 'Walnut'? Actually 'Natural' > 'Cherry' and < 'Walnut'? Let's check: 'Cherry' < 'Natural Ash' < 'Walnut', so yes it includes it. Be aware of case sensitivity.)
-
Select products that have ProductDescription Writer Desk or Dining Table or Coffee Table using IN operator.
SELECT * FROM Product_T WHERE ProductDescription IN ('Writer Desk', 'Dining Table', 'Coffee Table');
Final Note
Now you have a comprehensive understanding of ORDER BY, IN, BETWEEN, and their variations. Practice these queries on the Product_T table and other sample data. These operators are the bread and butter of SQL querying, and with this knowledge, you can answer any exam or interview question related to filtering and sorting. Good luck!