Filtering and Sorting: practice questions
400 questions in four levels, all on RetailMart, the practice database of this course. Write every query yourself, get it wrong, read the error, fix it. That is how it sticks.
Answers are coming soon. Post your query in the WhatsApp Community or Discord and we will check it together.
Easy 100 questions Medium 100 questions Hard 100 questions Crazy 100 questions
Core syntax, applied directly
CONCEPTUAL QUESTIONS Q1 Your junior asks "what does the WHERE clause do?" - explain in one line. Q2 In an interview, you're asked: AND vs OR - which has higher precedence and why does it matter? Q3 A teammate is debating whether BETWEEN 1 AND 10 includes the boundary numbers. What do you tell them? Q4 When would you choose IN over chaining many OR conditions? Q5 A student writes WHERE name LIKE 'samsung%' and gets zero rows. Why - and what should they have used? Q6 A query WHERE phone = NULL returns nothing even though some phones look empty. Explain. Q7 Why do experienced engineers always add ORDER BY even when data "looks sorted"? Q8 In ORDER BY, what is the default sort direction if you don't specify ASC or DESC? Q9 Explain what LIMIT 10 OFFSET 20 returns - and which page (10-per-page) the user is viewing. Q10 Write out the standard clause order: SELECT, FROM, WHERE, ORDER BY, LIMIT - and then the EXECUTION order. SELECT + BASIC WHERE Q11 The Customer Service team is exporting the full customer master list. Pull every column from customers.customers. Q12 Marketing wants a contact list - show first_name and email from customers.customers. Q13 The catalog team needs product_id, product_name, and price from products.products for a price-list PDF. Q14 The Finance Director wants order_id, cust_id, and net_total from sales.orders for a revenue audit. Q15 HR is building an employee directory. Show employee_id, first_name, and role from stores.employees. Q16 The premium catalog team wants every product priced ABOVE 500. Q17 The 'value zone' team wants products priced BELOW 100. Q18 A pricing analyst is testing - find any product whose price equals exactly 999.99. Q19 Marketing is launching a satisfaction survey for completed purchases. Pull all delivered orders from sales.orders. Q20 The Ops team wants to ignore cancellations - show all orders that are NOT 'Cancelled'. Q21 Loyalty wants the 'Gold tier' contact list. Filter customers.customers where tier = 'Gold'. Q22 Re-engagement campaign: customers whose tier is NOT 'Bronze' (everyone above entry level). Q23 The CHRO wants senior employees - salary > 50000. Q24 HR is reviewing entry-level pay - show employees whose salary is below 30000. Q25 Store Operations wants the Mumbai locations - stores.stores where city = 'Mumbai'. Q26 The expansion team wants every store outside Delhi - city != 'Delhi'. Q27 Support escalation list: pull all tickets with priority = 'High'. Q28 The support manager wants the open queue - tickets where status = 'Open'. Q29 Loyalty wants 'big point holders' - members with points_balance above 1000. Q30 CX wants all 5-star reviews for the marketing landing page - reviews with rating = 5. Q31 The Quality team wants reviews flagged as unhappy - rating < 3. Q32 HR is doing an attendance audit. Pull hr.attendance records for the date '2025-01-15'. Q33 The CMO wants every high-budget campaign - budget above 100000. Q34 The CFO wants large expenses for the audit - finance.expenses where amount > 50000. Q35 DevOps is chasing production errors - application_logs where level = 'ERROR'. Q36 The API team wants 500-error rows - audit.api_requests where status_code = 500. Q37 The Web Analytics team wants only the mobile page views - device_type = 'Mobile'. Q38 Production wants the 'Completed' work-orders list - manufacture.work_orders where status = 'Completed'. Q39 The call-center supervisor wants 'long calls' - call_duration_seconds above 300 (5+ minutes). Q40 Payroll is reviewing high-paid net salaries - pay_slips where net_salary > 10000. BETWEEN / IN / LIKE / IS NULL Q41 The pricing team wants the mid-tier range - products priced BETWEEN 200 AND 1000. Q42 The 'edge case' pricing review - products NOT priced between 100 and 500 (either cheaper or more expensive). Q43 The H1 review meeting needs orders placed between January and June 2025. Q44 The CHRO wants the salary 'middle band' - employees earning BETWEEN 40000 AND 80000. Q45 Loyalty wants Gold + Silver tier customers - use IN. Q46 Exclusion list: customers whose tier is NOT IN ('Bronze', 'Platinum'). Q47 The Ops dashboard wants orders that are either Delivered or Shipped - use IN. Q48 Escalation queue: tickets whose priority is IN ('High', 'Critical'). Q49 Catalog audit - products whose name STARTS WITH 'A'. Q50 Marketing wants every 'Pro' line product - product_name CONTAINS 'Pro'. Q51 The premium 'Pro' tier suffix - product_name ENDS WITH 'Pro'. Q52 The Gmail-first email campaign - customers whose email ends with '@gmail.com'. Q53 Same for Yahoo users - email ends with '@yahoo.com'. Q54 HR wants every 'Manager' across roles - role contains 'Manager'. Q55 The Sales org tree - employees whose role STARTS WITH 'Sales'. Q56 Customer call wants to find 'Priya' (any casing) - first_name ILIKE 'priya%'. Q57 Catalog wants every Samsung product (any casing) - product_name ILIKE 'samsung%'. Q58 A reporting quirk - customers whose first_name has 'a' as the SECOND letter (LIKE '_a%'). Q59 Logistics wants the 'in transit' list - sales.shipments where delivered_date IS NULL. Q60 Same logistics dashboard - already-delivered shipments where delivered_date IS NOT NULL. Q61 Privacy report: anonymous page-view sessions - web_events.page_views where customer_id IS NULL. Q62 Logged-in user page views - customer_id IS NOT NULL. Q63 The support queue 'still open' - tickets where resolved_date IS NULL. Q64 The support team wants closed tickets - resolved_date IS NOT NULL. Q65 The CFO wants the post-2025 order book - orders where order_date >= '2025-01-01'. Q66 Finance wants campaigns with very specific budget amounts - budget IN (100000, 200000, 500000). Q67 The merchandising shortlist - products whose brand_id is in (1, 2, 3, 4, 5). Q68 Call analytics - calls where call_reason IN ('Complaint', 'Inquiry'). Q69 Acquisition team wants customers who joined IN 2024 - registration_date BETWEEN '2024-01-01' AND '2024-12-31'. Q70 CFO wants only 2025 orders - use order_date >= '2025-01-01' AND order_date < '2026-01-01'. ORDER BY + LIMIT + OFFSET + DISTINCT Q71 The premium catalog needs the 10 most expensive products for the homepage. Q72 The 'budget products' carousel - 10 cheapest products. Q73 The DBA wants the 5 most recent orders for a smoke test. Q74 Historical review - the 5 earliest orders ever placed. Q75 CHRO wants the top 10 highest-paid employees for the compensation review. Q76 HR wants the 10 lowest-paid employees for the minimum-wage compliance check. Q77 Marketing wants the newest customers first - sort by registration_date DESC. Q78 Customer Service wants the directory alphabetically - by first_name. Q79 Store Ops wants every store ordered by city for the regional review. Q80 The CFO wants the 20 highest-value orders by net_total. Q81 Catalog ordering - products sorted by price DESC, then by product_name ASC (tie-break). Q82 Sort employees by salary DESC, then by first_name ASC. Q83 The call-center supervisor wants the 5 longest support calls. Q84 Web analytics wants the 10 most recent page_views. Q85 HR wants the 20 most recent attendance records. Q86 The CFO wants the top 10 refund_amount returns for the loss review. Q87 The CMO wants the 5 highest-budget campaigns. Q88 Production wants the top 10 work_orders by quantity_produced. Q89 Loyalty wants the 5 OLDEST customers - earliest registration_date. Q90 Logistics wants shipments sorted by delivered_date with the in-transit ones at the bottom (NULLS LAST). Q91 Support wants tickets sorted by resolved_date with unresolved ones at the TOP (NULLS FIRST). Q92 The pagination test - PAGE 1 (rows 1-10) of customers ordered by customer_id. Q93 PAGE 2 (rows 11-20) of customers ordered by customer_id. Q94 PAGE 3 of the price-DESC product list, 20 per page (rows 41-60). Q95 PAGE 5 of the high-value orders list (20 per page, rows 81-100), sorted by net_total DESC. Q96 The Web Analytics team wants the distinct device types - what unique values exist? Q97 Loyalty wants the list of all tier names (no duplicates). Q98 The Ops team wants every distinct order_status that has appeared. Q99 Store Ops wants the alphabetical list of distinct cities. Q100 Support wants the alphabetical list of distinct ticket categories. Combined ideas, multi-step thinking
FILTERING DEEPER - CONCEPTUAL Q1 In WHERE A AND B OR C - which is evaluated first, AND or OR? Q2 Why is WHERE NOT (col = 5) different from WHERE col != 5 when col can be NULL? Q3 What does the three-valued logic of SQL mean - TRUE / FALSE / what? Q4 Explain why WHERE col = NULL returns no rows but WHERE col IS NULL does. Q5 What's the difference between IS DISTINCT FROM and !=? Q6 In WHERE x IN (1, 2, NULL) - does the NULL match anything? Q7 In WHERE x NOT IN (1, 2, NULL) - what's the surprising result and why? Q8 Explain the difference between IS TRUE and = TRUE on a BOOLEAN column. Q9 Compare WHERE col LIKE '%abc%' vs WHERE position('abc' IN col) > 0 - same result, but which is faster on a large table? Q10 What's the cost of WHERE LOWER(col) = 'priya' - and why does it disable a regular index? Q11 Why is BETWEEN '2025-01-01' AND '2025-01-31' slightly different from >= AND < when col has TIME parts? Q12 Explain what ESCAPE means in LIKE '50\%' ESCAPE '\'. Q13 Difference between ORDER BY 1 and ORDER BY col_name - which is safer for production? Q14 In multi-column ORDER BY, does each column have its own ASC/DESC? Show example. Q15 What does NULLS FIRST vs NULLS LAST control? Q16 What is the default position of NULLs in ASC vs DESC ORDER BY? Q17 Difference between LIMIT 10 and FETCH FIRST 10 ROWS ONLY. Q18 Why is OFFSET 1000000 LIMIT 10 slow - and what's the alternative for pagination? Q19 Difference between DISTINCT and DISTINCT ON (col). Q20 Why might SELECT DISTINCT * be misleading on a table with TIMESTAMP columns? Q21 What is "keyset pagination" and why is it faster than offset pagination? Q22 Explain the precedence of AND/OR/NOT - give a query where missing parens changes the result. Q23 What does <> mean - same as !=? Q24 Compare WHERE col1 = col2 vs WHERE col1 IS NOT DISTINCT FROM col2 on NULLable columns. Q25 Why might SELECT * FROM t LIMIT 5 give different rows each time (without ORDER BY)? COMPLEX WHERE - MULTI-CONDITION Q26 Marketing wants Gold customers in Mumbai OR Delhi who registered in 2024. Show the precedence-correct query. Q27 Support wants Critical OR High priority tickets that are still 'Open'. Q28 The CMO wants customers whose tier is Gold or Platinum AND whose phone starts with '+91 9'. Q29 Show orders that are NOT Delivered AND NOT Cancelled AND placed in 2025. Q30 Find products priced > 1000 AND cost_price > 500 AND brand_id NOT IN (1, 2). Q31 Find employees with salary > 50000 AND (role LIKE '%Manager%' OR role LIKE '%Director%'). Q32 Find call_center.calls longer than 600 seconds AND with call_reason IN ('Complaint', 'Inquiry'). Q33 Find sales.shipments where delivered_date IS NULL AND shipped_date < CURRENT_DATE - 7 (stale in-transit). Q34 Find tickets created in the last 7 days AND priority IN ('High','Critical') AND resolved_date IS NULL. Q35 Find page_views from anonymous users (customer_id IS NULL) AND device_type = 'Mobile' AND view_timestamp >= CURRENT_DATE - 30. Q36 Find expenses > 100000 in 2025 AND exp_cat_id IN (1, 2, 3, 4, 5). Q37 Find loyalty members with points_balance BETWEEN 500 AND 5000 AND join_date < CURRENT_DATE - INTERVAL '1 year'. Q38 Find returns where refund_amount > 5000 OR reason LIKE '%Defective%'. Q39 Find audit.application_logs at level 'ERROR' or 'FATAL' AND timestamp >= CURRENT_DATE - 1. Q40 Find api_requests where status_code = 500 AND endpoint LIKE '/api/v2/%' AND response_time_ms > 1000. Q41 Find products with price > 5000 AND (brand_id IS NULL OR brand_id IN (1, 2)). Q42 Find customers in tier Gold OR Platinum AND registered in 2024 OR 2025 - show the parenthesization needed. Q43 Find employees whose salary > 80000 AND role NOT LIKE '%Intern%' AND store_id IS NOT NULL. Q44 Find orders placed on weekends (Saturday/Sunday) with net_total > 10000. Q45 Find tickets where status = 'Open' AND priority IN ('High','Critical') AND age (CURRENT_TIMESTAMP - created_date) > INTERVAL '24 hours'. Q46 Find product_reviews where rating BETWEEN 1 AND 2 (negative) AND review_date >= CURRENT_DATE - 30. Q47 Find shipments where status = 'Delivered' AND (delivered_date - shipped_date) > INTERVAL '7 days' (slow deliveries). Q48 Find customers using IS DISTINCT FROM: WHERE tier IS DISTINCT FROM 'Bronze' (includes NULL tier!). Q49 Find rows using IS NOT TRUE on a BOOLEAN: stores.stores WHERE (some_boolean) IS NOT TRUE - captures FALSE OR NULL. Q50 Find orders where (CURRENT_DATE - order_date) BETWEEN 7 AND 30 (week-to-month-old orders). COMPLEX LIKE / ILIKE / IS NULL Q51 Customers whose first_name starts with 'A' or 'B' or 'C' using ILIKE. Q52 Customers whose email ends with @gmail.com OR @yahoo.com using two LIKEs joined by OR. Q53 Products with 'Pro' in the name but NOT ending in 'Pro'. Q54 Customers whose first_name has EXACTLY 4 letters (use LENGTH). Q55 Products with name matching the LIKE pattern '_ _ _%' (at least 3 chars with two embedded). Q56 Find any email that contains a literal underscore '_' character (use ESCAPE). Q57 Customers with phone starting '+91 90', '+91 91', or '+91 99'. Q58 Products whose name has the second character as 'a' (case-insensitive). Q59 Stores whose city contains exactly one space. Q60 Employees whose email is in the form '[email protected] ' - pattern match. Q61 Customers whose email does NOT use a Gmail or Yahoo domain. Q62 Products whose name contains a digit (use ~ regex operator). Q63 Customers whose first_name contains exactly two vowels (advanced - use regexp_matches or LENGTH tricks). Q64 Shipments where delivered_date IS NULL AND status != 'Cancelled' (truly pending). Q65 Tickets where resolved_date IS NULL AND priority = 'Critical' AND created_date < CURRENT_DATE - 2 (overdue critical). Q66 Customers whose phone IS NOT NULL AND LENGTH(phone) != 14 (incorrectly formatted Indian phone with +91). Q67 Products whose supplier_id IS NULL AND price > 5000 (high-value, no supplier - data quality issue). Q68 Page_views where customer_id IS NULL AND device_type = 'Mobile' (anonymous mobile users for retargeting). Q69 Payments where order_id IS NOT NULL AND amount IS NULL (audit anomaly). Q70 Customers whose tier_updated_at IS DISTINCT FROM registration_date (those who upgraded tiers). Q71 Returns whose refund_amount IS NULL (returns awaiting refund processing). Q72 Employees whose store_id IS NULL OR dept_id IS NULL (incomplete records). Q73 Customers whose email matches '%@%.%' (basic email shape check). Q74 Products whose product_name has a '%' sign in it (LIKE with ESCAPE). Q75 Tickets whose subject starts with a digit (e.g., '500-something'). SORTING + PAGINATION Q76 Top 10 products by price DESC, tie-broken by product_name ASC. Q77 Bottom 10 employees by salary, tie-broken by joining_date DESC (most recent hire first within a tie). Q78 Orders sorted by order_date DESC NULLS LAST, then net_total DESC. Q79 Customers ordered by registration_date DESC - paginated to page 4 (20 per page). Q80 Products ordered by price DESC - get page 7 (rows 121-140) using LIMIT/OFFSET. Q81 Page 1 of high-value orders (net_total > 5000), sorted by order_date DESC, 25 per page. Q82 Top 5 cities by store count (need GROUP BY - single line). Q83 Most recent 10 support tickets across all priorities. Q84 Most recent 5 page_views per device_type - use DISTINCT ON. Q85 Most recent 1 order per customer using DISTINCT ON (cust_id) ... ORDER BY cust_id, order_date DESC. Q86 Get the 50th most expensive product (ORDER BY price DESC LIMIT 1 OFFSET 49). Q87 Get the 100th oldest customer registration. Q88 Top 3 customer tiers by member count. Q89 Sorted list of distinct courier_names from sales.shipments. Q90 Top 10 longest-running calls in the last 30 days. Q91 Orders sorted with NULL net_total at the bottom even in DESC sort. Q92 List products with the SAME price (handles ties): order by price DESC then product_id ASC for a stable order. Q93 Top 10 stores by opening_date (oldest first). Q94 Most recent 20 ad_spend rows per platform. Q95 Show 5 page_views - but PAGE 1 of MOBILE users only, ordered by view_timestamp DESC. Q96 Pagination using KEYSET (not OFFSET): orders WHERE order_date < last_seen_date ORDER BY order_date DESC LIMIT 20. Q97 Top 5 brand_ids by product count. Q98 Top 10 customers by registration_date DESC, excluding any with NULL first_name. Q99 Top 10 finance.expenses by amount DESC, only from 2025. Q100 Show the 25 most recently shipped shipments (where shipped_date IS NOT NULL). Interview grade, edge cases
FILTERING & SORTING - CONCEPTUAL Q1 What does "sargable" mean - and why does WHERE LOWER(email) = ... defeat an index? Q2 Compare WHERE col = NULL vs WHERE col IS NULL - why the first never matches. Q3 Explain IS DISTINCT FROM - and why it's safer than = for nullable columns. Q4 Walk through how WHERE col BETWEEN x AND y treats inclusive bounds. Q5 Why is WHERE col1 = a AND col2 = b often faster with a composite index (col1, col2)? Q6 Explain index column-order matters: (a, b) vs (b, a). Q7 Why is WHERE date_col >= '2025-01-01' AND date_col < '2026-01-01' faster than EXTRACT(year FROM date_col) = 2025? Q8 Compare ILIKE 'abc%' vs ILIKE '%abc' - only one is index-usable. Q9 Walk through LIMIT + OFFSET pagination - and why deep OFFSETs are slow. Q10 Explain keyset pagination - show ORDER BY id > last_seen_id LIMIT 50. Q11 What is ORDER BY ... NULLS LAST - and what's the default for ASC vs DESC? Q12 Compare DISTINCT vs DISTINCT ON - and when each preserves which row. Q13 Explain WHERE x = ANY(array) vs WHERE x IN (...) - semantically equivalent. Q14 What is WHERE x = ALL(subquery) - and why is it rarely used? Q15 Explain EXISTS vs IN - when does each scale better? Q16 Why does NOT IN break when the subquery returns NULLs? Q17 Compare NOT EXISTS vs LEFT JOIN ... IS NULL for anti-join. Q18 What does WHERE col @@ tsquery do - full-text search predicate. Q19 Explain how a covering index can answer a query without touching the heap. Q20 What is "row constructor compare": (a, b) > (1, 2) - and how does it help keyset paging. Q21 Why is ORDER BY RANDOM() LIMIT 1 catastrophic on huge tables? Q22 Compare WHERE col IN (subq) vs WHERE col = (subq scalar). Q23 Explain WHERE col SIMILAR TO regex - and why most use ~ instead. Q24 What is a "false predicate" (WHERE 1=0) - used as table-shape filter. Q25 Walk through the planner's decision: SeqScan vs IndexScan vs BitmapIndexScan. INDEX-AWARE FILTERING Q26 Find orders in date range '2025-03-01' to '2025-04-01' (sargable). Q27 Find customers whose email LIKE 'a%' (prefix-search index-friendly). Q28 Find products WHERE price BETWEEN 1000 AND 5000 (range index). Q29 Find orders WHERE order_status IN ('Pending','Processing') using IN-list. Q30 Find products WHERE supplier_id = 10 AND brand_id = 3 (composite-index candidate). Q31 Find tickets WHERE priority = 'Critical' AND status = 'Open' (composite). Q32 Find shipments WHERE courier_name = 'Bluedart' AND shipped_date >= now() - 7. Q33 Find page_views WHERE device_type = 'Mobile' AND os = 'iOS' (composite-index potential). Q34 Find employees WHERE role = 'Manager' AND store_id IN (1,2,3). Q35 Find orders WHERE net_total > 10000 AND order_date >= '2025-01-01' (compound). Q36 Sargable date filter: orders in current month (DATE_TRUNC vs range bounds). Q37 Sargable: WHERE created_at >= now() - INTERVAL '7 days'. Q38 Non-sargable rewrite: WHERE year(order_date) = 2025 -> WHERE order_date >= '2025-01-01' AND order_date < '2026-01-01'. Q39 Index-only scan: SELECT email FROM customers WHERE email LIKE 'a%' (with appropriate index). Q40 Find tickets WHERE resolved_date IS NULL (partial-index candidate). Q41 Find orders WHERE order_status = 'Cancelled' (partial-index for rare value). Q42 Find customers WHERE deleted_at IS NULL AND email = '[email protected] '. Q43 Find pay_slips WHERE salary_year = 2025 AND salary_month IN (1,2,3). Q44 Find reviews WHERE rating >= 4 AND created_at >= '2025-01-01'. Q45 Find inventory_snapshots WHERE warehouse_id = 5 AND snapshot_date = '2025-04-15'. Q46 Find calls WHERE call_reason = 'Refund' AND duration > 300. Q47 Find ad_spend WHERE platform = 'Facebook' AND spend_date BETWEEN ... AND .... Q48 Find page_views with referrer_url LIKE 'https://google.%' (prefix). Q49 Find customers with tier_id IN (3, 4) - top tiers. Q50 Find supply_chain.shipments WHERE supplier_id = 7 AND quantity > 100. PAGINATION + ORDER BY EDGE CASES Q51 OFFSET-LIMIT pagination: orders page 100, page size 50 (OFFSET 4950). Q52 Keyset pagination: orders WHERE (order_date, order_id) < (last_date, last_id) ORDER BY order_date DESC, order_id DESC LIMIT 50. Q53 ORDER BY net_total DESC NULLS LAST - keep NULLs at end. Q54 ORDER BY tier_id NULLS FIRST - surface "no tier" first. Q55 ORDER BY priority CASE WHEN priority='Critical' THEN 1 WHEN 'High' THEN 2 ... (custom sort). Q56 Tie-breaker: ORDER BY revenue DESC, customer_id ASC (deterministic order). Q57 ORDER BY DATE_TRUNC('month', order_date), net_total DESC - bucket-then-sort. Q58 SELECT DISTINCT ON (cust_id) * FROM orders ORDER BY cust_id, order_date DESC - latest order per customer. Q59 SELECT DISTINCT ON (product_id) ... ORDER BY product_id, review_date DESC - most-recent review per product. Q60 Top-N per group via window or DISTINCT ON. Q61 Stable pagination across DELETEs - why id-based keyset is robust. Q62 Sort with LOCALE: ORDER BY full_name COLLATE "C" vs default. Q63 Sort numbers stored as TEXT: ORDER BY col::int (cast). Q64 Sort emails by domain: ORDER BY split_part(email, '@', 2). Q65 Sort tickets by priority weight: CASE-driven. Q66 Pagination cursor with composite key (created_at, id). Q67 Backward pagination (previous page) using keyset. Q68 LIMIT + OFFSET 0 - degenerate case (just LIMIT). Q69 LIMIT 0 - return no rows but force query plan & metadata. Q70 ORDER BY column_position (1, 2, 3) - quick demo. Q71 Find duplicates: ORDER BY email, customer_id then row_number window pattern. Q72 Avoid OFFSET 100000: use keyset with composite cursor. Q73 ORDER BY 1 vs ORDER BY full_name - when each is appropriate. Q74 ORDER BY RANDOM() LIMIT N - sample N random rows (small tables only). Q75 TABLESAMPLE BERNOULLI(1) - proper random sampling on huge tables. SUBQUERY & SET FILTERS Q76 EXISTS: customers who placed at least one order. Q77 EXISTS: products with at least one 5-star review. Q78 NOT EXISTS: customers who never wrote a review. Q79 NOT EXISTS: products that never sold. Q80 IN (subquery): orders by Gold-tier customers. Q81 NOT IN (subquery): customers NOT in loyalty.members - show NULL-safety variant with NOT EXISTS. Q82 = ANY: orders matching list of statuses pulled from a config table. Q83 > ALL: products priced higher than all products of brand_id=5. Q84 < ANY: customers whose tier_id < ANY(SELECT tier_id FROM ...). Q85 Find orders by customers in the top 10 highest-spend cust_ids (subquery + IN). Q86 Find products in categories with > 100 products. Q87 Find tickets opened on dates when there was a system outage (subquery joining audit logs). Q88 Find customers in cities where there is at least one store. Q89 Find shipments in months where average delivery time was < 2 days. Q90 Find pay_slips in months when total payroll > 100,000 (HAVING + subquery). Q91 Find orders whose product mix overlaps with the top-selling brand. Q92 Find ad_campaigns active during a customer signup spike (subquery joining). Q93 Find customers whose tier matches a calculated cohort. Q94 Find products in brands whose AVG(price) > 5000 (correlated subquery). Q95 Find employees whose salary > AVG(salary) for their department (correlated subquery). Q96 Find customers who placed > 3 orders in any single week (subquery + grouping). Q97 Find products whose total units sold > median product units. Q98 Find orders that placed in the same hour as the spike (audit-linked). Q99 Find calls handled by agents who also resolved tickets (intersection-style subquery). Q100 Find customers who have ALL of {order, review, ticket, call} (relational division pattern). Production scenarios, optimisation
CONCEPTUAL Q1 Explain SQL three-valued logic (TRUE/FALSE/UNKNOWN) and how WHERE treats UNKNOWN. Q2 Why does x = NULL never match, and what should you use instead? Q3 Explain IS DISTINCT FROM and why it is "NULL-safe equality". Q4 Why can NOT IN (subquery) return zero rows when the subquery has a NULL? Q5 Compare EXISTS vs IN - semantics, NULL-safety, and how planners treat them. Q6 State De Morgan's laws and why they matter when negating compound predicates. Q7 Explain AND/OR precedence: how is "a OR b AND c" parsed? Q8 Why prefer half-open ranges (>= start AND < end) over BETWEEN for dates? Q9 Why are deep OFFSETs slow, and what does the engine actually do? Q10 Describe keyset pagination and why it beats OFFSET for large pages. Q11 What are the default NULL orderings for ASC and DESC, and how do you override? Q12 Compare DISTINCT vs DISTINCT ON - which row does DISTINCT ON keep? Q13 Show that x IN (a,b,c) equals x = ANY(ARRAY[a,b,c]). Q14 Explain x = ALL(subquery) and > ALL(subquery) - when is each true? Q15 Explain < ANY(subquery) and > ANY(subquery) in terms of MIN/MAX. Q16 Two ways to express relational division ("matches ALL of a set"). Q17 Compare NOT EXISTS vs LEFT JOIN ... IS NULL for anti-joins. Q18 What makes a predicate "sargable", and how does it shape how you write WHERE? Q19 Expand the row-constructor comparison (a,b) > (1,2). Q20 What does COLLATE "C" do to ORDER BY, vs a locale collation? Q21 Why is ORDER BY RANDOM() expensive, and what is the cheaper sampling option? Q22 Compare col = (scalar subquery) vs col IN (subquery) - cardinality rules. Q23 Compare SIMILAR TO, POSIX ~, and LIKE prefix vs suffix matching. Q24 Why does a stable/paginated sort need a unique tie-breaker column? Q25 Does the written order of WHERE predicates change the result or the plan? COMPLEX PREDICATES & NULL LOGIC Q26 Find customers whose phone is missing (NULL or empty string). Q27 Find shipments where delivered_date differs from shipped_date, NULL-safely. Q28 Find Returned-or-Cancelled orders over 5000 (mind OR/AND precedence). Q29 Find orders that are NOT (Delivered AND under 1000) - apply De Morgan. Q30 Find March-2025 orders using a half-open date range. Q31 Find promotions overlapping the window 2025-06-01..2025-06-30. Q32 Find orders whose net_total is zero, treating NULL as zero via COALESCE. Q33 Find orders whose status is none of Delivered/Shipped/Out for Delivery. Q34 Find customers whose email begins with 'a' (case-insensitive). Q35 Find customers whose email local-part contains a digit (regex). Q36 Find customers whose name contains a non-ASCII character. Q37 Find customers who have a tier but no tier_updated_at timestamp. Q38 Find products priced 1000-5000 but excluding exactly 1999. Q39 Find orders where gross_total - discount_amount exceeds 10000. Q40 Find customers whose tier is anything other than Platinum (include NULLs). Q41 Find addresses with a valid 6-digit numeric pincode. Q42 Find reviews that are unrated (NULL) or rated below 2. Q43 Find customers whose email does NOT end in .com/.in/.net/.org. Q44 Find 2025+ orders with net_total between 2000 and 8000. Q45 Find order_items with positive quantity but non-positive net_amount (data smell). Q46 Find tickets unresolved for more than 30 days (created_date is a timestamp). Q47 Find Critical/High tickets using = ANY over an array. Q48 Find customers whose first_name has leading/trailing whitespace. Q49 Find orders where "Cancelled" and "net_total = 0" disagree (XOR-style). Q50 Rank products by margin %, guarding against price = 0 division. SET-BASED FILTERS - EXISTS / IN / ANY / ALL / DIVISION Q51 Customers who placed at least one order (EXISTS). Q52 Products that never sold (NOT EXISTS). Q53 Customers not in loyalty.members - NULL-safe with NOT EXISTS. Q54 Orders placed by Platinum-tier customers (IN subquery). Q55 Products priced above every product of brand 5 (> ALL). Q56 Members whose tier rank is below at least one Mumbai member (< ANY). Q57 Orders whose status is in a VALUES list (= ANY, read-only - no config table). Q58 Products that have at least one 5-star review (correlated EXISTS). Q59 Customers who reviewed but never ordered (EXISTS + NOT EXISTS). Q60 Orders containing products from brands that have more than 100 products. Q61 Customers who bought from ALL of categories {1,2,3} (HAVING COUNT DISTINCT). Q62 Customers present in orders AND reviews AND tickets (chained EXISTS). Q63 Orders above the global average net_total (scalar subquery). Q64 Products priced above their own brand's average (correlated scalar). Q65 Orders by the top-10 highest-spending customers (IN aggregated subquery). Q66 Stores that have never had a Returned order (NOT EXISTS). Q67 Tickets opened on a day with >100 ERROR/FATAL log entries (audit subquery). Q68 Customers who live in a city that has a store (city via addresses). Q69 Products priced above at least one brand's average price (> ANY). Q70 Customers with no orders - NOT IN made safe by filtering NULLs. Q71 Customers with at least one order over 50,000 (correlated EXISTS, inequality). Q72 Customers who bought every product of brand 5 (division via count subquery). Q73 Customers with 10+ orders using a derived table in FROM. Q74 Customers who ordered but never returned anything (EXISTS + NOT EXISTS). Q75 Brands whose every product is priced under 20000 (> ALL guarantee). PAGINATION, ORDERING & TOP-N WITHOUT WINDOW FUNCTIONS Q76 Page 100 (size 50) of orders by id using OFFSET - the slow way. Q77 The same page using keyset pagination (order_id > last_seen). Q78 Forward page using a composite (order_date, order_id) cursor. Q79 Backward (previous) page using keyset - flip comparison and ORDER BY. Q80 Top orders by net_total, keeping NULLs last. Q81 Sort tickets by custom priority weight (CASE), then newest first. Q82 Top-20 customers by revenue with a deterministic tie-break. Q83 Latest order per customer using DISTINCT ON. Q84 Most-recent review per product using DISTINCT ON. Q85 Sort customers by name using COLLATE "C" (byte order). Q86 Sort customers by email domain, then full email. Q87 Sort phone numbers (TEXT) numerically, not lexically. Q88 Top-3 orders per customer WITHOUT a window function (correlated count). Q89 The single highest-value order per customer via correlated NOT EXISTS. Q90 Products selling above the median units sold (PERCENTILE_CONT, no window). Q91 The second-highest-priced product per brand WITHOUT a window function. Q92 Paginate customers on a stable (registration_date, customer_id) cursor. Q93 Order reviews by review-text length, longest first. Q94 Top-10 stores by revenue with a deterministic tie-break. Q95 Bottom-10 products by margin (ORDER BY ASC + LIMIT). Q96 Earliest order per store using DISTINCT ON ascending. Q97 Paginate customers with >50k revenue by customer_id cursor (HAVING + ORDER BY). Q98 The 50 most recent still-open Critical tickets. Q99 Take a ~1% random sample of orders efficiently (TABLESAMPLE). Q100 Latest DELIVERED order per customer over 5000, newest first - no window functions.