UPI Study › Courses › Database Programming › Free lessons › Lesson 5.5 Free with a free account
Ordering Results: Sorting Techniques in SQL
Database Programming · Chapter 5: Querying, Filtering, and Sorting DataSection 5.5 · lesson 30 of 769 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: Built-In SQL Functions: How and When to Use Them →← Core Concepts for Manipulating Databases with SQLNext lesson: Built-In SQL Functions: How and When to Use Them →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Sorting query results with ORDER BY, multiple keys, NULLs, and collations.
- Write ORDER BY clauses with several keys, each with its own direction
- Place NULL values deliberately using a CASE expression as a sort key
- Explain how collations and text storage affect alphabetical and numeric ordering
- Choose aliases and unique tie-breakers for stable, maintainable sorts
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,029 words). Read along, or search it.
Opening Question
The Same Catalog in Two Orders
Sofia Alvarez prints Lantern Books' catalog twice. The products are correct both times, but their order changes, making a price comparison harder to follow. Nothing in her query requested a particular order. How can she describe a list that stays meaningful, including when several products share a category? Order by controls presentation. Direction, multiple keys, missing-value placement, and text comparison rules together define what the beginning of a result actually means.
Definition
ORDER BY Directions and Collations
Use our canonical products and the illustrative categories. Querying a table without order by makes no promise about the displayed sequence. Ascending is the default. Numbers go from smaller to larger, and date values from earlier to later; descending reverses the chosen comparison order. Text needs a comparison rule called a collation. Alphabetical-looking order can change with language, case sensitivity, and accent sensitivity. An order by clause usually follows filtering and output expressions logically. That is why a calculated alias can be a useful sorting name. Sorting is a query operation. It does not rearrange the permanent meaning of a table, and it does not imply a grouping or aggregation.
Multiple Sort Keys
Category Ascending, Price Descending
Read multiple sort keys from left to right. Category decides first; price matters only among products with equal categories. Each key has its own direction. Category ascending and price descending means category order first, then expensive products before cheaper products inside each category. The unique identifier is a final tie-breaker. It determines an order even if two products share both category and price. Run the mixed-direction sort. Adding a descending word to one key does not silently make every later key descending too. Book products appear in descending price order, followed by Equipment and Stationery. Moving price to the front would ask a different question about the whole catalog.
Sort Expressions
Sorting by Alias Instead of Column Position
A sort key can be an expression, an alias, or a column name. Here the alias names price multiplied by stock. You can sort by an expression without displaying it in an ordinary select. But distinct queries have stricter rules in MySQL and SQL Server. Column positions are another shortcut: order by two means the second selected expression. Inserting an earlier output column can silently change that meaning. Run the named-alias version. Names make the ranking easier to maintain than an ordinal position whose target can move. The highest stock values belong to Database Basics, Statistics Workbook, and Biology Guide. This ranks inventory value, a different measure from unit price.
NULL Placement
Putting Missing Dates Last With CASE
This disposable restock relation adds illustrative dates for selected product identifiers. Missing dates should appear after scheduled dates, with scheduled dates running earliest first. SQLite, MySQL, and SQL Server normally put null first in an ascending sort. PostgreSQL and Oracle have different defaults, so verify the target engine. The case expression creates a first key: zero for a recorded date and one for a missing date. The date and identifier supply later keys. Run the query. MySQL and SQL Server lack nulls last syntax; this case pattern works in both. The scheduled identifiers come first in date order, and the missing ones follow in identifier order. Case changes the sorting value without replacing the stored missing date.
Binary Collation
Uppercase Smith Sorts Before Lowercase Names
Compare three temporary name labels. SQLite's binary collation compares their encoding, so an uppercase initial can sort before a lowercase initial. Binary comparison is not a universal human alphabet. It does not mean every uppercase character in every script precedes every lowercase character. Run this explicitly binary order. A collation is part of the requested comparison, rather than a cosmetic change made after sorting. Smith with an uppercase initial appears before the lowercase names. Locale-aware case and accent rules require the appropriate engine's supported collation.
Case-Insensitive Sorting
SQLite NOCASE Collation and Ties
Now request SQLite's no case collation. For these ASCII names, letter case no longer separates the two spellings of Smith. The identifier still matters: names equal under the selected collation form a tie. A unique later key makes their relative order intentional. Run the changed comparison. SQLite's built-in no case behavior is limited, so do not treat this demonstration as a complete Unicode linguistic sorter. Adams comes first, and the Smith spellings follow by identifier. MySQL and SQL Server use their own collation names, with separately chosen case and accent rules.
Common Mistake
Text Ten Sorts Before Text Nine
Numbers stored as text are compared character by character. Text ten precedes text nine, because its initial character is smaller under the relevant digit ordering. A numeric report instead needs numeric intent. Here cast converts valid numeric references before ordering; the original text remains available for display. Run the numeric sort. In a real schema, store quantities as numeric types when that is their meaning, rather than repeatedly repairing their representation. The result is nine, ten, then one hundred. Conversion rules and invalid input behavior vary by engine, so validate data before assuming every string can be converted.
Portability
Collation Names and Outermost ORDER BY
These non-run fragments show that collation names are dialect-specific. Inspect the actual column or query collation, rather than guessing from a common installation default. With distinct, a hidden sort column can be ambiguous after duplicates collapse. MySQL's default strict rules and SQL Server reject such queries; SQLite is more permissive. Request final presentation in the outermost query. Inner ordering has legitimate uses with limiting or other features, but does not promise the final result's order.
Quick Check
Priority Descending, Then Code Ascending
A new dispatch queue sorts by descending priority, then ascending code. Two entries have equal priority, so the second key must settle their order. Which code sequence will the query return? Pause, and decide.
Answer
Each Key Settles Remaining Ties
The answer is P, Q, R. The higher-priority entries come first, and their equal priority makes ascending code the deciding key. R first would reverse the main direction. Q before P would ignore or reverse the second direction, despite leaving the priority groups in place. The run confirms a left-to-right comparison. Each key settles only the ties remaining after earlier keys have been compared.
Key Takeaways
An Ordered Result Is a Query Promise
Sofia can print an intentional catalog order. She defines the main ranking, adds later tie-breakers, and chooses where missing dates belong. Use names or aliases for maintainable sorts. Remember that collation controls text comparisons, while numeric quantities need numeric comparison. Ask the outermost query for the final order. An ordered result is a promise made by a query, not an accidental feature of stored rows.
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 Ordering Results: Sorting Techniques in SQL
How do you sort by multiple columns in SQL?
Where do NULL values appear when sorting in SQL?
Why does ORDER BY put 10 before 9?
Can you use ORDER BY with a column number or alias?
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 →