UNIHIVE

Study Hub UNIPORT CSC 282

CSC 282 · Database Programming

SQL: querying data with SELECT

Choosing rows and columns, sorting, patterns, aggregate functions, GROUP BY with HAVING, joins and subqueries.

Our notes

2 min read

Basic form

    SELECT column_list
    FROM table
    WHERE condition
    GROUP BY columns
    HAVING group_condition
    ORDER BY columns;

The clauses run in the order FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY.

Choosing rows and columns

    SELECT surname, level FROM student
    WHERE dept_code = 'CSC' AND level >= 200
    ORDER BY surname ASC;

Operators: =, <> (not equal), <, >, BETWEEN 40 AND 59, IN ('CSC', 'PHY'), LIKE 'Ok%' (% any characters, _ one character), IS NULL.

Aggregates

COUNT, SUM, AVG, MIN, MAX.

    SELECT course_code, COUNT(*) AS students, AVG(score) AS mean_score
    FROM result
    WHERE session = '2025/2026'
    GROUP BY course_code
    HAVING COUNT(*) >= 2
    ORDER BY mean_score DESC;

WHERE filters rows before grouping; HAVING filters groups after.

Worked example

Result rows for 2025/2026: (A, CSC 282, 70), (B, CSC 282, 55), (C, CSC 282, 64), (A, STA 260, 48), (B, STA 260, 72), (A, MTH 210, 80).
The query above returns:

course_codestudentsmean_score
CSC 282363.0
STA 260260.0

MTH 210 has one student and is removed by HAVING. Check: (70 + 55 + 64)/3 = 63; (48 + 72)/2 = 60.

Joins

Combine tables on matching keys.

    SELECT s.surname, r.course_code, r.score
    FROM student s
    JOIN result r ON r.matric_no = s.matric_no
    WHERE r.score < 40;

  • INNER JOIN: only rows that match in both tables.
  • LEFT JOIN: every row of the left table, with NULLs where the right has no match: "all students and their results, including students with none".
  • Joining three tables: chain the joins (student → result → course to show course titles).

Subqueries

    SELECT surname FROM student
    WHERE matric_no IN (SELECT matric_no FROM result WHERE score < 40);

    SELECT course_code, score FROM result
    WHERE score > (SELECT AVG(score) FROM result);

Exams usually ask

  • Write a SELECT with WHERE, ORDER BY, GROUP BY and HAVING for a scenario.
  • Write an inner and a left join and explain the difference.
  • Predict the output of a query on a small table.

Common mistake

Selecting a column that is neither grouped nor aggregated (SELECT course_code, surname … GROUP BY course_code). Every selected column must be in GROUP BY or inside an aggregate.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All CSC 282 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.