Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Basic Queries in SQL ยท Lesson 6 of 10

Module Four

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
6

MODULE 5: SORTING AND LIMITING QUERY RESULTS

Module Overview

Welcome to Module 5 of Basic Queries! So far, you have learned how to retrieve information from databases using SELECT and how to find specific records using WHERE.

But imagine your school has 2,000 students. Your teacher wants to arrange their examination scores from the highest to the lowest. Or perhaps a supermarket manager wants to display only the five most expensive products. How can you do this?

SQL provides special commands called ORDER BY and LIMIT to help you arrange and control the number of records displayed.

In this module, you will learn how to sort records in ascending and descending order, arrange information using multiple columns, and limit the number of results displayed.

Lesson 1: Introduction to the ORDER BY Clause

The ORDER BY clause is used to arrange records in a database according to a particular column.

Think about your school's examination results. Your teacher may want to arrange students' scores from the lowest to the highest or from the highest to the lowest.

The ORDER BY clause makes this possible.

Basic SQL syntax:

SELECT column_name
FROM table_name
ORDER BY column_name;

For example, imagine you have a Students table containing students' names and ages.

You want to arrange the students according to their ages.

SELECT * FROM Students
ORDER BY Age;

This query arranges the student records by age in ascending order by default.

Remember: ORDER BY changes how records are displayed. It does not permanently rearrange or change the original records stored in the database.

Lesson 2: Sorting Records in Ascending Order

Ascending order means arranging values from the smallest to the largest.

For numbers, ascending order looks like this:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

For names, ascending alphabetical order starts with A and moves towards Z.

SQL uses the keyword ASC to arrange records in ascending order.

Example: Students table

StudentID Name Age Score
101Daniel1375
102Mary1290
103Peter1465
104Aisha1385
105John1270

Example 1: Arrange students by age from youngest to oldest.

SELECT * FROM Students
ORDER BY Age ASC;

Example 2: Arrange students alphabetically by name.

SELECT * FROM Students
ORDER BY Name ASC;

Example 3: Arrange examination scores from lowest to highest.

SELECT * FROM Students
ORDER BY Score ASC;

Quick Tip: ASC means ascending. It is optional because SQL uses ascending order by default when ORDER BY has no direction specified.

Lesson 3: Sorting Records in Descending Order

Descending order means arranging values from the largest to the smallest.

For numbers, descending order looks like this:

100, 90, 80, 70, 60, 50, 40, 30

For names, descending alphabetical order moves from Z towards A.

SQL uses the keyword DESC to arrange records in descending order.

Example 1: Arrange students by age from oldest to youngest.

SELECT * FROM Students
ORDER BY Age DESC;

Example 2: Display the highest examination scores first.

SELECT * FROM Students
ORDER BY Score DESC;

Example 3: Arrange students' names from Z to A.

SELECT * FROM Students
ORDER BY Name DESC;

Descending order is useful when you want to identify the highest score, most expensive product, largest quantity, or newest record based on a suitable column.

Lesson 4: Sorting by Multiple Columns

Sometimes, arranging information using only one column is not enough. You may want to arrange records using two or more columns.

SQL allows you to do this by separating the column names with commas inside the ORDER BY clause.

Imagine a school wants to arrange students by class and then by their names alphabetically.

Example:

SELECT * FROM Students
ORDER BY Class ASC, Name ASC;

This query first arranges students according to their classes. Within each class, it arranges students alphabetically by name.

Another example:

Imagine a supermarket wants to arrange products by category and display the most expensive products first within each category.

SELECT * FROM Products
ORDER BY Category ASC, Price DESC;

The database first arranges products alphabetically by category. Within each category, products are arranged from the highest price to the lowest price.

Important: SQL follows the order of the columns written in the ORDER BY clause. The first column is the main sorting condition.

Lesson 5: Introduction to the LIMIT Clause

Imagine a supermarket has 5,000 products, but the manager only wants to display the first 10 products in a report.

Displaying all 5,000 products may not be necessary.

SQL provides the LIMIT clause to control how many records are returned by a query.

Basic syntax:

SELECT column_name
FROM table_name
LIMIT number;

Example 1: Display only five students.

SELECT * FROM Students
LIMIT 5;

This query returns a maximum of five records from the Students table.

Example 2: Display only three products.

SELECT * FROM Products
LIMIT 3;

This query returns a maximum of three product records.

Example 3: Display only ten customers.

SELECT * FROM Customers
LIMIT 10;

This query returns a maximum of ten customer records.

Remember: LIMIT controls the number of records returned. If you want the records to appear in a particular order, combine LIMIT with ORDER BY.

Lesson 6: Retrieving Specific Numbers of Records

You can combine SELECT, ORDER BY, and LIMIT to retrieve a particular number of records in a specific order.

This is very useful when creating reports and identifying important information.

Example 1: Find the Five Highest Examination Scores

Imagine a school wants to identify its five best-performing students.

SELECT * FROM Students
ORDER BY Score DESC
LIMIT 5;

The database first arranges students from the highest score to the lowest score and then displays only the first five records.

Example 2: Find the Three Cheapest Products

A supermarket manager wants to see the three cheapest products.

SELECT * FROM Products
ORDER BY Price ASC
LIMIT 3;

This displays the three products with the lowest prices.

Example 3: Find the Five Most Expensive Products

SELECT * FROM Products
ORDER BY Price DESC
LIMIT 5;

This displays the five products with the highest prices.

Example 4: Display the Ten Newest Customers

Imagine an online business wants to see its ten newest customers.

SELECT * FROM Customers
ORDER BY RegistrationDate DESC
LIMIT 10;

This works when RegistrationDate contains valid registration dates. The newest dates appear first.

Lesson 7: Understanding LIMIT with OFFSET

Sometimes, you do not want to display the first few records. You may want to skip some records and display the next set.

SQL provides the OFFSET keyword to help you skip a specified number of records.

For example, imagine your database contains 20 students. You want to skip the first five students and display the next five.

SELECT * FROM Students
LIMIT 5 OFFSET 5;

This means:

  • LIMIT 5 means display five records.
  • OFFSET 5 means skip the first five records.

This technique is useful when displaying information across different pages on a website.

Another example:

SELECT * FROM Students
LIMIT 10 OFFSET 10;

This skips the first ten records and returns the next ten.

Important: When using OFFSET, it is usually best to include ORDER BY so that records appear in a predictable order.

Practical Activity: School Examination Database

You are working as a junior database assistant at Bright Future Academy in Ibadan. Your teacher has asked you to arrange students' examination results.

Study the following Students table:

StudentID Name Class Score
101DanielJSS 275
102MaryJSS 190
103PeterJSS 365
104AishaJSS 285
105JohnJSS 170
106GraceJSS 395

Task 1: Arrange Students by Their Names Alphabetically

SELECT * FROM Students
ORDER BY Name ASC;

Task 2: Arrange Students by Their Scores from Highest to Lowest

SELECT * FROM Students
ORDER BY Score DESC;

Task 3: Display Only the First Three Student Records

SELECT * FROM Students
LIMIT 3;

Task 4: Display the Three Students with the Highest Scores

SELECT * FROM Students
ORDER BY Score DESC
LIMIT 3;

Task 5: Arrange Students by Class and Then by Name

SELECT * FROM Students
ORDER BY Class ASC, Name ASC;

Practical Challenge: Supermarket Database

Imagine you are helping a supermarket in Ibadan organise its product records.

The supermarket has a table called Products with the following columns:

  • ProductID
  • ProductName
  • Price
  • Category
  • Quantity

Write SQL queries to perform these tasks:

  1. Display all products arranged alphabetically by ProductName.
  2. Arrange products from the most expensive to the cheapest.
  3. Display products from the cheapest to the most expensive.
  4. Display only the first five products.
  5. Display the five most expensive products.
  6. Display the three products with the lowest quantities.
  7. Arrange products by Category and then by Price from highest to lowest.
  8. Skip the first five products and display the next five products.

Important SQL Tips

  • Use ASC when arranging information from smallest to largest or A to Z.
  • Use DESC when arranging information from largest to smallest or Z to A.
  • Use ORDER BY to arrange records.
  • Use LIMIT to control the number of records returned.
  • Use OFFSET to skip records before displaying the next set.
  • Combine ORDER BY and LIMIT when finding the highest or lowest records.

Module Summary

In this module, you have learned:

  • ORDER BY arranges records according to selected columns.
  • ASC sorts records in ascending order.
  • DESC sorts records in descending order.
  • You can sort records using multiple columns.
  • LIMIT controls the number of records returned.
  • OFFSET skips a specified number of records.
  • ORDER BY and LIMIT can work together to identify the highest or lowest values.
  • Sorting query results does not permanently change the original database records.

Module Assessment

Answer the following questions to test your understanding.

  1. What is the purpose of the ORDER BY clause?
  2. What does ASC mean in SQL?
  3. What does DESC mean in SQL?
  4. Which SQL keyword is used to limit the number of records returned?
  5. What is the difference between ascending and descending order?
  6. Write a query to arrange employees alphabetically by name.
  7. Write a query to arrange products from the highest price to the lowest price.
  8. Write a query to display only the first five records from a Customers table.
  9. What is the purpose of OFFSET?
  10. Write a query to find the three students with the highest examination scores.

Congratulations!

You have successfully completed Module 5 of Basic Queries! You now know how to organise database information, arrange records, and control how many results are displayed.

These skills are useful when preparing reports, analysing examination results, managing online stores, and working with large databases.

Coming Up Next

Module 6: Basic SQL Functions

In the next module, you will learn how SQL can perform simple calculations. You will discover how to count records, calculate totals, find averages, and identify the highest and lowest values in a database.

CRMNuggets โ€“ Learn. Practice. Get Certified.

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’