smartyfy.mrindigi.com

Databases & SQL Master Course — 110. PostgreSQL Porting Practice Lab

Lesson 110 PostgreSQL Porting Practice Lab

Verification scope and lab safety

PostgreSQL 18 only. These scripts were checked against official documentation but were not executed on that engine in the authoring environment. Every result below is a reasoned expectation, not observed output. Use a dedicated disposable local lab with the required privileges, never an existing application database. No server installation, credential changes, or external database operation is part of this lesson.

Prerequisites and objectives

Complete Lessons 101–109 and the earlier SQLite reporting lessons. You will port a small customer-order report by defining a shared result contract, identifying deliberate type changes, testing empty groups and date boundaries, and recording which evidence comes from SQLite execution versus PostgreSQL documentation review.

Write the acceptance contract first

The report must include every customer, count paid orders, sum their amounts in integer cents, and show zero for a customer without paid orders. It must order customers by identity. The reporting window is half-open: include dates on or after the start and before the end. These requirements are independent of any engine’s preferred syntax.

Integer cents avoid introducing decimal rounding changes during this particular port. This is a chosen domain with whole cents, not a universal monetary model. A system requiring fractional minor units would need a different contract. PostgreSQL uses date for the order date and boolean for paid; the SQLite baseline uses canonical date text and constrained integer flags.

The destination fixture deliberately includes an unpaid order and a customer with no orders. Without those rows, an incorrect filter placement could appear correct. A porting test should challenge semantic boundaries, not merely repeat a happy-path example that every candidate query passes.

Build the destination fixture

Run this only in the dedicated disposable PostgreSQL 18 lab. The source schema is described for comparison; the SQL block below is the PostgreSQL destination. Keep execution evidence separately labeled. The authoring environment executed the shared report logic in SQLite, but PostgreSQL execution remains pending.

BEGIN;
CREATE TEMP TABLE lab_customers110 (
 id integer PRIMARY KEY, name text NOT NULL
) ON COMMIT DROP;
CREATE TEMP TABLE lab_orders110 (
 id integer PRIMARY KEY,
 customer_id integer NOT NULL REFERENCES lab_customers110(id),
 ordered_on date NOT NULL,
 amount_cents integer NOT NULL CHECK (amount_cents >= 0),
 paid boolean NOT NULL
) ON COMMIT DROP;
INSERT INTO lab_customers110 VALUES (1,'Ada'),(2,'Ben'),(3,'Cy');
INSERT INTO lab_orders110 VALUES
 (101,1,'2026-10-01',1500,true),
 (102,1,'2026-10-02',1800,true),
 (103,2,'2026-10-02',900,false),
 (104,2,'2026-10-03',500,true);

Preserve outer-join meaning

The paid condition belongs in the join’s matching rule because unpaid orders should not contribute while every customer remains visible. COUNT of the child identity ignores a NULL-extended child. COUNT of all rows would incorrectly report one order for Cy. COALESCE gives the empty paid total its required zero value.

SELECT c.id, COUNT(o.id) AS paid_orders,
 COALESCE(SUM(o.amount_cents), 0) AS paid_cents
FROM lab_customers110 AS c
LEFT JOIN lab_orders110 AS o
 ON o.customer_id = c.id AND o.paid = TRUE
GROUP BY c.id ORDER BY c.id;
Reasoned PostgreSQL report; same shared logic observed in SQLite
Customer ID Paid orders Paid total (cents)
1 2 3300
2 1 500
3 0 0

Matching output is one acceptance criterion, not the whole migration. PostgreSQL has different types, permissions, concurrency behavior, and transaction-error recovery. A SQLite report run cannot certify those destination behaviors. Keep a migration record with each assumption, its destination test, and an honest status such as observed, reasoned, or pending.

Worked practice

Exercise 1

Compute the total paid amount directly and reconcile it with the customer report.

Worked solution
SELECT SUM(amount_cents) AS paid_cents
FROM lab_orders110 WHERE paid = TRUE;

The expected total is 3,800 cents: 1,500 plus 1,800 plus 500. The unpaid 900-cent order is excluded. Adding the customer report totals gives the same result. This reconciliation catches duplicated child rows or missing eligible orders that a row-count check alone might miss.

Exercise 2

Restrict paid orders to 1 October inclusive through 3 October exclusive while preserving every customer.

Worked solution
SELECT c.id, COUNT(o.id), COALESCE(SUM(o.amount_cents),0)
FROM lab_customers110 AS c
LEFT JOIN lab_orders110 AS o ON o.customer_id = c.id
 AND o.paid = TRUE
 AND o.ordered_on >= DATE '2026-10-01'
 AND o.ordered_on < DATE '2026-10-03'
GROUP BY c.id ORDER BY c.id;

The expected Ben total becomes zero because his paid order falls exactly on the excluded end date. The unpaid order inside the window still does not qualify. Keeping both date predicates in ON preserves Ben and Cy. A BETWEEN predicate would include both endpoints and would implement a different window.

Exercise 3

Identify customers with no orders of any payment status.

Worked solution
SELECT c.id FROM lab_customers110 AS c
WHERE NOT EXISTS (SELECT 1 FROM lab_orders110 AS o WHERE o.customer_id = c.id)
ORDER BY c.id;

Only Cy qualifies. Ben has both paid and unpaid orders, so he is not a customer without orders even when his paid report total for the narrower window is zero. Define the absence question precisely before choosing a predicate; zero eligible revenue and no order history are different conditions.

Exercise 4

Verify the destination rejects an orphan order, recover, and end the lab.

Worked solution
SAVEPOINT trial;
INSERT INTO lab_orders110 VALUES (105,99,DATE '2026-10-02',100,true);
-- Expected error: run recovery below after observing it.
ROLLBACK TO SAVEPOINT trial;
RELEASE SAVEPOINT trial;
SELECT COUNT(*) FROM lab_orders110;
ROLLBACK;

The proposed customer does not exist, so the foreign key should reject the row. This assertion must eventually be executed on PostgreSQL itself. A successful SQLite foreign-key test would establish only the source environment’s behavior. Record the PostgreSQL result as pending until the actual destination run provides evidence.

Build a migration evidence checklist

For each report, record the source query, destination query, fixture, expected rows, and actual engine/version results. Add negative tests for invalid types and constraints, and verify how the client handles a failed transaction. Include session time zone or collation when those settings can alter the result. A report that ignores these settings may pass today and drift under a different connection.

The shared baseline here was executed with SQLite 3.53.1 using foreign-key enforcement enabled and an integer paid flag constrained to zero or one. Its observed report rows and total match the table above. Those observations support the relational calculation only. No PostgreSQL parser, date coercion, Boolean storage, catalog, or savepoint behavior was executed by that baseline.

Pitfalls and summary

Do not measure migration success by the absence of syntax errors alone. Avoid silently changing NULL to zero, moving outer-join filters into WHERE, widening a half-open date window, or dropping a constraint because the import becomes easier. Treat each such change as a requirement decision that needs evidence.

A careful port preserves meaning before optimizing or adopting engine-specific shortcuts. This lab supplies destination scripts and expected outcomes, plus a separately executed shared SQLite baseline. The final acceptance step is a recorded PostgreSQL run in the disposable lab, followed by investigation of every mismatch rather than a blanket compatibility claim.

Knowledge check

Question 1

Why is the paid predicate in the LEFT JOIN condition?

  1. Unpaid orders should be excluded without dropping customers
  2. It makes COUNT(*) ignore the NULL-extended row automatically
  3. It is equivalent to an outer WHERE paid = TRUE for customers without matches
  4. It converts unmatched customers into actual zero-valued order rows
Answer and explanation

A. The matching rule limits eligible children while the left join preserves all parents.

Question 2

Why does the report use COUNT(o.id) instead of COUNT(*)?

  1. COUNT(o.id) automatically removes repeated non-NULL order identities
  2. The child identity is NULL for a preserved customer with no match
  3. COUNT(*) excludes orders with zero amounts
  4. COUNT(o.id) counts customers independently of join multiplicity
Answer and explanation

B. Counting a non-NULL child key avoids counting the NULL-extended placeholder row as an order.

Question 3

Which order date is excluded by the stated half-open window?

  1. 2026-10-03
  2. 2026-10-01, because the start predicate is exclusive
  3. 2026-10-02, because the end is interpreted as the previous full day
  4. Neither boundary, because every date range is inclusive
Answer and explanation

A. The end predicate is strictly less than 3 October, so that boundary is excluded.

Question 4

What does the executed SQLite baseline establish?

  1. The PostgreSQL destination parser has accepted its complete setup
  2. The destination date and Boolean conversions have been observed
  3. The shared relational calculation works for its tested SQLite fixture
  4. PostgreSQL transaction-error recovery has been verified by the SQLite run
Answer and explanation

C. Evidence must stay attached to the engine and behavior actually exercised.

Question 5

Why is Cy the only result of the no-orders query?

  1. Ben also qualifies because his paid total is zero in the narrower window
  2. Ada qualifies because EXISTS removes duplicate customer matches
  3. Every customer with an unpaid order qualifies regardless of paid orders
  4. Cy has no related order row of any payment status
Answer and explanation

D. NOT EXISTS tests any related order, independently of paid-report filters.

Dialect verification notes

The target is PostgreSQL 18. Engine execution remains pending. SQLite was not used as a substitute for executing these dialect-specific scripts. Record actual server version, session settings, results, and errors when running the local lab. Python is not a learner prerequisite.

Primary references