Practise data constraints, deliberate queries, grouping, and parameterised input in a disposable database.
Define the Data Rules
CREATE TABLE resources (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
url TEXT NOT NULL UNIQUE,
topic TEXT NOT NULL
);
A primary key identifies a row; NOT NULL prevents missing values; UNIQUE prevents duplicate URL values according to the database's comparison rules. This example supplies IDs explicitly when inserting data. Empty strings still satisfy NOT NULL, so application rules may need additional validation.
Select What the Interface Needs
SELECT id, title, url
FROM resources
WHERE topic = 'web'
ORDER BY title, id;
Select explicit columns so the caller knows which fields it receives. ORDER BY makes the intended ordering visible, and the ID acts as a tie-breaker for identical titles. Without ordering, do not depend on rows appearing in insertion order.
Count Rows by Category
SELECT topic, COUNT(*) AS resource_count
FROM resources
GROUP BY topic
ORDER BY resource_count DESC, topic;
Grouping turns many rows into one result per topic. COUNT(*) counts rows, while COUNT(column) excludes null values in that column. Check a tiny hand-counted dataset before trusting an aggregation used in a dashboard or progress report.
Treat Missing Values Explicitly
SELECT id, title
FROM resources
WHERE title IS NULL;
Use IS NULL to test for SQL null rather than equality with NULL. This query should return no rows under the example table's NOT NULL constraint; it illustrates how to inspect a less constrained dataset. A missing value and an empty string represent different states.
Pass Input as a Parameter
-- PostgreSQL query template for a driver that supports $1:
SELECT id, title, url
FROM resources
WHERE topic = $1
ORDER BY title, id;
Supply the parameter value through the database driver's separate parameter argument. Do not paste user input into the SQL string. Placeholder syntax varies by database and driver; this template is not a complete standalone SQL-console command. Consult the driver's documented parameter API.