Writing Advanced SQL Queries: Techniques and Patterns

UPI Study › Courses › Database Programming › Free lessons › Lesson 4.6 Free with a free account

Writing Advanced SQL Queries: Techniques and Patterns

Database Programming · Chapter 4: SQL Data Types in DepthSection 4.6 · lesson 25 of 7610 min · free with a free account

← Storing Binary Data: The BLOB TypeNext lesson: Adding Records with the INSERT Statement →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Filtering rows with WHERE, BETWEEN, IN, LIKE, DISTINCT, and type conversion.

  • Combine comparison and logical operators in WHERE clauses using explicit parentheses
  • Apply BETWEEN, IN, and LIKE according to their exact meanings
  • Filter time-bearing values with a half-open date range
  • Explain how DISTINCT and explicit type conversion affect query results

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,141 words). Read along, or search it.

Opening Question

Narrowing a Focused Product List

Maya Rao, Lantern Books' owner, needs a focused product list. Which conditions answer her question? This disposable shop database retains our canonical products, prices, and stock. Categories and added-on dates are illustrative extensions. Run the setup, and inspect the products. Explicit ordering makes this demonstration predictable. Eight products are available. We will narrow them with filters, distinguish repeated values, and handle conversions deliberately. The decimal declaration still has SQLite numeric affinity. These filters do not create fixed-scale arithmetic.

Definition

WHERE Keeps Only True Conditions

Where introduces a condition, a test applied to candidate rows. Only a true result qualifies; false and unknown results do not. Find books below twenty-three dollars. Category can filter rows without appearing in the selected columns. Run it, and inspect the identifiers surviving both comparisons. World History and Statistics Workbook qualify. And requires both conditions; or requires at least one; not reverses true and false. Conceptually: from supplies rows, where filters, select forms results, distinct deduplicates. Physical execution may differ. Quote text and dates; leave numeric literals unquoted. Find missing values with is null, never equality with null.

Comparison Operators

Not-Equal Tests and Stock Thresholds

Comparisons express equal, unequal, less, and greater relationships. Greater than or equal includes the boundary. This filter combines a stock threshold with not-equal category. Exclamation mark equals also means not equal. Run the query, with identifiers ordered for easy comparison. Database Basics and the three stationery products remain. Reading Lamp fails the category test, as well as this stock threshold. Text case rules depend on collation and engine. SQLite equality normally distinguishes case here; default like behavior folds ordinary A S C I I letters. Negating unknown still gives unknown. Not does not turn a missing comparison into a known yes.

Operator Precedence

Grouping AND and OR With Parentheses

Precedence groups tests without parentheses. Here, comparisons come before not, then and, then or. The first query accepts any stationery product, plus equipment over ten dollars. The second requires the price threshold for both categories. Run both counts, comparing the effect of explicit grouping. The ungrouped condition keeps four rows; the grouped condition keeps one. Parentheses change which category branch must satisfy the price test. Even when defaults work, explicit parentheses make mixed logic easier to review.

Quick Check

Cheap Books or Out-of-Stock Items

A new clearance dataset asks for books below twenty dollars, or any item with no stock left. How many rows satisfy the condition? Count a row once, even if both branches match. Pause and predict.

Answer

Counting Each Matching Row Once

Two rows qualify, the first choice. The inexpensive book and the out-of-stock stationery item survive. Run the count: the book also has zero stock, but that does not duplicate its result row. One would omit the stationery branch. Three would wrongly admit an item that satisfies neither branch.

Range and List Tests

BETWEEN Endpoints and IN Lists

Between includes both endpoints. Write the lower endpoint first; reversed numeric bounds produce no matches. In tests membership in a list, replacing a chain of or comparisons on one column. Here it accepts books or equipment. Run the range and list together, as one combined condition. Four product identifiers survive: eleven, twelve, fourteen, and eighteen. Values exactly at either price endpoint are included. Not between reverses a known range result. Not in excludes listed values, but a null in its list can make comparisons unknown. Add conditions incrementally, inspecting rows after each change. Compact syntax still needs clear meaning.

Pattern Matching

LIKE Wildcards and Escape Characters

Like matches a text pattern. Percent stands for any number of characters, including none; underscore stands for exactly one character. This pattern begins with P, allows one character, then requires n. The trailing percent allows the rest of the name. Run both pattern tests. The second names an escape character, so its percent sign is treated literally. Pen Set matches the first pattern. The escaped test returns true for the literal percentage text. A starts-with pattern may support an index range search. A leading wildcard usually prevents that prefix search. Other filters or access paths may still help. SQL Server bracket patterns are not portable.

Date Ranges

Half-Open Ranges for Time-Bearing Dates

Ranges need special care when a date column also holds a time. A last-day date literal can exclude later times on that day. For all of September, use an inclusive start and an exclusive October start. This example uses consistent, normalized U T C text. Run the filter, using full timestamps with consistent format. September thirtieth at eighteen hundred survives; October first at midnight does not. The upper boundary is excluded. Normalize text before comparing. Mixed offsets, formats, or precisions can break the correspondence between lexical and chronological order.

Deduplication

DISTINCT Compares Every Selected Column

Distinct removes duplicate result rows, comparing every selected column together. The first column has no special status. Selecting only category collapses repeated products into one value per category. Run with explicit ordering. Distinct promises uniqueness, not presentation order. The three categories remain once each. Adding price would instead compare category-and-price pairs, preserving multiple rows within a category. Request uniqueness when needed. Investigate unexpected duplicates before hiding them; deduplication also costs processing.

Type Conversion

Explicit CAST and Implicit Conversion

Conversion changes a value's type. Explicit conversion is requested; implicit conversion happens automatically to make operands compatible. Cast uses the form, cast a value as a target type. This SQLite query converts numeric text, performs mixed-type arithmetic, and tries invalid numeric text. Run the examples, and inspect this engine's actual results. The results are one hundred twenty-four, eight, and zero. SQLite's invalid text-to-integer cast does not raise the conversion error another engine might produce. That zero can hide bad input. Validate values, and compare compatible types deliberately.

Dialect Comparison

CAST and CONVERT Differ by Engine

Cast targets differ. MySQL uses signed or unsigned for integer targets, and char for text. SQL Server accepts int and varchar targets. Its convert function puts the type first, while MySQL's two-argument form puts the value first. SQL Server style twenty-three requests year-month-day text. That formatting argument is not portable. Invalid text can coerce to zero with warnings in MySQL numeric contexts. SQL Server can instead stop with a conversion error; SQLite has its own rules. A decimal cast can round fractional detail in engines with fixed decimal types. For SQLite date parsing, use date functions instead of casting as date. Supply correctly typed values when possible. Converting an indexed column can obstruct useful index access.

Quick Check

Distinct City and Channel Pairs

A new visits report selects distinct city-and-channel pairs from the four displayed records. How many distinct pairs remain? The report needs both columns, not cities alone. Pause and predict. Three pairs remain, the third choice. The repeated Pune web visit collapses, while Pune counter stays separate. Run the query: its count confirms three. Two would count only cities, discarding the channel distinction required by this report. Distinct applies to the complete selected row. Choosing result columns is part of deciding what counts as a duplicate.

Key Takeaways

Predicates Built From the Business Question

Build predicates from the business question. Group mixed logic, and handle missing values with null tests. Choose range, membership, and pattern operators for their actual meanings. For time-bearing values, prefer a carefully normalized half-open interval. Choose columns before deduplicating, and convert types deliberately. Maya needs clear conditions, as well as executable syntax.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Writing Advanced SQL Queries: Techniques and Patterns

What is the order of precedence for AND, OR, and NOT in SQL?
SQL evaluates comparisons first, then NOT, then AND, then OR, unless parentheses change the grouping. So WHERE category = 'stationery' OR category = 'equipment' AND price > 10 means stationery at any price plus equipment over 10. Writing WHERE (category = 'stationery' OR category = 'equipment') AND price > 10 applies the price test to both categories. Explicit parentheses make mixed AND and OR logic easier to read and review.
Does BETWEEN include the endpoints in SQL?
Yes, BETWEEN includes both endpoints, so price BETWEEN 10 AND 20 matches 10, 20, and every value in between. Write the lower bound first, because reversed numeric bounds such as BETWEEN 20 AND 10 match nothing. For columns that also hold a time, a last-day upper bound can miss later times that day, so a half-open range like created_at >= '2026-09-01' AND created_at < '2026-10-01' is safer.
What do the % and _ wildcards mean in SQL LIKE?
In a LIKE pattern, the percent sign matches any number of characters, including none, and the underscore matches exactly one character. For example, name LIKE 'P_n%' matches Pen Set: a P, any one character, an n, then anything. To match a literal percent sign, name an escape character, as in name LIKE '%10!%%' ESCAPE '!'. Case sensitivity depends on the engine and collation; SQLite's default LIKE ignores case for ASCII letters.
Does DISTINCT apply to one column or the whole row?
DISTINCT applies to the whole selected row, removing a result row only when every selected column matches another. SELECT DISTINCT category FROM products returns each category once, but SELECT DISTINCT category, price keeps one row per category-and-price pair, so a category can appear several times. DISTINCT does not promise any order, so add ORDER BY when order matters, and investigate unexpected duplicates before hiding them.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →