22 min read Declarative Querying & CRUD Lesson 6 of 15
Part 2 — Querying, Relationships & Schema Design

SQL: Talking to the Database

Declarative Querying, CRUD Operations, Aggregations & Query Execution Order

In previous lessons, we explored database architecture, tables, relationships, normalization, and integrity constraints. Until now, we observed databases from the outside. Now, we begin speaking directly to the engine. How do we instruct the system: "Show me all active users", "Deduct 20 units from stock", or "Record a new purchase order"? The universal lingua franca of relational data systems is SQL (Structured Query Language).

What You Will Master in This Lesson:

The craft of declarative data manipulation and execution mechanics:

  • Declarative Paradigm: "What result I want" vs "How to do it"
  • CRUD Mastery: Safe execution of SELECT, INSERT, UPDATE, DELETE
  • Filtering & Slicing: WHERE, AND/OR, ORDER BY, LIMIT, and OFFSET
  • Aggregates & Groups: COUNT, SUM, AVG, GROUP BY, and HAVING
  • Execution Pipeline: The 8-stage logical order of SQL execution
  • Security & ORMs: Preventing SQL Injection via Parameterized Queries

1 Is SQL a Programming Language?

There is a fundamental paradigm distinction between SQL and general-purpose languages. Languages like Python, JavaScript, and C++ are Imperative: you command the computer step-by-step:

Initialize loop index → evaluate if condition → mutate variable → break when target reached

In contrast, SQL is Declarative. You never describe how to traverse disk pages, when to search B+ Trees, or how to allocate memory buffers. You simply declare the mathematical specification of the desired result:

SELECT name FROM users WHERE status = 'active';

You declare: "Provide the names of all users whose status is active." The database cost-based optimizer autonomously determines whether to perform an index scan, sequential scan, hash join, or parallel worker execution based on data statistics!

The Triad: Database vs DBMS vs SQL

Novice developers frequently conflate these terms. Their distinctions are crystal clear:

1. Database (The Data)

The physical files, tables, and bytes stored durably on persistent disk.

2. DBMS (The Software)

The engine server managing access (e.g., PostgreSQL, MySQL, SQLite).

3. SQL (The Language)

The standard instruction protocol clients use to issue commands to the DBMS.

Application  →  SQL Query  →  DBMS (Engine)  →  Database (Disk Storage)

2 Our Example Dataset

To anchor our SQL queries throughout this lesson, we will interact with a concise e-commerce schema consisting of two tables:

users 3 rows
id name email status
1Salimsalim@example.comactive
2Rahimrahim@example.comactive
3Karimkarim@example.cominactive
products 3 rows
id name price stock
101Laptop80,00010
102Mouse1,20050
103Keyboard2,50020

3 SELECT: Reading Data & Column Projection

The most common SQL statement is SELECT, used to retrieve rows from one or more relations:

1. Retrieving all columns (* Asterisk Wildcard): SELECT * FROM users;
2. Explicit Column Projection: SELECT name, email FROM users;
Production Guideline: Avoid SELECT * in Application Services!

If a table has 40 columns (including long JSON blobs or text descriptions), SELECT * forces the engine to read massive disk pages into buffer memory and transmit unneeded bytes across the network. Explicitly selecting only required columns dramatically reduces disk I/O, network bandwidth, and memory consumption.

4 WHERE: Filtering with Boolean Predicates

To narrow down query results to specific tuples that satisfy criteria, append a WHERE clause:

Filter active users: SELECT name, email FROM users WHERE status = 'active';
Comparison Operators:
  • = : Equal
  • != or <> : Not Equal
  • >, < : Greater, Less than
  • >=, <= : Greater/Equal, Less/Equal
Logical Combinations:
  • AND : All predicates must evaluate to True
  • OR : At least one predicate must be True
  • NOT : Inverts predicate boolean evaluation
  • IN ('active', 'pending') : Set membership test
Compound Predicate Example (Products under 5,000 with stock over 10): SELECT * FROM products WHERE price < 5000 AND stock > 10;

5 ORDER BY, LIMIT, OFFSET & DISTINCT

Relational tables are unordered mathematical sets. To impose deterministic ordering and windowing on results:

ORDER BY (Sorting)

Sort low-to-high (ASC) or high-to-low (DESC):

SELECT * FROM products ORDER BY price DESC;
LIMIT & OFFSET (Pagination)

Skip the first 20 records and return the next 10:

SELECT * FROM products LIMIT 10 OFFSET 20;
DISTINCT (Eliminating Duplicates)

Extract unique city values across hundreds of user records:

SELECT DISTINCT city FROM users;

6 CRUD: Data Mutations & The Missing WHERE Catastrophe

The vast majority of web applications operate on four fundamental data mutations, known by the acronym CRUD:

C - Create
INSERT INTO
R - Read
SELECT
U - Update
UPDATE ... SET
D - Delete
DELETE FROM
Inserting new rows (INSERT): INSERT INTO users (name, email, status) VALUES ('Hasan', 'hasan@example.com', 'active');
Mutating existing rows (UPDATE): UPDATE users SET status = 'inactive' WHERE id = 1;
Purging specific rows (DELETE): DELETE FROM users WHERE id = 3;

Disaster Warning: What Happens When You Omit the WHERE Clause?

This is the single most infamous operational pitfall in software engineering. When you issue an UPDATE or DELETE statement without a WHERE clause:

UPDATE users SET status = 'inactive';

Result: Every single customer account in your database is deactivated!

DELETE FROM users;

Result: Every record in the table is permanently erased!

Senior engineers safeguard production databases by executing updates inside explicit transaction blocks (BEGIN; ... ROLLBACK;) or pre-checking row counts via SELECT COUNT(*) before applying mutations.

7 Aggregate Functions, GROUP BY & HAVING

Beyond returning individual rows, SQL engines perform fast mathematical computations over millions of tuples:

COUNT(*) Total rows
SUM(stock) Total summation
AVG(price) Arithmetic mean
MIN(price) Minimum value
MAX(price) Maximum value
GROUP BY: Categorical Bucketing

Calculate user counts segmented by status:

SELECT status, COUNT(*) FROM users GROUP BY status;
HAVING: Group-Level Predicate Filtering

Retain only status groups that contain more than 1 member:

SELECT status, COUNT(*) FROM users GROUP BY status HAVING COUNT(*) > 1;
What is the Difference Between WHERE and HAVING?

WHERE filters individual tuples before groups are assembled. In contrast, HAVING filters aggregated groups after aggregation has occurred. Consequently, aggregate functions like COUNT(*) or AVG() are illegal inside the WHERE clause!

8 Interactive Lab: Live SQL Engine & Execution Stepper

Hands-on Lab

Execute interactive queries against our in-memory SQL engine, inspect the 8-stage execution order, and observe SQL Injection defenses:

Select Preset SQL Query:
Supports SELECT, INSERT, UPDATE, DELETE, GROUP BY
Query Execution Output: Ready

9 Three-Valued Logic, Dialects & The ORM Era

What is NULL?

In SQL, NULL represents unknown or missing information. It is not zero (0) and not an empty string ("").

Invalid: WHERE email = NULL
Valid: WHERE email IS NULL or IS NOT NULL
Why SQL Matters in the Age of ORMs?

Modern backends rely on Prisma, Django ORM, Hibernate, or Laravel Eloquent. However, ORMs compile directly down to SQL.

Diagnosing devastating N+1 query cascades, optimizing missing indexes, and tuning high-throughput services require deep mastery of raw SQL.

10 Knowledge Check: Interactive Quiz

3 Multiple Choice Questions
Question 1

Why is SQL classified as a "Declarative" language?

Question 2

Which clause is logically evaluated before the SELECT clause during SQL execution?

Question 3

What catastrophic consequence occurs if you execute UPDATE users SET status = 'inactive';?

Key Architectural Takeaways

  • Declarative Paradigm: We declare desired output states; the database execution optimizer figures out the optimal execution path.
  • CRUD Core: INSERT (Create), SELECT (Read), UPDATE (Update), and DELETE (Delete).
  • Filtering & Slicing: WHERE filters individual tuples, ORDER BY sorts them, and LIMIT/OFFSET paginates windows.
  • Aggregates & Groups: COUNT, SUM, AVG combined with GROUP BY and group filtering via HAVING.
  • Execution Pipeline: FROM → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT.