IMEN891K / IDSC501 / AXGS-501 · Data Engineering · Fall 2026

6. SQL I: Basics

Sangwoo Mo · POSTECH
Industrial & Management Engineering

Where We Are

PART IPART IIPART IIICollection and PreparationLec 2-5SQLLec 6-8NoSQLLec 9-10Big DataLec 11-13Monitoring and UpdatesLec 14-17

Outline: SQL I

01

Read a Table

find rows and choose columns

02

Refine a Result

remove repeats, sort and keep top rows

03

Handle Missing Values

choose how absent prices affect the result

04

Write Safely

keep constraints and related changes together

01 · Read a Table

01

Read a Table

find rows and choose columns

02

Refine a Result

remove repeats, sort and keep top rows

03

Handle Missing Values

choose how absent prices affect the result

04

Write Safely

keep constraints and related changes together

Tables and SQL

A database stores related tables; SQL reads and changes their rows
TermToday
TableNamed rows and columns
SchemaColumn names, types and constraints
SQLThe language for reading and writing tables
SQLiteThe database engine running inside this deck

Schema and RowsA schema defines the columns; rows supply their values

Schema: the definition

Product
  pname         TEXT, primary key
  price         REAL
  category      TEXT
  manufacturer  TEXT

Rows: the stored values

pnamepricecategory
Gizmo19.99Gadgets
PowerGizmo29.99Gadgets
SingleTouch149.99Photography
MultiTouch203.99Household
One definition, many product rows

Case study: A Product Catalogue

Product(pname, price, category, manufacturer)
pnamepricecategorymanufacturer
Gizmo19.99GadgetsGizmoWorks
PowerGizmo29.99GadgetsGizmoWorks
SingleTouch149.99PhotographyCanon
MultiTouch203.99HouseholdHitachi
Find products by category, compare prices and prepare a short price list
Four products form the input for filtering, choosing columns and sorting prices

SELECT, FROM and WHEREThe question names one input table, a row condition and output columns

FROM

Read Product

WHERE

Keep Gadgets

SELECT

Show name and price

SELECT pname, price
FROM Product
WHERE category = 'Gadgets';
Read the table, keep matching rows, then choose columns

SQL Query: Selection

Before: four products

pnamecategory
GizmoGadgets
PowerGizmoGadgets
SingleTouchPhotography
MultiTouchHousehold

After: two Gadgets

pnamecategory
GizmoGadgets
PowerGizmoGadgets
SELECT pname, category FROM Product
WHERE category = 'Gadgets';
Selection keeps matching rows; their columns remain available

SQL Query: Projection

Input: already filtered rows

pnamepricecategory
Gizmo19.99Gadgets
PowerGizmo29.99Gadgets

Output: two chosen columns

pnameprice
Gizmo19.99
PowerGizmo29.99
SELECT pname, price FROM Product
WHERE category = 'Gadgets';
Projection chooses columns from the rows already selected

A Query Produces a Table

Product: four rows

pnameprice
Gizmo19.99
PowerGizmo29.99
SingleTouch149.99
MultiTouch203.99

Answer: two rows

pnameprice
Gizmo19.99
PowerGizmo29.99
SELECT pname,price FROM Product WHERE category='Gadgets';
The result is another table with named columns and selected rows

Strings and Conditions

SELECT pname, price
FROM Product
WHERE category = 'Gadgets' AND price > 20;
  ↑ strings in single quotes

Parentheses Change the Filter

SELECT pname,category,price FROM Product
WHERE (category='Gadgets' OR category='Photography')
  ↑ OR inside the parentheses first, then AND
  AND price>20;
pnamecategoryprice
PowerGizmoGadgets29.99
SingleTouchPhotography149.99
Parentheses apply the price condition to both selected categories

IN Lists the Allowed Values

SELECT pname,category FROM Product
WHERE category IN ('Gadgets','Photography');
  ↑ any value in the list
pnamecategory
GizmoGadgets
PowerGizmoGadgets
SingleTouchPhotography
IN selects the three products in either named category

Recap: The Product Table

pnamepricecategorymanufacturer
Gizmo19.99GadgetsGizmoWorks
PowerGizmo29.99GadgetsGizmoWorks
SingleTouch149.99PhotographyCanon
MultiTouch203.99HouseholdHitachi
Predict the remaining rows and output columns before writing the query

Demo: Read the Product Table

  1. Return the name and price of every Gadget product
  2. Keep only Gadget products priced above 20
Ctrl/⌘ + Enter
Query result
Write a query on the left, then Run.

Answer: Read the Product Table

SELECT pname,price FROM Product
WHERE category='Gadgets' AND price>20;
pnameprice
PowerGizmo29.99
Adding the price condition keeps PowerGizmo and removes Gizmo

02 · Refine a Result

01

Read a Table

find rows and choose columns

02

Refine a Result

remove repeats, sort and keep top rows

03

Handle Missing Values

choose how absent prices affect the result

04

Write Safely

keep constraints and related changes together

Caveat: Duplicates in the Output

Four product rows

pnamecategory
GizmoGadgets
PowerGizmoGadgets
SingleTouchPhotography
MultiTouchHousehold

SELECT category

category
Gadgets
Gadgets
Photography
Household

SELECT DISTINCT category

category
Gadgets
Photography
Household
Two products share Gadgets; selecting a column keeps both copies until DISTINCT removes one

ORDER BY: Sorting the Results

SELECT   PName, Price, Manufacturer
FROM     Product
WHERE    Category='Gadgets' AND Price > 20
ORDER BY Price, PNameby Price, ties by PName
Ties are broken by the second attribute on the ORDER BY list, etc.
Ordering is ascending, unless you specify the DESC keyword.

LIMIT and Deterministic Order

SELECT pname, price FROM Product
ORDER BY price DESC, pname ASC LIMIT 2;
  ↑ first 2 rows after the sort
pnameprice
MultiTouch203.99
SingleTouch149.99
Sort before limiting; an explicit tie-breaker makes the chosen rows reproducible

Recap: Categories and Prices

pnamepricecategory
Gizmo19.99Gadgets
PowerGizmo29.99Gadgets
SingleTouch149.99Photography
MultiTouch203.99Household
The input repeats Gadgets twice; the two Gadget prices are different

Demo: Prepare a Price List

  1. List Gadget names and prices, highest price first; return only the first product
  2. List each category once with DISTINCT
Ctrl/⌘ + Enter
Query result
Write a query on the left, then Run.

Answer: Prepare a Price List

SELECT pname,price FROM Product
WHERE category='Gadgets'
ORDER BY price DESC,pname LIMIT 1;
pnameprice
PowerGizmo29.99
ORDER BY defines the order; LIMIT keeps the first row

Answer: Unique Categories

SELECT DISTINCT category FROM Product;
category
Gadgets
Photography
Household
Two Gadgets inputs become one category row

03 · Handle Missing Values

01

Read a Table

find rows and choose columns

02

Refine a Result

remove repeats, sort and keep top rows

03

Handle Missing Values

choose how absent prices affect the result

04

Write Safely

keep constraints and related changes together

NULL and Missing Values

pnameprice
Gizmo19.99
PowerGizmoNULL
SingleTouch149.99
MultiTouch203.99
NULL means the price is missing; test it with IS NULL
This copy has a missing PowerGizmo price; NULL is different from a zero price

NULL Comparisons

ExpressionResult
NULL = NULLUNKNOWN
NULL <> 5UNKNOWN
NULL IS NULLTRUE
NULL IS NOT NULLFALSE
WHERE keeps only TRUE; FALSE and UNKNOWN both drop the row
An absent value needs IS NULL; equality cannot identify a missing match

Caveat: Missing Prices in a Filter

Missing-price input

pnameprice
Gizmo19.99
PowerGizmoNULL
SingleTouch149.99
MultiTouch203.99

WHERE price > 20

pnameprice
SingleTouch149.99
MultiTouch203.99

PowerGizmo: the price is unknown, so the comparison cannot be true

PowerGizmo disappears because its price is unknown; NULL does not become zero

Recap: The Missing-Price Copy

pnamepricecategorymanufacturer
Gizmo19.99GadgetsGizmoWorks
PowerGizmoNULLGadgetsGizmoWorks
SingleTouch149.99PhotographyCanon
MultiTouch203.99HouseholdHitachi
PowerGizmo is the only product with a missing price in this copy

Demo: Handle Missing Prices

  1. Find products with a missing price
  2. Return products priced above 20, and also include products with a missing price
Ctrl/⌘ + Enter
Query result
Write a query on the left, then Run.

Answer: Handle Missing Prices

SELECT pname,price FROM Product
WHERE price>20 OR price IS NULL;
pnameprice
PowerGizmoNULL
SingleTouch149.99
MultiTouch203.99
The explicit NULL condition includes PowerGizmo alongside the two known prices above 20

04 · Write Safely

01

Read a Table

find rows and choose columns

02

Refine a Result

remove repeats, sort and keep top rows

03

Handle Missing Values

choose how absent prices affect the result

04

Write Safely

keep constraints and related changes together

Keys and References

cnamestockpricecountry
GizmoWorks25.0USA
Canon65.0Japan
Hitachi15.0Japan
pnamemanufacturer
GizmoGizmoWorks
PowerGizmoGizmoWorks
SingleTouchCanon
MultiTouchHitachi
A primary key identifies a row; a foreign key requires an existing referenced key
Each product names one existing company; the key columns identify the referenced rows

Entity–Relationship (ER) DiagramAn ER diagram describes entities, attributes and relationships before table design

CompanyProductmakesCNameStockPriceCountryPNamePriceCategory1NEntityRelationshipAttributeKey (Underlined)Cardinality 1 : N
One company makes many products: 1 on one side, N on the other

ER to TablesEach relationship becomes either a foreign key column or a table of its own

1 : NCompanyProductmakes1N⇒CompanyCNameStockPriceCountryProductPNamePriceCategoryManufacturerForeign Key on the N SideN : MProductCategoryinNM⇒ProductPNamePriceProductCategoryPNameCatNameCategoryCatNameDepartmentJunction Table: One Row per Pair
Use a foreign key for 1:N and a junction table for N:M

Junction TableIf a product may sit in several categories, Category leaves Product and gets its own table

Product
PNameManufacturer
GizmoGizmoWorks
PowerGizmoGizmoWorks
SingleTouchCanon
MultiTouchHitachi
ProductCategory
PNameCatName
GizmoGadgets
PowerGizmoGadgets
SingleTouchPhotography
SingleTouchGadgets
MultiTouchHousehold
Category
CatNameDepartment
GadgetsElectronics
PhotographyElectronics
HouseholdHome
ProductCategory: PRIMARY KEY (PName, CatName) · PName → Product.PName · CatName → Category.CatName
SingleTouch has two category links but one product row

A Composite Key Identifies a Pair

CREATE TABLE ProductCategory (
  pname TEXT NOT NULL REFERENCES Product(pname),
  catName TEXT NOT NULL,
  PRIMARY KEY (pname,catName)the pair is unique
);

CREATE TABLE and INSERT

CREATE TABLE Product (
  pname TEXT PRIMARY KEY NOT NULL,
  price REAL, category TEXT, manufacturer TEXT NOT NULL,
  FOREIGN KEY (manufacturer) REFERENCES Company(cname)
    ↑ must exist in Company
);
INSERT INTO Product VALUES ('Gizmo',19.99,'Gadgets','GizmoWorks');

Caveat: A Repeated Primary Key

INSERT INTO Product VALUES ('Gizmo',99,'Gadgets','GizmoWorks');
SQLite says
UNIQUE constraint failed: Product.pname
A repeated product key fails even when the other values differ

UPDATE and DELETE

UPDATE Product SET price = 24.99 WHERE pname = 'Gizmo';
  ↑ WHERE picks the row to change
SELECT pname, price FROM Product;
pnameprice
Gizmo24.99
PowerGizmo29.99
SingleTouch149.99
MultiTouch203.99
DELETE FROM Product WHERE pname = 'Gizmo';
-- without WHERE, UPDATE or DELETE affects every row
The condition identifies the write target; Gizmo changes while the other prices remain

Caveat: A Write Without WHERE

UPDATE Product SET price=24.99;
  ↑ no WHERE: every row changes
SELECT pname,price FROM Product;
pnameprice
Gizmo24.99
PowerGizmo24.99
SingleTouch24.99
MultiTouch24.99
All four prices change when UPDATE has no target condition

Caveat: Deleting a Referenced Company

DELETE FROM Company WHERE cname='GizmoWorks';
SQLite says
FOREIGN KEY constraint failed
A company referenced by products cannot be deleted under the default policy

Transactions

AcctBalance
a1020,000
a2015,000
Transfer $3k from a10 to a20:
1. Debit $3k from a10
2. Credit $3k to a20
AcctBalance
a1017,000
a2018,000
A transaction commits related changes together; ROLLBACK cancels uncommitted changes
Both balance changes must complete together; one completed change would lose money

ACID Describes Transaction Guarantees

PropertyMeaning
AtomicityRelated changes succeed or fail together
ConsistencyDeclared constraints hold after the transaction
IsolationIsolation level controls concurrent observations
DurabilityCommitted work survives a failure
ACID connects the write boundary to constraints, concurrency and recovery

Caveat: A Crash Between Two WritesTwo separately committed writes can leave a half-finished transfer

Before

AccountBalance
a1020,000
a2015,000

Debit only: crash

AccountBalance
a1017,000
a2015,000

Both writes

AccountBalance
a1017,000
a2018,000
The debit-only state loses 3,000 from the combined balance

BEGIN, COMMIT and ROLLBACK

BEGIN;
UPDATE Product SET price=24.99 WHERE pname='Gizmo';
SELECT pname,price FROM Product WHERE pname='Gizmo';
ROLLBACK;undo everything since BEGIN
SELECT pname,price FROM Product WHERE pname='Gizmo';

Recap: Valid Writes

cname
Canon
GizmoWorks
Hitachi
pnamepricemanufacturer
Gizmo19.99GizmoWorks
PowerGizmo29.99GizmoWorks
SingleTouch149.99Canon
MultiTouch203.99Hitachi
Gizmo starts at 19.99; Google is absent from Company

Demo: Change a Price Safely

  1. Change Gizmo to 24.99 inside a transaction, inspect it, then roll back and inspect it again
  2. Try inserting a product made by Google, which is absent from Company
Ctrl/⌘ + Enter
Query result
Write a query on the left, then Run.

Answer: Roll Back a Price Change

BEGIN;
UPDATE Product SET price=24.99 WHERE pname='Gizmo';
SELECT price FROM Product WHERE pname='Gizmo';
ROLLBACK;
SELECT price FROM Product WHERE pname='Gizmo';
price
19.99
ROLLBACK restores Gizmo to 19.99 in the current transaction

Answer: A Missing Manufacturer

INSERT INTO Product VALUES('NewGizmo',10,'Gadgets','Google');
SQLite says
FOREIGN KEY constraint failed
The foreign key rejects a manufacturer absent from Company

Takeaway: SQL I

1A query defines which rows and columns answer the question
2Duplicates, order and missing values change what the result means
3Keys constrain valid data; transactions keep related writes together
← → / Space · S notes · O overview · F fullscreen · number + Enter
Speaker notes