Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Introduction to SQL for Data Analysis ยท Lesson 6 of 9

Module Five

๐Ÿ“– 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 Organising Query Results โ€“ Introduction to SQL for Data Analysis. This module teaches learners how to arrange database records alphabetically, sort prices, organise student records and limit the number of results returned by SQL.

Module 5: Sorting and Organising Query Results

Welcome to Module 5 of Introduction to SQL for Data Analysis. In the previous module, you learned how to filter database records using the WHERE clause.

Imagine you are working in a supermarket in Ibadan. The manager gives you a list of 500 products and asks you to arrange them from the cheapest to the most expensive.

You don't need to arrange the products manually. SQL can do it for you! In this module, you will learn how to sort and organise information stored in a database.


1. What Is Data Sorting?

Data sorting means arranging information in a particular order so that it becomes easier to read, understand and analyse.

You can sort information in different ways:

  • Arrange students alphabetically by their names.
  • Arrange products from the cheapest to the most expensive.
  • Arrange examination scores from highest to lowest.
  • Arrange employees from the oldest to the youngest.
  • Arrange customers according to their registration dates.

SQL uses the ORDER BY clause to arrange query results.


2. Understanding the ORDER BY Clause

The ORDER BY clause tells SQL which column to use when arranging records.

Basic Syntax

SELECT column_name
FROM table_name
ORDER BY column_name;

Let's use a school database to understand how it works.

Example: Students Table

student_id student_name age score
1Samuel1375
2Mary1290
3Peter1465
4Esther1385
5David1270

To arrange students alphabetically by their names, use:

SELECT *
FROM Students
ORDER BY student_name;

SQL will arrange the names alphabetically, starting with David, Esther, Mary, Peter and Samuel.

When you do not specify a sorting direction, SQL uses ascending order by default.


3. Understanding ASC โ€“ Ascending Order

ASC means ascending order. It arranges values from the smallest to the largest or alphabetically from A to Z.

Examples include:

  • Numbers: 1, 2, 3, 4, 5.
  • Names: Ada, David, Esther, Mary, Samuel.
  • Prices: โ‚ฆ500, โ‚ฆ1,000, โ‚ฆ2,000, โ‚ฆ5,000.

Example 1: Arrange Students by Age

SELECT *
FROM Students
ORDER BY age ASC;

The youngest students will appear first, followed by older students.

Example 2: Arrange Products by Price

SELECT *
FROM Products
ORDER BY price ASC;

This query displays the cheapest products first.

Example 3: Arrange Examination Scores

SELECT student_name, score
FROM Students
ORDER BY score ASC;

This displays students from the lowest examination score to the highest.


4. Understanding DESC โ€“ Descending Order

DESC means descending order. It arranges values from the largest to the smallest or alphabetically from Z to A.

Examples include:

  • Numbers: 100, 90, 80, 70, 60.
  • Names: Samuel, Peter, Mary, Esther, David.
  • Prices: โ‚ฆ10,000, โ‚ฆ5,000, โ‚ฆ2,000, โ‚ฆ1,000.

Example 1: Highest Scores First

SELECT *
FROM Students
ORDER BY score DESC;

This query displays students with the highest scores first.

Example 2: Most Expensive Products First

SELECT *
FROM Products
ORDER BY price DESC;

This helps a supermarket manager identify the most expensive products.

Example 3: Youngest Students Last

SELECT *
FROM Students
ORDER BY age DESC;

This displays older students before younger students.


5. Sorting Using Multiple Columns

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

For example, a school may want to arrange students by class and then alphabetically by their names.

SELECT *
FROM Students
ORDER BY class ASC, student_name ASC;

SQL first arranges students according to their classes. Within each class, it arranges their names alphabetically.

Another Example: Scores and Names

Imagine two students have the same examination score. You can sort by score first and then by name.

SELECT student_name, score
FROM Students
ORDER BY score DESC, student_name ASC;

This arranges students by their highest scores first. If two students have the same score, their names are arranged alphabetically.


6. Using WHERE and ORDER BY Together

You can combine the WHERE clause and the ORDER BY clause in one SQL query.

The WHERE clause filters the records, while ORDER BY arranges the records that remain.

Example 1

Find students who scored more than 70 and arrange them from the highest score to the lowest.

SELECT *
FROM Students
WHERE score > 70
ORDER BY score DESC;

Example 2

Find supermarket products that cost less than โ‚ฆ5,000 and arrange them from the cheapest to the most expensive.

SELECT *
FROM Products
WHERE price < 5000
ORDER BY price ASC;

Important: In a basic SQL query, write WHERE before ORDER BY.


7. Limiting Results Using LIMIT

Imagine a supermarket has 10,000 products, but the manager only wants to see the first five most expensive products.

You can use the LIMIT clause to control how many records SQL returns.

Basic Syntax

SELECT column_name
FROM table_name
LIMIT number;

Example 1: Display Only Five Students

SELECT *
FROM Students
LIMIT 5;

This query displays a maximum of five records.

Example 2: Find the Three Most Expensive Products

SELECT *
FROM Products
ORDER BY price DESC
LIMIT 3;

SQL first sorts products from the highest price to the lowest and then displays only three records.

Example 3: Find the Five Highest Examination Scores

SELECT student_name, score
FROM Students
ORDER BY score DESC
LIMIT 5;

This is useful when identifying the top five students in a class.


8. Using LIMIT with OFFSET

Sometimes, you want to skip a number of records before displaying the next set of results.

SQL uses OFFSET for this purpose.

Basic Syntax

SELECT column_name
FROM table_name
LIMIT number OFFSET number;

Example

SELECT *
FROM Students
LIMIT 5 OFFSET 5;

This skips the first five records and returns the next five records, if they are available.

OFFSET is useful when building websites that display database records across different pages.

Real-Life Example: Website Pagination

  • Page 1 displays records 1โ€“10.
  • Page 2 displays records 11โ€“20.
  • Page 3 displays records 21โ€“30.

For example, the second page can use:

SELECT *
FROM Students
LIMIT 10 OFFSET 10;

This technique is called pagination. It helps websites display large amounts of information in smaller sections.


9. Using DISTINCT to Remove Duplicate Values

Sometimes, a database contains repeated values. The DISTINCT keyword helps you display only unique values in your query results.

Imagine a school has students from different states, and several students come from the same state.

To display each state only once, write:

SELECT DISTINCT state
FROM Students;

If 20 students come from Oyo State, SQL will display Oyo only once in this result.

Another Example

Find the different product categories available in a supermarket.

SELECT DISTINCT category
FROM Products;

This can display categories such as Food, Drinks, Electronics and Clothing without repeating them.

Remember: DISTINCT removes duplicate combinations of the selected columns, not necessarily duplicate records from the original table.


10. Combining Sorting, Filtering and Limiting

One of the most useful things about SQL is that you can combine different commands to answer more detailed questions.

Example 1: Top Three Students

Find the three students with the highest examination scores.

SELECT student_name, score
FROM Students
ORDER BY score DESC
LIMIT 3;

Example 2: Affordable Products

Find products that cost less than โ‚ฆ10,000, arrange them from cheapest to most expensive, and display only five products.

SELECT *
FROM Products
WHERE price < 10000
ORDER BY price ASC
LIMIT 5;

Example 3: Best Performing Students in JSS 2

Find the five highest-scoring students in JSS 2.

SELECT student_name, score
FROM Students
WHERE class = 'JSS 2'
ORDER BY score DESC
LIMIT 5;

11. Common SQL Sorting Mistakes

Incorrect Approach Correct Approach
ORDER price BY ORDER BY price
ORDER BY price HIGH ORDER BY price DESC
ORDER BY student_name A-Z ORDER BY student_name ASC
LIMIT five LIMIT 5
ORDER BY before WHERE WHERE before ORDER BY

Remember:

  • ASC means ascending order.
  • DESC means descending order.
  • ORDER BY sorts query results.
  • LIMIT controls the number of records returned.
  • OFFSET skips a specified number of records.
  • DISTINCT returns unique values or combinations.

12. Practical Exercise

You have been invited to help a school in Ibadan organise its student database.

The Students table contains these columns:

  • student_id
  • student_name
  • age
  • class
  • state
  • score

Write SQL queries to complete the following tasks:

  1. Display all students alphabetically by name.
  2. Arrange students from the youngest to the oldest.
  3. Arrange examination scores from highest to lowest.
  4. Display only the first five students.
  5. Find the three students with the highest scores.
  6. Find students who scored above 60 and arrange them by score.
  7. Display all the different states represented in the school.
  8. Skip the first five students and display the next five.

Sample Solutions

-- 1. Arrange students alphabetically
SELECT *
FROM Students
ORDER BY student_name ASC;

-- 2. Youngest students first
SELECT *
FROM Students
ORDER BY age ASC;

-- 3. Highest scores first
SELECT *
FROM Students
ORDER BY score DESC;

-- 4. Display five students
SELECT *
FROM Students
LIMIT 5;

-- 5. Find the top three students
SELECT student_name, score
FROM Students
ORDER BY score DESC
LIMIT 3;

-- 6. Students who scored above 60
SELECT *
FROM Students
WHERE score > 60
ORDER BY score DESC;

-- 7. Display different states
SELECT DISTINCT state
FROM Students;

-- 8. Skip the first five records
SELECT *
FROM Students
LIMIT 5 OFFSET 5;

13. Knowledge Check

Question 1: Which SQL clause is used to sort records?

  1. WHERE
  2. ORDER BY
  3. GROUP BY
  4. CREATE

Question 2: What does ASC mean?

  1. Ascending order
  2. Descending order
  3. Automatic sorting
  4. Advanced SQL command

Question 3: Which keyword sorts records from highest to lowest?

  1. ASC
  2. DESC
  3. LIMIT
  4. DISTINCT

Question 4: Which SQL clause limits the number of records returned?

  1. WHERE
  2. ORDER
  3. LIMIT
  4. SELECT

Question 5: Which keyword helps remove duplicate values from query results?

  1. UNIQUE
  2. REMOVE
  3. DISTINCT
  4. DELETE

Question 6: What does OFFSET do?

  1. Deletes records
  2. Skips a specified number of records
  3. Changes a table name
  4. Creates a database

Question 7: Which query finds the three most expensive products?

  1. SELECT * FROM Products LIMIT 3;
  2. SELECT * FROM Products ORDER BY price DESC LIMIT 3;
  3. SELECT * FROM Products ORDER BY price ASC;
  4. SELECT * FROM Products WHERE price = 3;

Question 8: Which clause should appear before ORDER BY in a basic filtered query?

  1. LIMIT
  2. WHERE
  3. DISTINCT
  4. OFFSET

Question 9: What happens when you write ORDER BY student_name ASC?

  1. Names are arranged from Z to A
  2. Names are arranged from A to Z
  3. Names are deleted
  4. Names are changed

Question 10: Which query displays different product categories without repeating them?

  1. SELECT category FROM Products;
  2. SELECT DISTINCT category FROM Products;
  3. DELETE category FROM Products;
  4. ORDER BY category FROM Products;

14. Module Summary

In this module, you learned how to organise database records and control the results returned by SQL queries.

  • ORDER BY arranges records.
  • ASC sorts from smallest to largest or A to Z.
  • DESC sorts from largest to smallest or Z to A.
  • You can sort using multiple columns.
  • WHERE filters records before sorting.
  • LIMIT controls how many records are displayed.
  • OFFSET skips records.
  • DISTINCT displays unique values or combinations.

You can now organise thousands of database records and quickly identify the information you need.


Coming Up in Module 6

SQL Functions and Data Aggregation

In the next module, you will learn how SQL can calculate totals, averages, minimum values, maximum values and the number of records in a database.

You will explore these important SQL functions:

  • COUNT() โ€“ Counts records.
  • SUM() โ€“ Adds numerical values.
  • AVG() โ€“ Calculates averages.
  • MIN() โ€“ Finds the smallest value.
  • MAX() โ€“ Finds the largest value.
  • GROUP BY โ€“ Groups records with matching values.

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.
โ†’