SQL Ordering & Aggregate Functions (ORDER BY, SUM, COUNT)

SELECT chooses fields, FROM chooses a table and WHERE filters records. ORDER BY sorts the resulting records. ASC sorts ascending; DESC sorts descending. Do not confuse sorting with filtering.

SELECT Name, Score
FROM Results
WHERE Score >= 50
ORDER BY Score DESC;

Worked aggregates

Suppose three selected records have scores 4,7,9. SUM(Score) returns 20. COUNT(*) returns 3. These answer different questions: how much in total, and how many records. A WHERE condition can restrict which records contribute.

SELECT SUM(Score)
FROM Results
WHERE Team = 'Blue';

For Blue scores 4 and 9 and a Red score 7, the filtered sum is 13. Do not add the Red score merely because it is in the same table.

Independent practice

Write a query counting all records, then change it to count only scores at least 50. Explain the difference between returning selected rows and returning one aggregate. GROUP BY and multi-table queries are optional extension and are not needed here.

AI Socratic Tutor

All-Access
Sign in or create an account. AI Tutor is an All-Access benefit.
Sign Up

Need guidance? Ask a question or use the hint below.

AI Socratic Tutor is an All-Access Benefit

Unlock step-by-step Socratic hints, algorithm trace table walkthroughs, and error diagnostics for every Cambridge exercise.

You're chatting with an AI tutor, not a person. AI can make mistakes, so double-check its answers.

Exam-Style Check: Behavior of ORDER BY DESC in SQL

• Multiple Choice
+25 XP
Question

A school administrator runs the following SQL query on the Students table:

SELECT StudentName, ExamScore
FROM Students
ORDER BY ExamScore DESC;

Which row will appear as the first result in the returned table?

All-Access Required

Interactive exercises for Module 2 and beyond require an active plan.