Database & SQL Engineering / SQL & RELATIONAL FUNDAMENTALS / SQL-001
SQL Workbench
Explore concept graphMateri
Problem: database untuk accounts dan transfers harus bisa dibuat ulang dari workspace kosong, tidak bergantung pada GUI, dan hasilnya harus dapat diperiksa lewat enam query yang benar-benar dijalankan.
Mulai: gambar dua tabel: accounts dengan account_id sebagai PRIMARY KEY, dan transfers dengan transfer_id sebagai PRIMARY KEY serta source_account_id dan destination_account_id sebagai dua FOREIGN KEY.
Disposable PostgreSQL database
└── schema cs101_sql001
├── accounts
│ ├── account_id PRIMARY KEY
│ └── owner_label NOT NULL
└── transfers
├── transfer_id PRIMARY KEY
├── source_account_id ──FK──> accounts.account_id
├── destination_account_id ──FK──> accounts.account_id
├── amount NUMERIC(12,2) CHECK(amount > 0)
├── currency CHAR(3)
└── created_at TIMESTAMPTZ
init.sql (DDL + DML + transaction)
↓
inspect.sql (6 SELECT queries)
↓
actual schema + tables + counts + keys + IDR totalStruktur dan enam query yang harus dapat kamu buktikan
| Inspeksi | Objek yang diuji | Hasil dataset contoh |
|---|---|---|
| 1. current_schema() | Schema aktif | cs101_sql001 |
| 2. pg_tables | Tabel yang ada | accounts,transfers |
| 3. COUNT(accounts) | Baris akun | 2 |
| 4. COUNT(transfers) | Baris transfer | 2 |
| 5. information_schema foreign keys | Relasi yang benar-benar dibuat | 2 |
| 6. SUM(amount) WHERE currency=‘IDR’ | Jumlah nominal dengan tipe NUMERIC | 155000.00 |
Gunakan seed transfer 125000.00 IDR dan 30000.00 IDR. Jangan menggabungkan nominal dari currency berbeda. Ini sandbox latihan, bukan double-entry ledger atau bukti transaksi finansial yang aman.
Konsep 1 / 3
Recognize relational tables, rows, primary keys and foreign keys before issuing queries.
A transfer record without a known source and destination account cannot support reproducible reporting or data integrity.
Draw two boxes labeled accounts and transfers, then connect source_account_id to accounts.account_id.
Intuisi utama
Accounts are rows identified by account_id; transfers reference two account IDs and preserve amount/currency as separate typed values.
A relation is a named table of rows. For the starter sandbox, accounts(account_id PK, owner_label) and transfers(transfer_id PK, source_account_id FK, destination_account_id FK, amount NUMERIC, currency, created_at TIMESTAMPTZ) are distinct relations. The two foreign keys link transfer endpoints to existing accounts. This is a teaching schema, not a banking ledger, and it does not enforce balance conservation or transfer authorization. Read each column and constraint as a contract before using SELECT. A CHECK on amount > 0 validates a single row, not total balances across transfers.
Contoh bertahap
A transfer T-100 from account A-01 to A-02 must reference real accounts and store an exact nominal amount.
- Draw accounts and transfers as two tables and label every key.
Mengapa: Separating entities prevents duplicated mutable account facts.
Hasil yang diharapkan: transfers references accounts twice by account_id.
- Mark the primary keys and both foreign keys.
Mengapa: Every transfer endpoint must identify an existing account.
Hasil yang diharapkan: Two declared FK relationships and unique transfer/account identifiers.
- Assign NUMERIC(12,2), CHAR(3) and TIMESTAMPTZ to amount, currency and time.
Mengapa: Type selection documents decimal precision, currency identity and time representation.
Hasil yang diharapkan: An IDR transfer can be inspected without using a binary float.
Konsep 2 / 3
Run a bounded DDL/DML/TCL script via psql twice without duplicating sample data.
Manual GUI setup can conceal dependencies, leave stale rows, and make examples irreproducible for teammates or CI.
Locate labs/SQL-001/init.sql and identify which SQL statements create structure versus rows.
Intuisi utama
DDL defines schema and tables, DML inserts seed rows, BEGIN/COMMIT group the operation, and a schema-qualified name or search_path chooses the namespace.
The authored init.sql creates a dedicated cs101_sql001 schema, two tables, sample account/transfer rows and a fixed transaction around DDL and seed DML. CREATE TABLE IF NOT EXISTS is useful for re-execution, but it does NOT guarantee an existing table has the expected columns; it is not a migration system. INSERT ... ON CONFLICT DO NOTHING prevents duplicate fixture IDs on repeated runs, but a conflicting payload could be silently ignored. Use the script only on a disposable sandbox database. SQL statement categories here: DDL (CREATE), DML (INSERT), DQL (SELECT), TCL (BEGIN/COMMIT). Run psql -X -v ON_ERROR_STOP=1 -f labs/SQL-001/init.sql against your test database, then repeat and inspect. Avoid running these commands on production.
Contoh bertahap
A fresh PostgreSQL database needs two known accounts and two deterministic transfers from versioned SQL.
- Create the dedicated cs101_sql001 schema, followed by accounts then transfers.
Mengapa: The referenced table must exist before its foreign keys can be defined.
Hasil yang diharapkan: The second table references the first without dependency errors.
- Insert account rows before transfer rows with stable IDs.
Mengapa: Foreign-key constraints enforce the relationship at insert time.
Hasil yang diharapkan: Both transfers link to existing accounts.
- Run init.sql twice against the same database.
Mengapa: ON CONFLICT DO NOTHING and table existence guards avoid duplicate sample rows.
Hasil yang diharapkan: Both executions leave exactly two accounts and two transfers.
Konsep 3 / 3
Run six bounded SQL inspection queries and classify the observed schema/data results.
A successful CREATE command does not prove the correct tables, keys, rows or aggregate values were created in the intended schema.
Write SELECT count(*) FROM cs101_sql001.accounts; before reading its expected result.
Intuisi utama
DQL SELECT observes metadata and business rows; search_path or schema qualification ensures queries target the sandbox instead of some similarly named table.
Run labs/SQL-001/inspect.sql using psql -X -v ON_ERROR_STOP=1 -At -f labs/SQL-001/inspect.sql. Its six SELECT queries report current_schema, table names, account count, transfer count, two FK constraints and IDR total. Fixture expects two accounts, two transfers, two foreign keys and IDR 155000.00. The six queries return inspectable observations, not a generic test pass. The CI integration runs on a disposable PostgreSQL 16 container with no published host port and checks replay and fresh database behavior. psql -At emits parseable tuples-only unaligned lines; this is for fixture assertions, not general CSV exports.
Contoh bertahap
You receive init.sql but must determine whether the script put correct rows and keys in the expected schema.
- Run the inspection queries after a successful init.sql.
Mengapa: Avoid reasoning from the mere existence of a SQL file.
Hasil yang diharapkan: The first two SELECTs show the active schema and the exact table names.
- Read the counts, foreign-key metadata and amount sum.
Mengapa: Check both structure and content of the fixture.
Hasil yang diharapkan: Counts 2/2, two foreign keys and IDR 155000.00 match the expected contract.
- Repeat from a new clean database and compare all six results.
Mengapa: Detect dependence on stale state or a particular database setup.
Hasil yang diharapkan: The six observations remain stable across clean and replayed databases.
Sumber resmi PostgreSQL 16
Sumber
Cross-domain connections
Curated relationships for this unit at G1. Proposed edges are suggestions, not prerequisites.
Dashed = proposed relationship; solid = reviewed connection. Only reviewed prerequisites constrain a learning path. Keyboard and text links remain available.