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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Adding Records with the INSERT Statement →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
Does BETWEEN include the endpoints in SQL?
What do the % and _ wildcards mean in SQL LIKE?
Does DISTINCT apply to one column or the whole row?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →