Beginner level · Module 2: Filtering and Sorting with SQL · Lesson 3 of 3
Sorting, Limiting and Calculated Columns
Order results, take the top rows, remove duplicates and calculate new values with aliases.
In this lesson you will
- Sort with ORDER BY and limit results
- Create calculated columns with clear aliases
Key concepts
ORDER BY ASC/DESCLIMITDISTINCTexpressions and AS
The lesson
ORDER BY visit_date DESC sorts newest first; several columns break ties: ORDER BY class, name. Without ORDER BY, the order of rows is not guaranteed.
LIMIT 10 returns only the first ten rows, which is useful for 'top 10' questions together with ORDER BY. DISTINCT removes duplicate rows, for example SELECT DISTINCT diagnosis FROM visits.
You can calculate in SELECT: quantity * price AS total or amount / 4500.0 AS amount_usd. Give calculated columns clear names with AS so reports are readable.
Step by step
- List the ten most recent visits.
- List the distinct diagnoses alphabetically.
- Calculate a total column with an alias.
- Convert SSP amounts to USD with a rate in the query.
Practice activity
Answer the remaining clinic questions, including the ten most recent visits and a list of distinct diagnoses.
Expected result: All fifteen practical questions are answered correctly.
Check your understanding
-
Is the order of rows guaranteed without ORDER BY?
Show answer
No.
-
Why divide by 4500.0 rather than 4500 in some databases?
Show answer
To avoid integer division and keep decimals.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.