Friday, November 27, 2026

How PostgreSQL Triggers Track Changes: OLD, NEW and a Practical Example

An application runs one UPDATE. The status changes, and PostgreSQL records the old and new values in a second table—without a separate audit INSERT from the application. How does the database know what to do?

In this hands-on example, you will build two PostgreSQL triggers, see the actual results, and find out what happens when a transaction is rolled back. The example uses fictional data in temporary tables and does not change TrainingHub.

What is a trigger?

A trigger connects an event on a database object to a function that PostgreSQL runs automatically. Our event is an UPDATE on a table. The trigger definition says when and for which rows the function runs; the trigger function contains what to do. Creating the function or trigger does not itself update a row.

We will use a BEFORE UPDATE trigger to normalize the proposed status and an AFTER UPDATE trigger to record a change. Both are FOR EACH ROW: PostgreSQL considers each affected row separately. The WHEN condition on the second trigger restricts it to rows whose status actually differs. See the PostgreSQL trigger overview.

Before you begin

You need PostgreSQL and a SQL client such as pgAdmin's Query Tool or psql, permission to create temporary tables and functions, and basic familiarity with SELECT and UPDATE. This example was executed with psql against PostgreSQL 17.8; pgAdmin display and results can differ. Open one disposable learning session and run the blocks in order on the same connection. Temporary objects disappear when that session ends. The statements write to the temporary tables; they do not change TrainingHub.

In pgAdmin, select a block and use Execute/Run. If your client displays only the last result from multiple statements, run the statements individually to see each result. Starting again? Open a new connection and rerun setup; creating the same objects twice in the same session causes a name conflict.

1. Create the sample tables

CREATE TEMP TABLE demo_enrollments (
    enrollment_id integer PRIMARY KEY,
    status text NOT NULL
);

CREATE TEMP TABLE demo_status_audit (
    enrollment_id integer NOT NULL,
    old_status text NOT NULL,
    new_status text NOT NULL
);

INSERT INTO demo_enrollments VALUES (1, 'active');

demo_enrollments holds one enrollment. demo_status_audit starts empty and will hold the before-and-after values. CREATE TEMP TABLE makes these session-local tables. We deliberately omit timestamps and user identity to keep the example focused.

2. Define a BEFORE trigger function

CREATE FUNCTION pg_temp.normalize_status() RETURNS trigger
LANGUAGE plpgsql AS $function$
BEGIN
    NEW.status := lower(trim(NEW.status));
    RETURN NEW;
END;
$function$;

CREATE FUNCTION gives the routine a name; pg_temp places it in the session's temporary schema. The empty parentheses mean no ordinary function parameters. RETURNS trigger identifies this as a trigger function, and LANGUAGE plpgsql chooses the procedural language. Matching $function$ tags surround the function body; the tag is a delimiter, not a variable.

For this row-level update, NEW represents the proposed new row. trim removes surrounding spaces, lower makes letters lowercase, and := assigns the result to NEW.status. RETURN NEW passes the modified row onward. This return value matters for a row-level BEFORE trigger: returning NULL instead would skip that row's operation. The exact return rules depend on trigger timing and event; see PL/pgSQL trigger functions.

3. Attach the BEFORE trigger

CREATE TRIGGER normalize_enrollment_status
BEFORE UPDATE ON demo_enrollments
FOR EACH ROW
EXECUTE FUNCTION pg_temp.normalize_status();

The trigger is named normalize_enrollment_status; it runs before updates to demo_enrollments, once for each affected row. EXECUTE FUNCTION identifies the trigger function. This example uses a PostgreSQL function returning trigger, not a procedure invoked with CALL.

4. Define and attach an AFTER trigger

CREATE FUNCTION pg_temp.record_status_change() RETURNS trigger
LANGUAGE plpgsql AS $function$
BEGIN
    INSERT INTO pg_temp.demo_status_audit
        (enrollment_id, old_status, new_status)
    VALUES (NEW.enrollment_id, OLD.status, NEW.status);
    RETURN NULL;
END;
$function$;

In this row-level UPDATE, OLD.status is the value before the update and NEW.status is the new value after our BEFORE normalization. The function inserts both into the audit table. PostgreSQL ignores the return value of an AFTER row trigger function, so this example uses RETURN NULL; it does not cancel the update.

CREATE TRIGGER audit_enrollment_status
AFTER UPDATE ON demo_enrollments
FOR EACH ROW
WHEN (OLD.status IS DISTINCT FROM NEW.status)
EXECUTE FUNCTION pg_temp.record_status_change();

AFTER UPDATE associates the function with completed updates. This ordinary AFTER row trigger runs at the end of the statement, still within the transaction. Its WHEN condition allows a log entry only when the old and new values differ. IS DISTINCT FROM also gives a definite comparison for NULL values, though both statuses in our sample tables are NOT NULL. Merely naming a column in UPDATE OF status is not the same as testing whether its value changed. See CREATE TRIGGER.

5. Update and inspect the result

UPDATE demo_enrollments
SET status = '  COMPLETED  '
WHERE enrollment_id = 1;

SELECT * FROM demo_enrollments;
SELECT * FROM demo_status_audit;

In the tested run, the first result is 1 | completed. The audit result is 1 | active | completed. The BEFORE function trimmed and lowercased the proposed value; then the AFTER function recorded the transition. The SQL statement did not explicitly insert into the audit table.

What if we write the same status again?

UPDATE demo_enrollments
SET status = 'completed'
WHERE enrollment_id = 1;

SELECT count(*) AS audit_rows_after_same_status
FROM demo_status_audit;

The tested result is 1. The UPDATE still affects the matching row, but the AFTER trigger's condition is false for the unchanged normalized status, so no additional audit row is inserted.

6. What does ROLLBACK do?

Run setup and the previous blocks first, then execute these statements on the same connection. Use normal autocommit for the earlier blocks so that the sample objects and first change are established before the explicit transaction.

BEGIN;
UPDATE demo_enrollments SET status = 'cancelled' WHERE enrollment_id = 1;
SELECT status FROM demo_enrollments WHERE enrollment_id = 1;
SELECT count(*) AS audit_rows_before_rollback FROM demo_status_audit;
ROLLBACK;

SELECT * FROM demo_enrollments;
SELECT * FROM demo_status_audit;

Before ROLLBACK, the status is cancelled and the audit table has 2 rows in this session. After rollback, the status is completed and only 1 | active | completed remains in the audit table. The trigger and the statement run in the same transaction, so the rollback reverses both changes from this transaction. This also means a trigger error can cause the triggering statement to fail. See the PostgreSQL documentation on trigger behavior.

BEFORE, AFTER and scope: what to remember

  • BEFORE row: can inspect or modify NEW for an INSERT or UPDATE; the appropriate returned row controls what happens next.
  • AFTER row: can react to the completed operation. This example records a status transition; it does not change the stored row by returning a different value.
  • ROW versus STATEMENT: a row trigger is considered for each affected row; an applicable statement trigger is considered once per statement, including when zero rows are affected. WHEN conditions can restrict both.
  • OLD and NEW: for an UPDATE row trigger both are available; their availability differs for INSERT, DELETE and statement triggers.

This small temporary audit table is a teaching example, not a complete security audit. It does not identify a person, prevent authorized changes to audit records, retain history after the session ends, or capture all database operations. Real systems need deliberate permissions, retention, monitoring, performance testing and a trustworthy identity strategy. Triggers add work and can hide side effects, so document them and measure behavior in your own workload.

Try it yourself

After setup in a fresh session, change the first status to ' ACTIVE '. Predict the normalized value and number of audit rows, then run the update and query both tables. Why does the condition avoid a new record? Next change it to 'completed' and check again.

For more hands-on SQL and PostgreSQL, explore Practical SQL with PostgreSQL: From Queries to Real Projects. This is the instructor's referral link. The example in this article is free and runs independently of the course.

Thursday, November 26, 2026

Why Does SQL BETWEEN Miss Orders on the Last Day?

Your report asks for orders from November 29 through November 30. The query runs without an error, but an order from November 30 at 13:45 is missing. Why?

In this tutorial we reproduce the boundary problem in PostgreSQL, inspect the exact result and build a date range that includes the entire last calendar day. The examples use fictional data and self-contained SELECT statements; no table is created or changed. Run each complete block in pgAdmin's Query Tool or another PostgreSQL client. The recorded execution used PostgreSQL 18.6 with psql.

Five orders around the boundary

We want orders on November 29 and November 30, including both full calendar days. The timestamps below are explicitly timestamp without time zone; for now, treat them as local date-and-time values with no time-zone conversion.

order_idplaced_atInclude?
12026-11-29 23:59:59yes
22026-11-30 00:00:00yes
32026-11-30 13:45:00yes
42026-11-30 23:59:59.999999yes
52026-12-01 00:00:00no

The query that misses part of the day

Here are explicit timestamp bounds, each at midnight:

WITH orders(order_id, placed_at) AS (
    VALUES (1, TIMESTAMP '2026-11-29 23:59:59'),
           (2, TIMESTAMP '2026-11-30 00:00:00'),
           (3, TIMESTAMP '2026-11-30 13:45:00'),
           (4, TIMESTAMP '2026-11-30 23:59:59.999999'),
           (5, TIMESTAMP '2026-12-01 00:00:00')
)
SELECT order_id, placed_at
FROM orders
WHERE placed_at BETWEEN TIMESTAMP '2026-11-29 00:00:00'
                    AND TIMESTAMP '2026-11-30 00:00:00'
ORDER BY order_id;

The result contains only orders 1 and 2. BETWEEN includes both endpoints: order 2 is exactly equal to the upper boundary and is included. Order 3 is later than 2026-11-30 00:00:00, so it is excluded along with order 4. PostgreSQL is applying the specified range correctly; it has not interpreted the upper boundary as the end of November 30. See PostgreSQL's comparison predicates.

An equivalent condition here is placed_at >= TIMESTAMP '2026-11-29 00:00:00' AND placed_at <= TIMESTAMP '2026-11-30 00:00:00'. The inclusive upper comparison is the key detail.

Include the whole final day

Use the start of the first day, inclusive, and the start of the following day, exclusive:

WITH orders(order_id, placed_at) AS (
    VALUES (1, TIMESTAMP '2026-11-29 23:59:59'),
           (2, TIMESTAMP '2026-11-30 00:00:00'),
           (3, TIMESTAMP '2026-11-30 13:45:00'),
           (4, TIMESTAMP '2026-11-30 23:59:59.999999'),
           (5, TIMESTAMP '2026-12-01 00:00:00')
)
SELECT order_id, placed_at
FROM orders
WHERE placed_at >= TIMESTAMP '2026-11-29 00:00:00'
  AND placed_at <  TIMESTAMP '2026-12-01 00:00:00'
ORDER BY order_id;

This half-open interval returns orders 1, 2, 3 and 4. It includes midnight at the start of November 30 and the last sample before December 1, while order 5, exactly at the next midnight, is excluded. For adjacent reporting periods, the same boundary can be the exclusive end of one period and the inclusive start of the next.

Why not BETWEEN and the next midnight?

Try a seemingly small change:

WITH orders(order_id, placed_at) AS (
    VALUES (1, TIMESTAMP '2026-11-29 23:59:59'),
           (2, TIMESTAMP '2026-11-30 00:00:00'),
           (3, TIMESTAMP '2026-11-30 13:45:00'),
           (4, TIMESTAMP '2026-11-30 23:59:59.999999'),
           (5, TIMESTAMP '2026-12-01 00:00:00')
)
SELECT order_id, placed_at
FROM orders
WHERE placed_at BETWEEN TIMESTAMP '2026-11-29 00:00:00'
                    AND TIMESTAMP '2026-12-01 00:00:00'
ORDER BY order_id;

This returns all five orders. Because BETWEEN includes the upper endpoint, it also includes order 5 exactly at December 1 midnight. This might be correct for a different business question, but it is outside our two-day calendar report.

Why not hard-code 23:59:59?

23:59:59 excludes order 4, whose time is 23:59:59.999999. Using a final representable fraction also couples the condition to the precision of the data type. The next-day exclusive boundary is clearer and does not require guessing a last fractional instant. PostgreSQL's date/time types describe timestamp precision.

What changes with time zones?

These examples use timestamp without time zone and do not demonstrate UTC conversions. If your actual column is timestamptz and the business rule concerns a local calendar day, determine both local-midnight boundaries in the intended named time zone and convert them appropriately before comparing instants. Daylight-saving transitions mean local days need not always be 24 hours. Avoid depending on the database session's default time zone without an explicit rule. PostgreSQL documents date/time comparisons and time zones. Test the exact rules and boundaries in your own environment.

The example is a correctness demonstration, not a performance benchmark. A range predicate can be useful with suitable indexes, but the chosen execution plan depends on the query, data and settings; use EXPLAIN on a representative workload before drawing performance conclusions.

Try it yourself

Add a sixth order at 2026-11-29 00:00:00 and predict whether each query returns it. Then add one at 2026-12-01 00:00:00.000001. Predict the results again and run the blocks. What happens at each inclusive or exclusive boundary?

For more hands-on SQL and PostgreSQL practice, explore Practical SQL with PostgreSQL: From Queries to Real Projects. This is the instructor's referral link. These examples are free and run independently of the course.

Max Pooling in CNNs: A Step-by-Step Python Example

How can a neural network make a feature map smaller without simply throwing away entire rows and columns? One option is max pooling: take a small window of values, keep its largest value, and repeat across the map.

In this tutorial, you will shrink a 4×4 map to 2×2 by hand and reproduce each step in Python. The numbers are a small, hand-written teaching example—not activations recorded from a trained model. We use a 2×2 window, a stride of 2 and no padding throughout.

Watch the step-by-step max pooling video tutorial or the animated 25-second Short. To see how a filter creates a feature map before this step, watch my CNN filter animation.

What is max pooling?

A feature map is a grid of values produced by a network layer. Max pooling looks at a local window of that grid and returns the largest value in the window. It then moves the window and repeats. Unlike a convolutional filter, a max-pooling window has no weights to learn: it applies the chosen maximum rule.

Window size says how many neighboring values we inspect. Stride says how far we move the window between positions. With a 2×2 window and stride 2, the windows in this example do not overlap. The TensorFlow MaxPool2D documentation describes window, stride and padding options.

Start with a 4×4 feature map

Here is our input. Treat each number as a sample feature-map value:

1  3  |  2  4
5  6  |  1  0
------+------
7  2  |  8  3
4  1  |  6  9

The lines divide the map into four 2×2 windows. Place a window in the upper-left corner. It contains 1, 3, 5, 6, so its maximum is 6. That becomes the upper-left value in the output.

Move the window and build the result

A stride of 2 moves the window two columns to the right. After that, we move two rows down and repeat. Here are all four calculations:

  • Upper left: max(1, 3, 5, 6) = 6
  • Upper right: max(2, 4, 1, 0) = 4
  • Lower left: max(7, 2, 4, 1) = 7
  • Lower right: max(8, 3, 6, 9) = 9

Put each maximum in the corresponding output position:

6  4
7  9

The input contains 16 values; the output contains 4. We reduced both the height and width from 4 to 2. The largest value from each window is retained, but the other values are lost. Knowing the four maxima alone does not let us reconstruct the original 4×4 map.

Calculate max pooling in Python

You need Python and NumPy. If NumPy is not installed in your selected environment, run python -m pip install numpy. Save the code as max_pooling_example.py, then run python max_pooling_example.py. It needs no model weights, image file or GPU.

import numpy as np


def max_pool_2x2_stride2(feature_map):
    """Pool complete 2x2 windows with stride 2 and no padding."""
    feature_map = np.asarray(feature_map)
    if feature_map.ndim != 2 or min(feature_map.shape) < 2:
        raise ValueError("Provide a two-dimensional array of at least 2x2.")
    height, width = feature_map.shape
    pooled = np.empty((height // 2, width // 2), dtype=feature_map.dtype)
    for output_row, row in enumerate(range(0, height - 1, 2)):
        for output_col, col in enumerate(range(0, width - 1, 2)):
            window = feature_map[row : row + 2, col : col + 2]
            pooled[output_row, output_col] = np.max(window)
    return pooled


feature_map = np.array([
    [1, 3, 2, 4],
    [5, 6, 1, 0],
    [7, 2, 8, 3],
    [4, 1, 6, 9],
])
print("Input feature map (4x4):")
print(feature_map)
for row in range(0, feature_map.shape[0] - 1, 2):
    for col in range(0, feature_map.shape[1] - 1, 2):
        window = feature_map[row : row + 2, col : col + 2]
        print(f"Window at row {row}, column {col}:\n{window}")
        print(f"Maximum = {np.max(window)}")
print("Max-pooled feature map (2x2):")
print(max_pool_2x2_stride2(feature_map))

The four printed maxima are 6, 4, 7, 9. The final output is:

[[6 4]
 [7 9]]

The slices select each window, and np.max(window) returns its largest value. The function accepts a two-dimensional array of at least 2×2. It uses complete 2×2 windows with stride 2; incomplete windows on the right or bottom are skipped, and no padding is added.

Why can a smaller map be useful?

Reducing spatial dimensions means subsequent layers process fewer spatial positions, which can reduce computation and memory use. Keeping the largest response in each window can retain a strong local response, but it discards other values and their exact locations inside that window. Whether this helps depends on the task and model. Max pooling is one option; not every CNN uses it.

In a CNN with multiple channels, pooling generally operates separately on each feature-map channel. Our small example shows one 2D map, not a complete image-classification model.

Try it yourself

Change the lower-right value from 9 to 5 and predict the new output before running the script. Run the modified script to check your prediction. Only the lower-right output changes, from 9 to 8, because 8 becomes the maximum in that window.

Frequently asked questions

Does max pooling train a filter?
No. It chooses the maximum in each window. The window size and stride are configuration choices; this operation does not learn filter weights.

Is max pooling the same as average pooling?
No. Max pooling returns the largest value in each window; average pooling returns the average of its values.

Does the map always shrink by half?
No. This example halves each dimension because its input is 4×4 and uses a 2×2 window with stride 2 and no padding. Output size depends on the input, window, stride and padding.

Does the largest value always mean the most important part of the original image?
Not necessarily. Its interpretation depends on the feature map and model. Pooling preserves the largest value within each window, not a guaranteed explanation of a prediction.

Continue learning

See the Computer Vision course overview for more about the course and its practical projects. My English-language course Computer Vision: OpenCV, Machine Learning and YOLO includes CNN concepts and practical work. This is my instructor referral link.

Tuesday, November 24, 2026

Why Does SELECT Fail? PostgreSQL Procedures vs Functions

Watch the tutorial

Watch the full PostgreSQL procedures tutorial or the short introduction.

You created a database routine, but SELECT produces an error: “is a procedure.” What happened? In PostgreSQL, a procedure is invoked with CALL. A function can be invoked in an expression such as SELECT. Let’s reproduce the error, then build and call a procedure that completes a group of synthetic enrollments.

The goal is to understand the definition, inputs, body, returned output and observed data changes—not just memorize a keyword. This example was executed with psql against PostgreSQL 18.6. You may use pgAdmin’s Query Tool or another compatible PostgreSQL client; the walkthrough below has not been separately tested in every client.

Before you begin

Use a PostgreSQL database where your account can create temporary tables and define the demonstrated temporary routines. Use a disposable learning session. All sample rows are fictional and independent of TrainingHub. The procedure performs an UPDATE, but only on our temporary sample table; it does not change a TrainingHub table. Keep the same database connection open for the complete walkthrough: the temporary table and routines belong to that session. Closing the session removes them.

Run the setup once. To start over, open a new database session and rerun it; running CREATE TEMP TABLE twice in the same session will report that the table already exists. Execute the deliberate error separately, with normal autocommit enabled. If you deliberately use an explicit transaction, an error can leave it aborted until ROLLBACK, and if the setup is part of that transaction rollback can remove the setup too. In that case start a fresh session and run the setup again.

The sample: four enrollments

enrollment_idcourse_idstatus
1101active
2101active
3102active
4101completed

The task: mark the active enrollments of one course as completed, then report how many rows changed. For course 101, two active rows match. Row 4 is already completed, and course 102 must remain untouched.

Set up the table, procedure and function

Run this entire setup block in one session. We explain both definitions below before invoking them.

-- Run the setup and all later statements in the SAME database session.
-- Synthetic sample; the table and routines live in the current temporary schema.
CREATE TEMP TABLE demo_enrollments (
    enrollment_id integer PRIMARY KEY,
    course_id integer NOT NULL,
    status text NOT NULL
);

INSERT INTO demo_enrollments (enrollment_id, course_id, status)
VALUES (1, 101, 'active'), (2, 101, 'active'),
       (3, 102, 'active'), (4, 101, 'completed');

CREATE PROCEDURE pg_temp.complete_course(
    IN p_course_id integer,
    INOUT p_updated_count integer
)
LANGUAGE plpgsql
AS $procedure$
BEGIN
    UPDATE demo_enrollments
    SET status = 'completed'
    WHERE course_id = p_course_id AND status = 'active';
    GET DIAGNOSTICS p_updated_count = ROW_COUNT;
END;
$procedure$;

CREATE FUNCTION pg_temp.active_count(p_course_id integer)
RETURNS bigint
LANGUAGE sql
AS $function$
    SELECT count(*) FROM demo_enrollments
    WHERE course_id = p_course_id AND status = 'active';
$function$;

CREATE TEMP TABLE creates a session-local table, and INSERT populates the four synthetic rows. pg_temp refers to this session’s temporary schema; it keeps the two demonstration routines separate from permanent application routines.

Read the procedure definition

CREATE PROCEDURE pg_temp.complete_course defines a named procedure; creation does not run its body. The parameters in parentheses have names, modes and types:

  • IN p_course_id integer receives the course identifier, such as 101.
  • INOUT p_updated_count integer accepts an input value and exposes an output value. This procedure overwrites the supplied initial value with the count. In a SQL CALL, the output parameter appears in a result row; it is not a guarantee that every procedure returns a result set.

LANGUAGE plpgsql chooses PostgreSQL’s procedural language. The matching $procedure$ tags delimit the procedure body as a string; the word inside the matching dollar-quote tags is a label, not a variable or parameter. Inside the BEGIN ... END block, the UPDATE targets only rows of the supplied course whose current status is active. Immediately afterward, GET DIAGNOSTICS p_updated_count = ROW_COUNT assigns the number of rows affected by that SQL command to the output parameter. See the official CREATE PROCEDURE and PL/pgSQL diagnostics documentation.

Read the function definition

The second definition, CREATE FUNCTION pg_temp.active_count(p_course_id integer), accepts a course ID. Its RETURNS bigint specifies the return type. Its LANGUAGE sql body is delimited by matching $function$ tags and returns the count of that course’s active rows. This specific function reads the sample table; functions are not universally read-only, and their effects depend on their definitions.

Why does SELECT fail for the procedure?

Run this separate statement after setup in the same session:

-- Intentional error: a procedure is not called with SELECT.
SELECT pg_temp.complete_course(101, 0);

PostgreSQL 18.6 reports:

ERROR:  pg_temp.complete_course(integer, integer) is a procedure
HINT:  To call a procedure, use CALL.

That statement does not invoke the procedure body. Use CALL for this procedure. Use SELECT for the active_count function in this example. A procedure can have output parameters as our example does, and a function can return scalar or set results; avoid assuming that “procedure” simply means no result. See PostgreSQL’s CALL reference.

Execute, inspect and repeat

Still in the same session, run each statement in order. If your client displays only the last result of a multi-statement execution, execute the statements individually so you can inspect each result.

-- Run after 01_setup.sql in the SAME session. The routine is not read-only.
SELECT pg_temp.active_count(101) AS active_before;
CALL pg_temp.complete_course(101, 0);
SELECT enrollment_id, course_id, status FROM demo_enrollments ORDER BY enrollment_id;
SELECT pg_temp.active_count(101) AS active_after;
CALL pg_temp.complete_course(101, 0);
  1. SELECT pg_temp.active_count(101) AS active_before returns 2: enrollment IDs 1 and 2 are active for course 101.
  2. CALL pg_temp.complete_course(101, 0) passes 101 to the input and 0 as the initial value of the INOUT parameter. The body overwrites that second value, and the result row has p_updated_count = 2.
  3. The table query shows IDs 1, 2 and 4 as completed; ID 3 stays active because it belongs to course 102.
  4. Calling the function again through SELECT gives active_after = 0 for course 101.
  5. A second identical CALL reports 0 changed rows because there are no active course-101 rows left in this fixture. This is a consequence of the particular WHERE clause, not a general property of procedures.
enrollment_idcourse_idstatus after first CALL
1101completed
2101completed
3102active
4101completed

These are actual values from the stated PostgreSQL execution. Other input data will produce different counts. The 0 argument is required here because p_updated_count is INOUT; this body does not use its incoming value. When calling a procedure from inside PL/pgSQL, output parameters have additional assignment rules; this tutorial shows direct SQL calls.

Functions, procedures and transaction control

In PostgreSQL, direct invocation is a practical distinction: SELECT pg_temp.active_count(101) invokes our function, whereas CALL pg_temp.complete_course(101, 0) invokes our procedure. The difference is not that functions can never change data or that procedures can never return output.

There are also important transaction-control differences. A procedure can use transaction control only under supported call conditions; for example, when CALL executes inside an explicit transaction block, the called procedure cannot execute transaction-control statements. Our procedure contains no COMMIT or ROLLBACK. Consult the CALL notes before designing routines that manage transactions.

Try it yourself

In a fresh session, rerun the setup. Predict the return value and changed row before calling CALL pg_temp.complete_course(102, 0). Use SELECT pg_temp.active_count(102) and the table query to check. Then call the same procedure again and explain why its count changes. Avoid applying this synthetic code to real customer data without appropriate validation and authorization.

For guided practice in PostgreSQL, SQL, functions and procedures, explore Practical SQL with PostgreSQL: From Queries to Real Projects. This is the instructor’s referral link. The example in this article is free and runs independently of the course.

Sunday, November 22, 2026

Traffic Heatmap with Python and YOLO: Visualize Vehicle Activity

Watch the full video tutorial · Watch the Short

Where did vehicles appear most often in a traffic video? A heatmap can turn a few seconds of bounding boxes into a picture that changes as the video plays. In this tutorial, we build one with Python, YOLO and OpenCV, and explain exactly what the colours represent.

The demonstration uses an AI-generated traffic scene. It is a small educational example, not a real traffic survey or a test of production accuracy.

What does this heatmap measure?

We divide the 1280 × 720 video into a 32 × 18 grid of 40 × 40 pixel cells. For each frame, a cell receives one point if its centre lies inside at least one accepted vehicle bounding box. It receives zero otherwise. We add the points across the frames.

This is detected box presence over frames. It is not the number of cars, the speed of a car, or a measurement of actual road occupancy. If two boxes overlap a cell centre in the same frame, that cell still receives only one point. A slowly moving or stationary vehicle can contribute to the same cell across many frames.

The source clip contains 241 frames at 24 frames per second. To keep colours comparable throughout the demonstration, the display uses a fixed scale from zero to 241 frames rather than stretching the range separately for every image. At any time, a value of 24 would mean the cell centre was covered by an accepted box in 24 processed frames; with every source frame processed, that corresponds to about one second of detected box presence in the video. The value is still a model-derived observation, not a confirmed physical occupancy.

From video to map

  1. Read the traffic clip one frame at a time.
  2. Run YOLOv8n with a confidence threshold of 0.20 and accept COCO vehicle classes car, motorcycle, bus and truck. This demonstration uses ByteTrack results.
  3. For every grid cell, check whether its centre falls inside any accepted vehicle box in the current frame.
  4. Add at most one to each cell for that frame, map the accumulated values to colours and draw the result over the video.

A fixed camera matters: a cell represents a position in the image, so camera movement makes the same grid cell cover different parts of the scene. If the camera moves, stabilise or otherwise account for that motion before interpreting a spatial map.

The core update

The complete program below reads a local video, runs the selected local YOLO model and writes an annotated MP4, three example frames, the grid as a NumPy array and a JSON summary. For another video, use a fixed camera and a compatible trained model; results will differ. The clip used in the demonstration is not offered as a download here.

The tested Windows/CPU environment used ultralytics 8.4.24, opencv-python 4.13.0.92, numpy 2.3.5, lap 0.5.13 and a CPU installation of PyTorch 2.10.0. See the official PyTorch installation selector for a suitable installation command. In an activated Python environment, the other tested packages can be installed with:

python -m pip install ultralytics==8.4.24 opencv-python==4.13.0.92 numpy==2.3.5 lap==0.5.13

The first run needs the appropriate local model file and tracker dependencies installed; this example does not assume a network connection will fetch missing files. Package compatibility depends on the Python version and platform.

Save the code as heatmap.py. Put your own video and a compatible local yolov8n.pt in the working directory, then run:

python heatmap.py --video your_video.mp4 --model yolov8n.pt --out traffic_heatmap.mp4

In model mode the script selects CPU, a 0.20 confidence threshold, a 640-pixel inference size, vehicle classes 2, 3, 5 and 7, and bytetrack.yaml. The optional --cache mode is for a previously generated compatible frame-by-frame JSON cache, not for an arbitrary JSON file. When no model is available locally, supply the required weights through a legitimate source and review their terms before use.

The following example uses Ultralytics; review the Ultralytics licensing terms for your use. The demonstration code is provided under AGPL-3.0, Copyright ARTSCI - Author of the AI/ML/CV course materials. The AI-generated video is not included under that code license.

Show the complete Python script
"""Build a 40px-grid vehicle detection-presence heatmap (not a vehicle counter).

Examples:
  python heatmap.py --video input.mp4 --model yolov8n.pt --out result.mp4
  python heatmap.py --video input.mp4 --cache tracks_cache.json --out result.mp4

The cache option requires an identical source-file SHA-256; model mode performs
local inference. For reproducible model mode, use the versions in README.md.
"""
import argparse
import hashlib
import json
from pathlib import Path

import cv2
import numpy as np


def sha256(path):
    h = hashlib.sha256()
    with open(path, 'rb') as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b''):
            h.update(chunk)
    return h.hexdigest()


def presence(boxes, w, h, grid=40):
    """One boolean per cell, true if its center is in any detection box."""
    # An edge cell can be narrower than grid; its true center is halfway
    # between its starting coordinate and the clipped image edge.
    left = np.arange((w + grid - 1) // grid) * grid
    top = np.arange((h + grid - 1) // grid) * grid
    x = (left + np.minimum(left + grid, w)) / 2
    y = (top + np.minimum(top + grid, h)) / 2
    present = np.zeros((len(y), len(x)), dtype=bool)
    for x1, y1, x2, y2 in boxes:
        present |= ((y[:, None] >= y1) & (y[:, None] <= y2) &
                    (x[None, :] >= x1) & (x[None, :] <= x2))
    return present


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--video', required=True)
    mode = p.add_mutually_exclusive_group(required=True)
    mode.add_argument('--cache', help='frame-indexed detections cached for this exact file')
    mode.add_argument('--model', help='local Ultralytics YOLO .pt file')
    p.add_argument('--out', default='traffic_heatmap.mp4')
    p.add_argument('--grid', type=int, default=40)
    p.add_argument('--confidence', type=float, default=0.20)
    p.add_argument('--save-cache', help='save inference results as JSON')
    args = p.parse_args()
    if args.grid < 1 or not 0 <= args.confidence <= 1 or (args.cache and args.save_cache):
        p.error('--save-cache requires --model, not --cache' if args.cache and args.save_cache else 'grid must be positive, confidence must be between 0 and 1')
    cap = cv2.VideoCapture(args.video)
    if not cap.isOpened():
        raise RuntimeError('Could not open video')
    w, h = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = float(cap.get(cv2.CAP_PROP_FPS))
    total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    if total < 1 or fps <= 0 or w % 2 or h % 2:
        raise ValueError('Video must have a known frame count, positive FPS, and even width and height; resize or pad odd dimensions first.')
    cache = None
    if args.cache:
        cache = json.loads(Path(args.cache).read_text(encoding='utf-8'))
        if cache['key']['source_sha256'] != sha256(args.video):
            raise ValueError('Cache source hash mismatch; rerun with --model')
        if len(cache['rows']) != total or any(row['frame'] != i for i, row in enumerate(cache['rows'])):
            raise ValueError('Cache frame count or order mismatch')
        if cache['key']['conf'] != args.confidence or cache['key']['classes'] != [2, 3, 5, 7]:
            raise ValueError('Cache parameters differ from expected settings')
        rows = cache['rows']
    else:
        if not Path(args.model).is_file():
            raise FileNotFoundError('Model must be an existing local file')
        from ultralytics import YOLO
        model = YOLO(args.model)
        rows = []
    out = cv2.VideoWriter(args.out, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
    if not out.isOpened():
        raise RuntimeError('Could not open video writer')
    heat = np.zeros(((h + args.grid - 1)//args.grid, (w + args.grid - 1)//args.grid), dtype=np.uint32)
    counts = []
    try:
        for frame_id in range(total):
            ok, frame = cap.read()
            if not ok:
                raise RuntimeError(f'Cannot decode frame {frame_id}/{total}')
            if cache is not None:
                detections = rows[frame_id]['detections']
                boxes = [d['xyxy'] for d in detections]
            else:
                result = model.track(frame, persist=True, conf=args.confidence, classes=[2,3,5,7],
                                     imgsz=640, tracker='bytetrack.yaml', device='cpu', verbose=False)[0]
                # Pilot stores only detections with an assigned track ID, so match it.
                boxes = result.boxes.xyxy.cpu().tolist() if result.boxes.id is not None else []
                ids = result.boxes.id.int().cpu().tolist() if result.boxes.id is not None else []
                classes = result.boxes.cls.int().cpu().tolist() if result.boxes.id is not None else []
                confidences = result.boxes.conf.cpu().tolist() if result.boxes.id is not None else []
                rows.append({'frame': frame_id, 'detections': [
                    {'id': tid, 'class': cl, 'conf': conf, 'xyxy': box}
                    for tid, cl, conf, box in zip(ids, classes, confidences, boxes)]})
            heat += presence(boxes, w, h, args.grid)
            counts.append(len(boxes))
            # Absolute, fixed scale: 0 is zero frames, 255 is total video frames.
            intensity = np.uint8(np.clip(heat.astype(np.float32) * 255 / total, 0, 255))
            # Repeat cells exactly grid pixels and crop the partial edge cells.
            intensity = np.repeat(np.repeat(intensity, args.grid, axis=0), args.grid, axis=1)[:h, :w]
            present_mask = np.repeat(np.repeat(heat > 0, args.grid, axis=0), args.grid, axis=1)[:h, :w]
            colour = cv2.applyColorMap(intensity, cv2.COLORMAP_TURBO)
            # Alpha is based on the unquantized count: a single detected frame
            # must remain visible even if 8-bit colour rounds its value to zero.
            alpha = np.where(present_mask, 0.58, 0.0).astype(np.float32)[..., None]
            view = np.uint8(frame * (1 - alpha) + colour * alpha)
            for x1,y1,x2,y2 in boxes:
                cv2.rectangle(view, (int(x1),int(y1)), (int(x2),int(y2)), (210,225,240), 1)
            out.write(view)
            if frame_id in (0, total//2, total-1):
                cv2.imwrite(str(Path(args.out).with_name(f'heatmap_frame_{frame_id:03d}.png')), view)
    finally:
        out.release(); cap.release()
    np.save(Path(args.out).with_name('final_counts.npy'), heat)
    result = {'source_sha256': sha256(args.video), 'frames': total, 'fps': fps,
              'size': [w,h], 'cell_px': args.grid, 'grid_shape': list(heat.shape),
              'scale_min_frames': 0, 'scale_max_frames': total,
              'maximum_cell_frames': int(heat.max()), 'nonzero_cells': int(np.count_nonzero(heat)),
              'detections_total': int(sum(counts)), 'frames_with_detections': sum(c > 0 for c in counts),
              'definition': 'number of frames whose cell center lies inside one or more tracked detection boxes'}
    Path(args.out).with_name('heatmap_result.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
    if args.save_cache:
        key = {'source_sha256': sha256(args.video), 'weights_sha256': sha256(args.model),
               'conf': args.confidence, 'classes':[2,3,5,7], 'imgsz':640, 'tracker':'bytetrack.yaml'}
        Path(args.save_cache).write_text(json.dumps({'key':key,'rows':rows}), encoding='utf-8')
    print(json.dumps(result, indent=2))


if __name__ == '__main__':
    main()

In this particular run, 263 of the 576 cells received at least one observation; the largest cell total was 201 of 241 frames. These describe the algorithm's detected boxes in this synthetic clip, not confirmed vehicle counts.

How to read the result responsibly

  • Detections are estimates. Missed objects leave gaps and false positives can add heat where there was no vehicle.
  • Box coverage is approximate. A rectangular box is not a segmentation mask, and testing only cell centres misses coverage that does not contain a centre.
  • Time and sampling matter. Results change with the number of sampled frames, frame rate, clip length and how long a vehicle stays in a place. Do not compare raw totals from clips of different lengths without a defined normalization.
  • Perspective matters. Equal-sized image cells do not necessarily represent equal areas on the road. A spatial calibration would be needed for meaningful real-world area or distance measurements.
  • Tracker identities are not verified car counts. An ID can change or disappear. This grid deliberately records box presence per frame; it does not use unique IDs as a count.

For comparison, a line counter answers a different question: how often an observed track crosses a chosen line. See my related traffic-counter article and video walkthrough.

Frequently asked questions

Can this count unique cars?

No. A cell stores detected presence across frames. Counting unique physical cars needs a separate tracking and validation method, and ID changes can still cause errors.

Why can a parked vehicle create a higher-value region?

Because its detected box can cover the same cell centre in many successive frames. The map reflects accumulated observations, not automatically traffic volume.

Does a blank cell prove no vehicle was there?

No. The model may miss a vehicle, a bounding box may cover only part of the cell without covering its centre, or the vehicle may be outside the frame.

For more on the underlying tools, see the official Ultralytics tracking documentation and OpenCV colour maps. Ultralytics also documents a separate heatmap solution; its implementation is distinct from the grid rule explained here.

If you would like to study more Python, OpenCV and YOLO projects, explore my Computer Vision course on Udemy. This is my instructor referral link.

Saturday, November 21, 2026

Sobel vs Canny Edge Detection in Python: An OpenCV Tutorial

How does a computer turn a photograph into lines? In this hands-on Python example, we compare two ways of finding intensity changes: Sobel derivatives and Canny edge detection. You will see the same input image, a gradient-strength map, and a binary edge map.

Watch the visual explanation: Sobel vs Canny Short. For the complete walkthrough, watch the Python and OpenCV tutorial.

What is an edge?

An edge is a location where pixel intensity changes sharply. A dark object against a bright background can create an edge, but so can a shadow, texture, or noise. An edge detector identifies changes in the image; it does not identify an object or understand its meaning.

How Sobel responds to changes

Sobel uses small, fixed kernels to approximate intensity derivatives. One derivative measures change along the x direction and another along y. Combining their values provides a gradient-strength map: brighter pixels in our visualization indicate a stronger response after the gradient magnitude is clipped to the 0–255 display range.

A filter scanning across an image is a useful way to understand the computation. The Sobel kernel is chosen by us; it is not a trained neural-network filter. If you want the background on sliding kernels, see How CNN Filters Find Edges.

What Canny adds

Canny is a multi-stage edge detector. Its stages include gradient estimation, thinning candidate edges through non-maximum suppression, and hysteresis thresholding. In this example, we apply Gaussian blur before Canny to reduce sensitivity to noise. The Sobel result uses unblurred grayscale, matching the course exercise. This makes the demonstration useful for exploring each step, but it is not a comparison with identical preprocessing.

The two Canny thresholds work together: strong candidate edges are kept; weaker candidates can be kept when connected to a strong edge. Changing thresholds can remove noise or detail, but the best settings depend on the input image. cv2.Canny does not automatically perform the separate Gaussian blur shown in this example.

Try it with Python and OpenCV

Install Python, then install the dependencies in your environment:

python -m pip install opencv-python numpy

To recreate the geometric image used in the video, save the following code as generate_input.py and run python generate_input.py in a new folder. It creates input.png; it stops if that file already exists so it does not overwrite your image.

"""Generate the seeded synthetic geometric image used in course lesson 07.

Run: python generate_input.py
Requires: pip install opencv-python numpy
"""
from pathlib import Path
import cv2
import numpy as np

rng = np.random.default_rng(7)
img = np.zeros((480, 640, 3), dtype=np.uint8)
img[:] = (30, 25, 45)
cv2.rectangle(img, (80, 80), (280, 280), (200, 180, 100), -1)
cv2.circle(img, (450, 180), 110, (100, 200, 180), -1)
cv2.ellipse(img, (320, 380), (120, 60), 30, 0, 360, (180, 100, 200), -1)
cv2.line(img, (60, 400), (580, 440), (220, 220, 80), 4)
noise = rng.normal(0, 8, img.shape).astype(np.int16)
img = np.clip(img.astype(np.int16) + noise, 0, 255).astype(np.uint8)
output = Path(__file__).resolve().parent / 'input.png'
if output.exists():
    raise SystemExit(f'File already exists: {output}. Choose a clean folder to avoid overwriting it.')
if not cv2.imwrite(str(output), img):
    raise RuntimeError(f'Unable to write {output}')
print(f'Saved {output}')

Now save the following script as sobel_canny.py in the same folder and run python sobel_canny.py. To use your own image instead, run python sobel_canny.py YOUR_IMAGE.jpg, replacing the name with the actual filename or path. Use an image you have the right to use.

"""Sobel gradient magnitude and Canny edges, based on course lesson 07.

Run: python sobel_canny.py [input_image]
Requires: pip install numpy opencv-python
Outputs are written alongside the script. Canny operates on blurred grayscale;
Sobel operates on unblurred grayscale, matching the lesson notebook.
"""
from pathlib import Path
import json
import sys

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
source = Path(sys.argv[1]) if len(sys.argv) > 1 else HERE / "input.png"
image = cv2.imread(str(source), cv2.IMREAD_COLOR)
if image is None:
    raise SystemExit(f"Cannot read image: {source}")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
gx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
gy = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
magnitude = np.sqrt(gx**2 + gy**2)
sobel = np.uint8(np.clip(magnitude, 0, 255))

def save(name, pixels):
    path = HERE / name
    if not cv2.imwrite(str(path), pixels):
        raise RuntimeError(f"Failed to write {path}")

save("sobel_magnitude.png", sobel)
measurements = {}
for low, high in [(20, 60), (50, 150), (100, 200), (150, 250)]:
    edges = cv2.Canny(blurred, low, high)
    assert edges.shape == gray.shape and set(np.unique(edges)).issubset({0, 255})
    save(f"canny_{low}_{high}.png", edges)
    measurements[f"{low}/{high}"] = int(np.count_nonzero(edges))
results = {
    "input": str(source.name), "width": int(image.shape[1]), "height": int(image.shape[0]),
    "opencv": cv2.__version__, "numpy": np.__version__,
    "canny_nonzero_pixels": measurements,
    "sobel_nonzero_pixels": int(np.count_nonzero(sobel)),
    "interpretation": "Canny is binary; Sobel shows clipped gradient magnitude. Counts are not accuracy measurements."
}
(HERE / "measurements.json").write_text(json.dumps(results, indent=2), encoding="utf-8")
print(json.dumps(results, indent=2))

The script saves sobel_magnitude.png, four Canny images for threshold pairs 20/60, 50/150, 100/200 and 150/250, and measurements.json in the script folder. Those counts report nonzero pixels; they are not accuracy scores or object counts. The demonstration was tested with OpenCV 4.13.0 and NumPy 2.3.5. Versions and image input can affect results. Re-running the processing script overwrites its output files.

Compare the results

  • Sobel: the displayed map shows the strength of intensity changes; it is not inherently a binary outline.
  • Canny: the output marks selected edge pixels after thinning and thresholding.
  • Try this: change both Canny thresholds and compare the resulting outlines. Also try a more textured image or change the blur. Do not assume that fewer lines always mean a more accurate result.

Frequently asked questions

Is Canny a neural network?
No. It is a classical, multi-stage image-processing algorithm. It does not learn weights from a training dataset.

Which is better, Sobel or Canny?
It depends on the task. Sobel provides derivatives or gradient strength; Canny is often useful when you want a thinner, binary edge map. Both are sensitive to image content and parameter choices.

Can edges be used to count objects?
They may help with later processing, but edges alone do not reliably count objects. Broken boundaries, touching objects, lighting and texture can lead to mistakes.

Continue learning

Explore the computer vision course overview and my English-language course, Computer Vision: OpenCV, Machine Learning and YOLO. The course includes hands-on lessons on image operations, edge detection and further computer vision techniques. This is my instructor referral link.

Further reading: OpenCV: Sobel derivatives and OpenCV: Canny edge detection.

Why Does SQL Skip Rank 3? ROW_NUMBER vs RANK vs DENSE_RANK

Watch the tutorial

Watch the full SQL ranking tutorial or the short introduction.

Two people share second place. Does the next person finish third or fourth? In SQL, the answer depends on the ranking function you choose. That choice can change a leaderboard or a top courses report even when the input data is the same.

We will run a small PostgreSQL example, look at the rows, and then rank courses within each category. The data below is synthetic: it does not change any database tables. You can run each complete SQL block in pgAdmin's Query Tool or another PostgreSQL client.

Four scores, one tie

IDParticipantScore
1Anna100
2Ben90
3Chris90
4Dana80

Ben and Chris have the same score. This self-contained query shows all three rankings side by side:

WITH scores (id, participant, score) AS (
    VALUES (1, 'Anna', 100), (2, 'Ben', 90),
           (3, 'Chris', 90), (4, 'Dana', 80)
)
SELECT participant, score,
       ROW_NUMBER() OVER (ORDER BY score DESC, id) AS row_num,
       RANK()       OVER (ORDER BY score DESC) AS rank_num,
       DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank_num
FROM scores
ORDER BY score DESC, id;

WITH ... VALUES supplies a temporary set of input rows for this query; it does not create a table. The OVER clause determines how each window function orders its input. The final ORDER BY controls the order in which the query displays the result.

participantscorerow_numrank_numdense_rank_num
Anna100111
Ben90222
Chris90322
Dana80443

ROW_NUMBER: one sequence number per row

ROW_NUMBER() assigns a different position to each row. Both 90-point rows still represent a tie by score, but their row numbers must differ. Here, id is a unique tie-breaker: Ben has a smaller ID, so he receives 2. If we ordered by score alone, PostgreSQL would not promise which tied row gets which number. This is useful when the requirement is to select a fixed number of rows and a deterministic tie-breaker is acceptable.

RANK: equal scores share a rank; gaps remain

RANK() assigns 2 to both 90-point rows. Since two rows have already occupied positions 2 and 3, the next rank is 4. Choose it when equal values should share a rank and the gap reflects the number of preceding rows.

DENSE_RANK: equal scores share a rank; no gaps

DENSE_RANK() also assigns 2 to both 90-point rows, but the next distinct score receives 3. Choose it when you want consecutive ranks for distinct score levels.

The distinction comes from what counts as a peer. The ordering inside RANK() and DENSE_RANK() uses score alone, so the two 90s are peers. Adding a unique id to those two window orderings would make them different peers and eliminate the intended tie. We use id in the ROW_NUMBER() ordering, and separately in the final display ordering; that final sort does not change the ranks. PostgreSQL documents these functions in Window Functions.

Rank courses separately in each category

Suppose a training company wants the two highest ranks in each category, including every course tied at second place. The next example supplies seven fictional courses; the values are an illustration, not counts from a live TrainingHub database.

WITH courses (course_id, category, course_name, enrollments) AS (
    VALUES (1, 'Java', 'Java Basics', 80),
           (2, 'Java', 'Spring Intro', 70),
           (3, 'Java', 'Java Testing', 70),
           (4, 'SQL', 'SQL Basics', 100),
           (5, 'SQL', 'SQL Joins', 90),
           (6, 'SQL', 'SQL Reports', 90),
           (7, 'SQL', 'SQL Views', 80)
), ranked AS (
    SELECT course_id, category, course_name, enrollments,
           ROW_NUMBER() OVER (
               PARTITION BY category ORDER BY enrollments DESC, course_id
           ) AS row_num,
           RANK() OVER (
               PARTITION BY category ORDER BY enrollments DESC
           ) AS course_rank
    FROM courses
)
SELECT category, course_name, enrollments, row_num, course_rank
FROM ranked
WHERE course_rank <= 2
ORDER BY category, enrollments DESC, course_id;

PARTITION BY category starts a separate ranking for Java and SQL. The inner CTE calculates ranks for each course; the outer query filters them. The SQL result is:

categorycourse_nameenrollmentsrow_numcourse_rank
JavaJava Basics8011
JavaSpring Intro7022
JavaJava Testing7032
SQLSQL Basics10011
SQLSQL Joins9022
SQLSQL Reports9032

Each category returns three courses, not two: both courses tied for second place satisfy course_rank <= 2. If the requirement is at most two rows per category, use WHERE row_num <= 2 instead. For this fixture that selects Java Basics, Spring Intro, SQL Basics and SQL Joins. It intentionally excludes one tied course in each category using course_id as the tie-breaker. If a category has fewer than two courses, it returns only the rows available.

DENSE_RANK() <= 2 would select the first two distinct enrollment-count levels per category. It can return more than two rows as well. More generally, RANK() <= N and DENSE_RANK() <= N need not return the same set because RANK can have gaps. Write the business rule first: exactly N rows where available, ranks with gaps, or N distinct value levels.

Common mistakes to avoid

  • Confusing display order with rank order. The final ORDER BY sorts the output. The ORDER BY inside each OVER defines that function's ranking.
  • Accidentally removing ties. A unique identifier inside RANK or DENSE_RANK makes rows with equal scores non-peers. Use an ID only where it is part of the intended ranking rule.
  • Assuming ROW_NUMBER() is reproducible with ties. Provide an explicit, unique tie-breaker if a stable choice matters.
  • Filtering a window value in the same query's WHERE. Calculate it in a CTE or subquery, then filter in the outer query. See the PostgreSQL window-function tutorial.
  • Ignoring missing values. These examples use non-null scores. If real data can contain NULL, decide where those rows belong and specify an appropriate NULLS FIRST or NULLS LAST rule. Do not treat a missing score as zero without a reason.

Try it yourself

Change Dana's score to 90. Predict all three columns before running the first query again. Which function gives three rows the same rank? Which one continues without a gap? For another exercise, change the second query to return at most two rows per category and verify which tied course is excluded.

For more practice with PostgreSQL, SQL and a synthetic training-business database, explore Practical SQL with PostgreSQL: From Queries to Real Projects. This is the instructor's referral link. The example above runs independently of the paid course.

Friday, November 20, 2026

How CNN Filters Find Edges: A 3×3 Convolution Example in Python

How can a convolutional neural network (CNN) begin to find useful patterns in an image? One building block is a small filter that moves across pixel values. At each position, it combines a local patch of pixels with the filter's weights to produce one number.

In this tutorial, we follow a 3×3 edge filter across a tiny image, calculate a value by hand, and reproduce the complete result in Python. The example uses a hand-picked filter to explain an operation used in CNNs; it is not an activation taken from a trained network.

Watch the moving filter and feature map in the YouTube Short.

1. The image and the filter

Our grayscale image is a 5×5 grid. Each row is identical. Here, 0 represents black and 255 represents white:

  0  255  255  255    0
  0  255  255  255    0
  0  255  255  255    0
  0  255  255  255    0
  0  255  255  255    0

The example filter has three identical rows. It subtracts the left side of each patch from the right side:

-1   0   1
-1   0   1
-1   0   1

This filter is sensitive to changes from left to right, so it responds to vertical boundaries. Different filters respond to different patterns.

2. Calculate the first output value

Place the filter over the upper-left 3×3 patch. Multiply each pixel by the weight at the same position and sum all nine products. Because the three rows in this particular patch are identical, we can show the calculation for one row and multiply its result by three:

One row: 0 × -1 + 255 × 0 + 255 × 1 = 255
Three rows: 255 + 255 + 255 = 765

The first output cell is therefore +765. Move the filter one pixel to the right and repeat. In the middle patch, all pixel values are 255, so the positive and negative contributions cancel and the output is 0. At the right boundary the response is -765.

3. From a moving filter to a feature map

We move one pixel at a time (stride 1) and do not add a border (no padding). The filter fits in three positions across and three down, so the 5×5 input produces a 3×3 output: (5 − 3 + 1) × (5 − 3 + 1).

 765   0  -765
 765   0  -765
 765   0  -765

These are signed raw responses. In this example, +765 and -765 indicate opposite directions of the same kind of brightness change. Zero appears for the uniform middle patch; it does not prove that every possible image patch with a zero response is uniform. Taking an absolute value, clipping values, or applying an activation changes how the output is interpreted.

4. Run the calculation in Python

You need Python and NumPy. If NumPy is not installed in your chosen environment, run python -m pip install numpy. Save the code below as cnn_filter_example.py and run python cnn_filter_example.py. No image file, model weights, or GPU is required.

import numpy as np

# Five identical rows make a simple grayscale image.
# Signed integers preserve negative results.
image = np.array([[0, 255, 255, 255, 0]] * 5, dtype=np.int32)
kernel = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], dtype=np.int32)

# Valid cross-correlation: stride 1, no padding, no flipped kernel.
feature_map = np.zeros((3, 3), dtype=np.int32)
for row in range(feature_map.shape[0]):
    for col in range(feature_map.shape[1]):
        patch = image[row:row + 3, col:col + 3]
        feature_map[row, col] = np.sum(patch * kernel)

print('First patch:')
print(image[:3, :3])
print('First output value:', feature_map[0, 0])
print('Signed feature map:')
print(feature_map)
np.testing.assert_array_equal(feature_map, [[765, 0, -765]] * 3)

The assertion checks this particular fixture; it is not a test of a trained model's accuracy. Using a signed integer type matters: unsigned pixel types cannot represent -765 directly.

How does this relate to a CNN?

A convolutional layer applies filters to local patches to create feature maps. A real CNN can use multiple filters, input channels, biases, nonlinear activations and other layers. Its filter weights are usually learned during training. Here we chose the numbers ourselves to make the calculation easy to inspect; we did not train or run a CNN.

Strictly speaking, this example does cross-correlation: it does not flip the kernel before applying it. CNN libraries commonly call this operation convolution. The PyTorch Conv2d documentation describes the cross-correlation operation used by that layer.

Try it yourself

Reverse each filter row to [1, 0, -1] and run the script again after removing or updating the assertion. Can you predict the new signs? Keep the image and all other code unchanged. The positive and negative outputs should exchange signs, while the middle column remains zero.

Frequently asked questions

Why is the output smaller than the input?
With a 3×3 filter, stride 1 and no padding, the filter can start at only three rows and three columns of a 5×5 input. Padding and stride change the output dimensions.

Are CNN filters always edge detectors?
No. Filters are learned for the task; the patterns and their interpretation depend on the trained network, layer and input.

Does a negative value mean an error?
No. A negative value is a valid signed response. Here its sign reflects the direction of the brightness change relative to our chosen filter.

Continue learning

Watch the short animation to follow the moving window. Read the course overview on this blog. My English-language course Computer Vision: OpenCV, Machine Learning and YOLO includes a hands-on lesson on convolution. This is my instructor referral link.

Sunday, November 15, 2026

Why Does SQL SUM Give the Wrong Total After a JOIN?

Watch the tutorial

Watch the full SQL JOIN and SUM tutorial or the short introduction.

Two orders total $200. After joining them to their items, a query reports $300 — with no error. Add DISTINCT inside SUM, and the answer becomes $100. Both results can be wrong for the question we intended to ask.

Let's inspect the rows, reproduce the problem in PostgreSQL and choose a fix based on which orders should count. The example is synthetic and read-only.

The question comes first

Suppose we need the sum of order totals for orders with at least one item. We have two orders:

order_idorder_total
101100
102100

The items are:

item_idorder_id
1101
2101
3102

Each order appears once in the orders data, and both have at least one item. The intended total is 100 + 100 = 200. In this demonstration, an order total is an order-level amount; the item table identifies matches and is not a source of item prices.

Each runnable example below defines its input using WITH and VALUES. Run a complete block in pgAdmin's Query Tool or another PostgreSQL client. It does not create persistent tables or modify data.

Start with the order-level total

WITH orders(order_id, order_total) AS (VALUES (101,100), (102,100))
SELECT SUM(order_total) AS order_total
FROM orders;

For these inputs the result is 200. Since both orders have items, the total of all orders happens to equal the total of orders with at least one item. That will not always be true.

Look at what JOIN really produces

WITH orders(order_id, order_total) AS (VALUES (101,100), (102,100)),
items(item_id, order_id) AS (VALUES (1,101), (2,101), (3,102))
SELECT o.order_id, o.order_total, i.item_id
FROM orders AS o
JOIN items AS i ON i.order_id = o.order_id
ORDER BY o.order_id, i.item_id;
order_idorder_totalitem_id
1011001
1011002
1021003

The join returns one row per matching order and item pair. Order 101 has two matching items, so its order-level amount appears twice. These rows describe distinct order-item pairs, not duplicate items or duplicate orders in the original input. See PostgreSQL's explanation of joined tables.

SUM adds the joined rows

WITH orders(order_id, order_total) AS (VALUES (101,100), (102,100)),
items(item_id, order_id) AS (VALUES (1,101), (2,101), (3,102))
SELECT SUM(o.order_total) AS joined_sum,
       SUM(DISTINCT o.order_total) AS distinct_amount_sum,
       COUNT(*) AS joined_rows,
       COUNT(DISTINCT o.order_id) AS distinct_order_ids
FROM orders AS o
JOIN items AS i ON i.order_id = o.order_id;
joined_sumdistinct_amount_sumjoined_rowsdistinct_order_ids
30010032

SUM(o.order_total) sums the order total on every joined row: 100 + 100 + 100 = 300. The extra $100 comes from repeating order 101's total once for each item.

SUM(DISTINCT o.order_total) does something different: it sums each distinct amount once, not each order once. Both orders have the amount 100, so this query counts that amount only once and returns 100. Distinct amounts are useful if that is actually the question; they are not a general repair for counting orders. PostgreSQL describes DISTINCT within aggregates in its aggregate-expression documentation.

COUNT(DISTINCT o.order_id) is a helpful diagnostic in this specific example because order_id identifies orders in the supplied data: three matched pairs contain two order IDs. A row-count difference does not automatically mean a join is wrong — it can be expected for a one-to-many relationship.

Fix for “orders with at least one item”: EXISTS

If we only need to check that a matching item exists, EXISTS asks that question without producing one order row per item:

WITH orders(order_id, order_total) AS (VALUES (101,100), (102,100)),
items(item_id, order_id) AS (VALUES (1,101), (2,101), (3,102))
SELECT SUM(o.order_total) AS matched_order_total
FROM orders AS o
WHERE EXISTS (
    SELECT 1 FROM items AS i WHERE i.order_id = o.order_id
);

The result is 200. EXISTS tests whether the subquery returns a row for the current order; its SELECT 1 does not mean that it returns or counts item prices. It includes an order once if at least one matching item exists. See PostgreSQL's EXISTS documentation.

If your report also needs item-level values, you may instead aggregate the item side to one row per order before joining it to orders. Joining a one-row-per-order summary avoids multiplying the order-level amount, provided the order key is unique and the joins and filters reflect the intended population. Whether an order amount should equal the sum of its item amounts depends on business rules such as discounts, tax and shipping; do not assume it without checking.

What about orders with no items?

Add an order 103 worth 50 with no matching item. The total of all orders is now 250. The total of orders with at least one item remains 200. Neither number answers every question:

WITH orders(order_id, order_total) AS (VALUES (101,100), (102,100), (103,50)),
items(item_id, order_id) AS (VALUES (1,101), (2,101), (3,102)),
item_counts AS (
    SELECT order_id, COUNT(*) AS item_count
    FROM items
    GROUP BY order_id
)
SELECT SUM(o.order_total) AS all_order_total,
       SUM(o.order_total) FILTER (WHERE ic.order_id IS NOT NULL) AS matched_order_total
FROM orders AS o
LEFT JOIN item_counts AS ic ON ic.order_id = o.order_id;

For this input the query gives 250 and 200 respectively. The grouped item_counts has at most one row per order ID; the LEFT JOIN retains order 103. Its unmatched ic.order_id is NULL, so the filtered aggregate excludes it. An inner join or the earlier EXISTS query intentionally excludes the order with no items. Choose based on your report's requirements.

With no qualifying non-null input amounts, PostgreSQL's SUM returns NULL rather than zero. If zero is the desired reporting rule, use COALESCE deliberately. See aggregate functions.

A practical debugging checklist

  1. Write down what one row represents in each input and what the final metric must count.
  2. Inspect the joined rows before aggregating, including identifiers from both sides.
  3. Compare joined row counts with distinct order IDs when the key is known and non-null.
  4. Check whether missing matches should be retained or removed.
  5. Compare against a small dataset with known answers, including two different orders that have the same amount.

These are correctness checks, not a performance benchmark. The best execution plan and timing depend on data, indexes, PostgreSQL version and the actual query; measure the relevant workload rather than assuming that EXISTS is always faster.

Try it yourself

Add a third item to order 101. What does the naive joined sum return? What does the EXISTS query return? Then add an order with no items and decide explicitly whether your report should include it. Run the queries and compare the results.

For another join-related surprise, see Why Your LEFT JOIN Loses Rows: ON vs WHERE in PostgreSQL.

For guided SQL practice, explore Practical SQL with PostgreSQL: From Queries to Real Projects. This is the instructor's referral link. The course uses TrainingHub, a synthetic training-business database.

The example uses self-contained PostgreSQL SELECT statements with synthetic data. Verify results in your own environment and on representative inputs.

Saturday, November 14, 2026

Why Does SQL NOT IN Return No Rows? The NULL Trap and NOT EXISTS

Watch the tutorial

Watch the full NOT IN and NULL tutorial or the short introduction.

Your query should find customers without a matching order. Instead, PostgreSQL returns no rows. There is no syntax error. The cause can be a single NULL in the subquery used by NOT IN.

In this tutorial, you will reproduce the problem with five small rows, see why it happens, and compare two ways to find customers with no order whose known customer ID matches. The examples run in PostgreSQL and do not change your database.

The data: three customers and two orders

We have customers Anna (1), Ben (2), and Cara (3). The order data contains a row for customer 1 and another row whose customer ID is NULL.

Customer IDName
1Anna
2Ben
3Cara
Order customer ID
1
NULL

The question is: which customers have no order with a matching known customer ID? Anna has a match. Ben and Cara do not. This does not prove that they never placed an order: the order with an unknown customer ID could belong to either of them. Without more data, we cannot assign it to anyone.

In the examples below, each query uses common table expressions (WITH) and VALUES to create temporary input rows for that statement. Paste any complete query into pgAdmin's Query Tool and execute it. Nothing is inserted, updated or deleted.

The surprising query: NOT IN

WITH customers(id, name) AS (
    VALUES (1, 'Anna'), (2, 'Ben'), (3, 'Cara')
),
orders(customer_id) AS (
    VALUES (1), (NULL::integer)
)
SELECT c.id, c.name
FROM customers AS c
WHERE c.id NOT IN (SELECT o.customer_id FROM orders AS o)
ORDER BY c.id;

Result in PostgreSQL: zero rows. Why don't Ben and Cara appear?

Why does one NULL change the result?

NOT IN compares a customer's ID with all values produced by the subquery. For Ben, whose ID is 2, the condition behaves like:

2 <> 1 AND 2 <> NULL

2 <> 1 is true, but 2 <> NULL is unknown, not true. Consequently, the complete condition is unknown. SQL's WHERE keeps rows for which its condition is true; both false and unknown fail the filter. Cara's comparison behaves the same way. Anna matches 1, so her NOT IN condition is false.

This is not a PostgreSQL error. It follows SQL's treatment of NULL as an unknown or missing value in comparisons. See PostgreSQL's documentation of NOT IN.

Fix 1: exclude NULL from the subquery

When unknown order customer IDs should not count as known matches, filter them out on the right-hand side:

WITH customers(id, name) AS (
    VALUES (1, 'Anna'), (2, 'Ben'), (3, 'Cara')
),
orders(customer_id) AS (
    VALUES (1), (NULL::integer)
)
SELECT c.id, c.name
FROM customers AS c
WHERE c.id NOT IN (
    SELECT o.customer_id
    FROM orders AS o
    WHERE o.customer_id IS NOT NULL
)
ORDER BY c.id;

Result:

idname
2Ben
3Cara

The subquery now produces only 1. Each ID on the left in this example is non-null. Filtering the subquery alone does not settle what should happen if a left-hand ID can also be NULL; see the separate case below.

Fix 2: ask whether a matching row exists

NOT EXISTS asks a different, often clearer question: for this customer, is there no order row whose customer ID equals this customer's ID?

WITH customers(id, name) AS (
    VALUES (1, 'Anna'), (2, 'Ben'), (3, 'Cara')
),
orders(customer_id) AS (
    VALUES (1), (NULL::integer)
)
SELECT c.id, c.name
FROM customers AS c
WHERE NOT EXISTS (
    SELECT 1
    FROM orders AS o
    WHERE o.customer_id = c.id
)
ORDER BY c.id;

The result is again Ben and Cara. The correlated condition uses the current customer's ID; the order with a NULL customer ID does not satisfy an equality comparison to that ID. SELECT 1 is enough because EXISTS checks whether the subquery returns a row, not the selected value. See PostgreSQL: EXISTS.

Neither this small example nor the name of an operator proves which query is faster. Performance depends on the query, data, indexes and execution plan; measure on the relevant workload.

What if the left-hand ID is NULL too?

The example deliberately uses non-null customer IDs. For nullable values on the left, the two approaches can differ even after filtering NULL from the subquery:

WITH orders(customer_id) AS (VALUES (1), (NULL::integer))
SELECT
    NULL::integer NOT IN (
        SELECT customer_id FROM orders WHERE customer_id IS NOT NULL
    ) AS null_not_in,
    NOT EXISTS (
        SELECT 1 FROM orders WHERE customer_id = NULL::integer
    ) AS null_not_exists;

PostgreSQL returns NULL for null_not_in and true for null_not_exists. In the second expression, equality to NULL does not produce a matching row. Decide deliberately how the application should treat an unknown customer ID; add an appropriate left-side condition if needed. Do not assume the approaches are interchangeable for all nullable inputs. The treatment of an empty subquery is another case to consider when designing a query.

Quick questions

Does NOT IN always return zero rows? No. The issue above arises when the subquery contains a NULL, in this single-column example. With no right-hand NULL, nonmatching non-null IDs can pass. If the subquery returns no rows, NOT IN has its own defined behavior.

Can I just replace every NOT IN with NOT EXISTS? Not without checking the intended behavior for NULL on both sides. For the demonstrated non-null customer IDs and equality match, the filtered NOT IN and NOT EXISTS produce the same result.

Does a row with a NULL customer ID belong to nobody? No. The ID is unknown in this dataset, so the row cannot be assigned to a specific customer from this information alone.

Does the example modify my data? No. The statements use VALUES and SELECT; they do not create tables or write rows.

Try it yourself

Change the second order from NULL to 2, run each query again, and predict which customers remain. Then change it back to NULL and explain why the first query loses the unmatched rows. In real work, check the business meaning of unknown IDs before choosing how to handle them.

For another SQL filtering surprise, read Why Your LEFT JOIN Loses Rows: ON vs WHERE in PostgreSQL.

To practice SQL and PostgreSQL with guided examples, explore Practical SQL with PostgreSQL: From Queries to Real Projects. This is the instructor's referral link. The course uses TrainingHub, a synthetic training-business database.

Verified against PostgreSQL 18.6 using a self-contained, read-only example. Behavior and plans for other workloads should be checked in their own environments.

Friday, November 13, 2026

Why PostgreSQL Does Not Always Use Your Index: EXPLAIN ANALYZE

Watch the tutorial

Watch the full PostgreSQL EXPLAIN ANALYZE tutorial or the short introduction.

You created an index, but PostgreSQL still chooses a sequential scan. Is the index broken? Not necessarily. In this tutorial, you will use EXPLAIN ANALYZE to compare two filters on the same temporary table and learn why an index can be useful for one query while the planner chooses a sequential scan for another.

The answer depends on the data and the work a query needs to do. We will inspect an actual local PostgreSQL execution, not guess from the presence of an index.

What you will need

Use PostgreSQL and a SQL client such as psql or pgAdmin's Query Tool. Run the complete setup and both queries in one database session: the sample table is temporary, so it disappears at the end of that session. The demonstrated run used PostgreSQL 18.6 on Linux in a separate disposable Docker container; the commands below were executed by psql. No existing course tables were changed. Creating temporary tables requires the appropriate database privileges.

The sample is deliberately artificial: 200,000 orders distributed evenly across 1,000 customer IDs. We compare a filter for a single customer with a filter for customers 1 through 900. These queries return different amounts of data; their elapsed times are not a benchmark of the same workload with and without an index.

Build the sample and the index

CREATE TEMP TABLE demo_orders (
    order_id integer NOT NULL,
    customer_id integer NOT NULL,
    amount numeric(10,2) NOT NULL
);

INSERT INTO demo_orders (order_id, customer_id, amount)
SELECT n, ((n - 1) % 1000) + 1, ((n % 10000)::numeric / 100)
FROM generate_series(1, 200000) AS g(n);

CREATE INDEX demo_orders_customer_id_idx ON demo_orders(customer_id);
ANALYZE demo_orders;

CREATE TEMP TABLE creates a session-scoped table. generate_series provides the sample values. The B-tree index is on customer_id; ANALYZE collects statistics the planner can use to estimate how many rows meet each condition. Other PostgreSQL settings, versions, hardware, data distributions and cached pages can produce different plans and times.

Confirm the inputs:

SELECT count(*) AS total_rows,
       count(*) FILTER (WHERE customer_id = 42) AS narrow_rows,
       count(*) FILTER (WHERE customer_id BETWEEN 1 AND 900) AS broad_rows
FROM demo_orders;

In our run the result was 200,000 total rows, 200 for customer 42 and 180,000 in the 1–900 range. The first filter matches 0.1% of this dataset; the second matches 90%.

One customer: inspect an index-supported plan

EXPLAIN (ANALYZE, BUFFERS)
SELECT sum(amount)
FROM demo_orders
WHERE customer_id = 42;

In one local execution, the relevant part of the plan was:

Aggregate  (cost=515.05..515.06 rows=1 width=32) (actual time=0.328..0.329 rows=1.00 loops=1)
  ->  Bitmap Heap Scan on demo_orders  (cost=5.84..514.55 rows=199 width=6) (actual time=0.068..0.304 rows=200.00 loops=1)
        Recheck Cond: (customer_id = 42)
        ->  Bitmap Index Scan on demo_orders_customer_id_idx  (cost=0.00..5.79 rows=199 width=0) (actual time=0.035..0.036 rows=200.00 loops=1)
              Index Cond: (customer_id = 42)
Execution Time: 0.351 ms

Read the tree from its child nodes upward: in this run, a Bitmap Index Scan used the customer index to identify candidate locations, and a Bitmap Heap Scan visited the table to obtain the matching rows. The aggregate summed their amounts. The planner estimated 199 rows at the bitmap heap scan; EXPLAIN ANALYZE reported 200 actual rows. The cost numbers are planner units, not milliseconds; actual time and Execution Time report timing from that run.

EXPLAIN ANALYZE actually executes its statement. This example uses SELECT, but do not assume it is harmless for statements with side effects. See the PostgreSQL EXPLAIN documentation.

Most customers: why a sequential scan can make sense

EXPLAIN (ANALYZE, BUFFERS)
SELECT sum(amount)
FROM demo_orders
WHERE customer_id BETWEEN 1 AND 900;

In the same run:

Aggregate  (cost=4532.63..4532.64 rows=1 width=32) (actual time=24.887..24.889 rows=1.00 loops=1)
  ->  Seq Scan on demo_orders  (cost=0.00..4082.00 rows=180253 width=6) (actual time=0.030..14.546 rows=180000.00 loops=1)
        Filter: ((customer_id >= 1) AND (customer_id <= 900))
        Rows Removed by Filter: 20000
Execution Time: 24.967 ms

The index still exists. Here the chosen plan reads the temporary table sequentially and filters its rows. The condition retains 180,000 of 200,000 rows, so an index is not automatically the most attractive way to retrieve the needed data. In another environment PostgreSQL might choose a different plan; costs and data distributions matter. See Examining Index Usage and Using EXPLAIN.

This is not evidence that the sequential scan was proven fastest across all workloads. We inspected the planner's choice and the observed execution of each query. The two example queries have different filters and result sizes: do not divide their times and claim an index speedup. Cache state and measurement overhead also affect reported times.

Read a plan without guessing

  1. Check the actual node: is it a sequential, index, bitmap index or bitmap heap scan? An index being present does not imply it was used.
  2. Compare estimates with observations: find estimated and actual rows in the same node; interpret loops when nodes run more than once.
  3. Read the condition: Index Cond, Recheck Cond and Filter tell you where predicates appear in this plan.
  4. Look at buffers and timing in context: cache state, scale, configuration and query execution affect observations. Repeat tests on representative data and hardware.

The full raw plans and a repeat run were retained alongside the example. A second local session produced the same row counts and scan types with different execution times; it does not establish behavior in other environments.

Try it yourself

Change the upper boundary from 900 to 10, then to 500, and inspect each plan. Which scan does your environment choose? Run each query more than once and record the data distribution, PostgreSQL version and result. Do not force a particular plan and assume it will remain optimal in production. To finish, close the session; its temporary table is removed automatically.

Continue learning

For more hands-on SQL, query plans and PostgreSQL, see Practical SQL with PostgreSQL: From Queries to Real Projects. Coupon availability may change. The course uses the synthetic TrainingHub database, while this article uses a separate temporary dataset.

See the PostgreSQL course overview for the complete learning path, prerequisites and more free SQL tutorials.