IntermediateData Modeling · 22 min · 12 challenges

Schema Types

A merchant on Stripe sells in Seattle, Tokyo and Kuwait City. Stripe's API takes each charge as an integer in the currency's smallest unit: 500 usd is $5.00, 500 jpy is 500 yen, 5000 kwd is 5 dinars. At payout, each currency's daily total matches the bank to the last unit. A float column would drift by fractions, and a 2-decimal column would round a 2.995 dinar price.

The FLOAT Money Bug

Daily Life
Interviews

An orders table stores line_total as DOUBLE. A customer buys 3 stickers at $0.10 each, and the finance check SUM(line_total) = 0.30 returns false. Every row looks right on screen, and the sum is wrong in the 17th decimal place.

SELECT
CAST(0.1 AS DOUBLE) + CAST(0.2 AS DOUBLE) AS double_sum,
DECIMAL '0.1' + DECIMAL '0.2' AS decimal_sum
double_sumdecimal_sum
0.300000000000000040.3

Why 0.10 has no exact DOUBLE

DOUBLE and REAL are floating-point types, often called floats. They store a number in binary, as a sum of halves, quarters, eighths and so on. A value like 0.5 or 0.25 fits exactly. A value like 0.1 never ends in binary, the way one-third never ends in decimal as 0.3333. The engine keeps the first 53 binary digits and drops the rest, so the stored value is 0.1000000000000000055 and change.

Each stored value is off by a tiny amount, and arithmetic accumulates those amounts. Sum 1,000,000 rows of 0.10 one after another as DOUBLE and the total is 100000.00000133288, where the invoice says 100000.00.

Order matters too. (0.1 + 0.2) + 0.3 gives 0.6000000000000001, and 0.1 + (0.2 + 0.3) gives 0.6. An engine that splits a table across several machines adds rows in whatever order the machines finish, so the same SUM over the same rows can return different totals on 2 runs. A revenue report that changes between refreshes is the usual first symptom.

3 numeric families

FamilyTypesStoresUse for
IntegerSMALLINT, INTEGER, BIGINTWhole numbers, exactCounts, quantities, keys, money in cents
Fixed-pointDECIMAL(p, s)Decimal digits, exactPrices, tax rates, exchange rates
Floating-pointREAL, DOUBLEBinary approximationSensor readings, distances, model scores

Ask one question of every numeric column: was this value counted, priced, or measured? Counted values are integers. Priced values need exact fractions. Measured values, such as a temperature of 21.4 degrees from a sensor accurate to 0.1 degrees, were approximate before they reached the table, and DOUBLE loses nothing the instrument had.

Sizing an integer

TypeBytesLargest value
SMALLINT232,767
INTEGER42,147,483,647
BIGINT89,223,372,036,854,775,807

An integer column that passes its ceiling breaks writes: the insert errors, or on some engines the value wraps to a negative number. INTEGER is enough for quantity on an order line. It is too small for the key of a table that gains 5,000,000 rows a day, which runs out of values in under 430 days. Keys and money in cents get BIGINT. The extra 4 bytes per row cost less than one emergency migration.

DECIMAL(p, s) and money

DECIMAL(p, s) stores p total digits with s of them after the decimal point. DECIMAL(12, 2) holds up to 9,999,999,999.99. Arithmetic on it is exact decimal arithmetic, so 0.10 + 0.20 is 0.30 and equality checks work.

Scale is a decision about the smallest amount the business tracks. US dollars have 2 decimal places. Japanese yen have 0. Kuwaiti dinars have 3, so DECIMAL(12, 2) cannot hold 1.125 KWD: depending on the engine, the write is rejected or the value is rounded to 1.13 and the ledger no longer matches the bank. An 8.875% sales tax on $19.99 comes to 1.7741125, which also needs a rounding rule before it fits 2 places.

Integer minor units
  • amount_minor BIGINT plus currency_code CHAR(3)
  • 1999 with USD means $19.99, and 1125 with KWD means 1.125 dinars
  • Every sum and comparison is integer arithmetic
  • A reader needs each currency's decimal places to display an amount
DECIMAL with spare scale
  • amount DECIMAL(18, 4) plus currency_code CHAR(3)
  • 19.9900 reads as the amount with no conversion
  • Scale 4 covers 3-decimal currencies with a digit to spare
  • Division and tax still need an explicit rounding rule
Both designs are exact, and both keep the currency beside the amount.
Multiple Choice

A refunds table must store refunds in US dollars, Japanese yen and Kuwaiti dinars, and finance compares its daily total to the bank statement with =. Which column design holds every refund exactly?

Float bugs stay invisible in testing because small sums round correctly on screen. They surface in production as a reconciliation that is off by a cent on a table too large to inspect.

String Types & Platform Traps

Daily Life
Interviews

A signup form in Wales sends the village name Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch. It has 58 letters. The city column was declared VARCHAR(50) because 50 looked generous. What happens next depends on the engine: the signup fails with an error, or the name is cut at 50 characters and saved without a warning.

3 text types

TypeBehaviorFits
CHAR(n)Always n characters, padded with spacesFixed-width codes such as country and currency
VARCHAR(n)Up to n characters, stores what is writtenNames, emails and titles with a known ceiling
VARCHARNo declared limitFree text: reviews, notes, descriptions

A variable-length column stores the characters present, so VARCHAR(500) holding Ana takes the same space as VARCHAR(10) holding Ana. The declared length is a limit on writes. Setting it low saves no storage and turns away legitimate customers.

CHAR(n) pads. The value US in a CHAR(5) column is stored as US followed by 3 spaces. Engines disagree on whether those spaces count in comparisons and in length, so a join between a CHAR(5) code and a VARCHAR code can match nothing and raise no error. Reserve CHAR for codes whose width a standard fixes, and declare that exact width.

Sizing from the real world

Size a text column from a standard when one exists, and from the data when none does. A sample of your own contacts is neither.
ColumnReal ceilingReasonable type
email254 characters, from the mail standardsVARCHAR(254)
phone_number15 digits plus a leading + in E.164 formVARCHAR(16)
country_code2 letters in ISO 3166CHAR(2)
currency_code3 letters in ISO 4217CHAR(3)
full_nameNo standard, and 100-character names existVARCHAR(200) or more
postal_codeLetters, spaces and leading zerosVARCHAR(12)
When no standard exists, query the longest value you already hold, then allow several times that. A limit is there to catch garbage, such as a 40,000-character paste into a name field, and belongs far above any real value.

Numbers that are text

A postal code, a phone number and an account number are made of digits and are never added or averaged. Declared as INTEGER, the Boston postal code 02134 is stored as 2134, the phone number +44 20 7946 0958 fails to load, and a 20-digit account number overflows even BIGINT. The test: if arithmetic on the column is meaningless, the column is text.

Platform traps

The same CREATE TABLE statement behaves differently from one engine to the next. Test these 4 behaviors on any engine before trusting a text column in it.

4 behaviors to test
  • Bytes or charactersWhat n countsSome engines count VARCHAR(n) in characters and others in bytes. Text outside basic Latin takes 2 to 4 bytes per character in UTF-8, so a byte-counted limit shrinks for most of the world's names.
  • Error or truncationWhat overflow doesSome engines reject a value that is too long. Others cut it to fit and report success, and a truncated email address still looks like an email address.
  • Case sensitivityWhat = means'Ana@x.com' = 'ana@x.com' is true where comparison ignores case and false where it does not, which changes what a uniqueness rule on email allows.
  • Empty string or NULLWhat '' storesSome engines store an empty string as NULL. A filter on middle_name = '' then matches no rows at all.
SELECT
city,
LENGTH(city) AS characters,
LENGTH(TO_UTF8(city)) AS bytes
FROM (
VALUES 'Lima', 'Zürich', '東京'
) AS t(city)
citycharactersbytes
Lima44
Zürich67
東京26

On an engine that counts bytes, VARCHAR(6) accepts Lima, rejects Zürich, and holds 2 Japanese characters where the designer expected 6.

Multiple Choice

An engine counts VARCHAR length in bytes, and city is declared VARCHAR(8). Which city name is too long for the column?

Run that length query on your own engine with one accented name and one non-Latin name before sizing anything. The result decides whether every limit in the schema means what its author intended.

Temporal Types & DST

Daily Life
Interviews
On 1 November 2026, clocks in New York ran through 01:00 to 01:59 twice. At 02:00 daylight time they fell back to 01:00 standard time. A courier app that stores pickup and delivery as local clock readings recorded a delivery that finished 20 minutes before it started.

4 temporal types

TypeOne value meansExample
DATEA calendar day, with no time of day2026-11-01
TIMESTAMPA clock reading, with no zone attached2026-11-01 01:30:00
TIMESTAMP WITH TIME ZONEOne instant on the shared global timeline2026-11-01 05:30:00 UTC
INTERVAL or integerA length of time40 minutes, or 2400000 ms

The distinction that prevents most bugs is instant versus clock reading. An instant is a point on the timeline that everyone on Earth shares, such as the moment a payment cleared. A clock reading is what a wall clock showed somewhere, and it identifies an instant only when a zone comes with it. The reading 2026-11-01 01:30:00 with no zone names 2 separate instants in New York alone.

The repeated hour

Instant in UTCNew York clockOffset
05:1501:15UTC-4, daylight
05:4501:45UTC-4, daylight
06:1501:15UTC-5, standard
06:4501:45UTC-5, standard
Sorted by the UTC column, the 4 events are in the order they happened. Sorted by the New York column, the 2 readings of 01:15 tie, and the event from 06:15 UTC lands ahead of the event from 05:45 UTC. Hourly counts double for the 01:00 hour, and any duration that crosses the change is off by 60 minutes.
SELECT
DATE_DIFF(
'minute',
TIMESTAMP '2026-11-01 05:50:00 UTC',
TIMESTAMP '2026-11-01 06:30:00 UTC'
) AS utc_minutes,
DATE_DIFF(
'minute',
TIMESTAMP '2026-11-01 01:50:00',
TIMESTAMP '2026-11-01 01:30:00'
) AS local_minutes
utc_minuteslocal_minutes
40-20
The spring change removes an hour. On 8 March 2026, New York clocks jumped from 02:00 to 03:00, so 02:30 never appeared on a clock there, and a job scheduled for 02:30 local time had no moment to run.
Multiple Choice

A night shift in New York clocks in at 23:00 on 7 March 2026 and out at 07:00 on 8 March, the night clocks jump from 02:00 to 03:00. Both readings are stored as TIMESTAMP with no zone. How long was the shift, and what does subtracting the 2 columns report?

Events in UTC, plans in local time

Something that happened
  • Store the instant: created_at TIMESTAMP WITH TIME ZONE, written in UTC
  • Order placed, payment captured, package scanned
  • Sorting and subtraction are correct in every zone
Something that is planned
  • Store the clock reading and the zone name in 2 columns
  • Opening hours, an appointment, a 09:00 daily report
  • The instant is computed when needed, under the rules then in force

A zone name such as America/New_York and an offset such as -05:00 carry different information. The offset is a fact about one instant. The name is a set of rules that yields the offset for any date, including dates after a government changes those rules. Store the name.

Dates and durations

A DATE answers 'which day', and the answer depends on where you stand. An order placed at 2026-11-23 02:00 UTC was placed on 22 November in Los Angeles, at 18:00. A column named order_date needs one documented zone, the same for every row, or daily revenue moves between days depending on who runs the report. A birthday or a contract start is a day by nature and belongs in DATE. Stored as a midnight timestamp, a birthday slips to the previous day when read in a zone west of the writer.

A duration is a quantity. Store it as an integer in a unit the column name states, such as duration_ms BIGINT, or store the start and end instants and subtract. Unnamed units get misread: 1700000000 and 1700000000000 are the same moment counted in seconds and in milliseconds. Calendar lengths resist fixed units. 31 January plus 1 month is 28 February in 2026, so 'monthly' is stored as a rule and applied to a date.

Daylight saving bugs appear on 2 days a year and hide on the other 363. Put one March case and one November case in the test data for every column that holds a time.

ENUM Traps

Daily Life
Interviews

A users table has an is_subscribed BOOLEAN column. Marketing counts subscribers, then counts non-subscribers, and the 2 counts add up to fewer than the number of users. Every row is still in the table. The column has 3 states, and both queries skipped the same one.

A boolean has 3 values

is_subscribedusers
TRUE6
FALSE3
NULL1

WHERE is_subscribed returns 6 rows. WHERE NOT is_subscribed returns 3, because negating NULL gives NULL and a filter keeps only rows that evaluate to true. The 10th user appears in neither list. When a flag has no meaningful 'unknown', declare it NOT NULL with a default, and the extra state cannot exist.

Multiple Choice

A devices table has 20 rows: is_online is TRUE in 12, FALSE in 5 and NULL in 3. What does this query return?

SELECT
COUNT(*) AS offline_devices
FROM devices
WHERE is_online != TRUE

2 more traps come from requirements that grow. A flag such as is_shipped becomes wrong the day an order can also be cancelled or returned, and another flag for each new state produces combinations nobody intended. A flag such as is_deleted records that something happened and discards when. A nullable deleted_at instant answers both questions in one column: NULL means not deleted, and a value says when.

ENUM: a fixed list of values

An enumerated column accepts only values from a declared list, such as pending, shipped, delivered and cancelled. The need is real. Without a list, a free-text status column collects every spelling a writer can produce.

statusorders
shipped41,208
Shipped1,377
SHIPPED212
shiped9
4 spellings of one state force every report to list all 4, and the next misspelling is counted nowhere. 2 designs enforce the list, and they fail in different places.
Native ENUM type
  • The list lives in the column's type definition
  • Adding a value is a schema change, and on some engines it rewrites or locks the table
  • ORDER BY status follows declaration order, so shipped sorts ahead of delivered
  • Some engines export the position number, and a reader sees 2 where the writer meant shipped
Lookup table with a foreign key
  • The list lives in the rows of an order_statuses table
  • Adding a value is one INSERT, with no change to orders
  • Each value can carry a display label, a sort position and an is_final flag
  • The foreign key rejects any status that has no row
orders
order_idPKBIGINT
status_codeFKVARCHAR(20)
placed_atTIMESTAMP WITH TIME ZONE
order_statuses
status_codePKVARCHAR(20)
display_labelVARCHAR(50)
sort_positionSMALLINT
is_finalBOOLEAN

A native ENUM suits lists fixed by the world, such as days of the week. Order states, plan tiers and ticket priorities change with the business, and each belongs in a lookup table, where a new value is a new row.

Multiple Choice

tickets.priority is a native ENUM declared in the order 'high', 'medium', 'low'. The team adds 'urgent', and the engine appends it to the list. A dashboard runs ORDER BY priority to show the most pressing tickets first. Where do urgent tickets appear?

Storing a UUID

Whether a key should be a UUID is a key generation question. The type question is how to store one. A UUID is a 128-bit number, usually written as 32 hex digits with 4 hyphens, and many schemas keep that written form in a text column.
16 bytes
one UUID in a native UUID column
36 bytes
the same UUID stored as text
On a table of 100,000,000 rows with a UUID key and 2 UUID foreign keys, the text form adds 6 GB of storage. Size is the smaller problem. Text compares character by character, and one UUID has several written forms.
SELECT
'A3F1C2D4-5B6E-4F70-8A9B-0C1D2E3F4A5B' = 'a3f1c2d4-5b6e-4f70-8a9b-0c1d2e3f4a5b' AS text_match,
CAST('A3F1C2D4-5B6E-4F70-8A9B-0C1D2E3F4A5B' AS UUID) = CAST('a3f1c2d4-5b6e-4f70-8a9b-0c1d2e3f4a5b' AS UUID) AS uuid_match
text_matchuuid_match
falsetrue

One service writes uppercase, another writes lowercase, and a join between their tables returns no rows and no error. A native UUID column parses both forms to the same 128 bits and rejects strings that are not UUIDs at all, such as an ID with a character missing.

Type Review Framework

Daily Life
Interviews

Every type is a data quality check that runs on each write, cannot be skipped by a hurried pipeline, and costs nothing to operate. A DATE column refuses 2026-02-30. An INTEGER column refuses N/A. A BOOLEAN column refuses maybe. A schema where every column is VARCHAR accepts all 3 and moves the checking into every query that reads the table.

5 questions for every column

Ask them in this order
  • What does one value mean?Meaning and unitPut the unit in the name: weight_grams, duration_ms, amount_minor.
  • Counted, priced, measured or labelled?Type familyCounted is an integer. Priced is exact decimal or integer minor units. Measured is DOUBLE. Labelled is text or a lookup key.
  • What is the largest real value in 10 years?SizeSize integers for growth and text for the longest legitimate value, then add headroom.
  • Can it be missing?NullabilityIf it cannot, declare NOT NULL. If it can, write down what NULL means for this column.
  • What will it be compared with?Matching typesA foreign key takes the exact type of the primary key it references. Between BIGINT and text, whether 123 matches 00123 depends on which side the engine converts.

A review, column by column

A shipments table arrives for review. Each declared type lets through a value the reviewed type refuses.

DeclaredA value it acceptsReviewed
shipment_id VARCHARThe same UUID in 2 spellingsshipment_id UUID
weight DOUBLE2.2, in pounds or kilogramsweight_kg DOUBLE
cost DOUBLE12.989999999cost_minor BIGINT, currency_code CHAR(3)
shipped VARCHARY, yes, TRUE, 1shipped_at TIMESTAMP WITH TIME ZONE
dest_zip INTEGER2134 for the postal code 02134destination_postal_code VARCHAR(12)
created VARCHAR03/04/2026created_at TIMESTAMP WITH TIME ZONE

The created column shows why text is the weakest check. 03/04/2026 is 3 April in London and 4 March in Chicago, and the column accepts both readings along with tomorrow. A temporal type stores one unambiguous value and sorts by time.

What types cannot catch

Types reject values of the wrong shape and accept wrong values of the right shape. The common case is a sentinel: a real-looking value that stands for 'missing', such as -1 for an unknown age, 1970-01-01 for an unknown date, or N/A in a name. 3 customers aged 34, 41 and unknown average 37.5 when the unknown is NULL, because AVG skips NULL. With -1 stored for the unknown, the average is 24.67 and nothing flags it. Store missing as NULL.

Type changes get more expensive as a table grows. Widening INTEGER to BIGINT on a new table is one line. After 2 years of rows it is a rewrite of every row and a change to every job and dashboard that reads the column.

Reviewing a subscriptions tableStep 1
>

A streaming startup built its `subscriptions` table in an afternoon. 2 new requirements arrive, and each one tests a type.

subscriptions
subscription_idUUIDPKuser_idBIGINTFKmonthly_priceDOUBLEis_activeBOOLEANstarted_atTIMESTAMP WITH TIME ZONE

Finance reports that monthly revenue differs in the last decimal places between 2 runs of one query. Next quarter the service launches in Japan and Kuwait. What happens to `monthly_price DOUBLE`?

Run the 5 questions on one table you own this week. A type fixed in review costs one line of SQL.
PUTTING IT ALL TOGETHER

> A ride-hailing company that operates in Chicago prepares to launch in Tokyo and Kuwait City. Its trips table stores fare DOUBLE, rider_name VARCHAR(40), pickup_time TIMESTAMP in Chicago local time, is_completed BOOLEAN and trip_id VARCHAR(36). Every column worked for one city, one currency and one alphabet, and every column breaks on launch day.

fare becomes fare_minor BIGINT with currency_code CHAR(3), so a 1,200 yen fare and a 2.995 dinar fare are both exact whole numbers.
rider_name is resized after checking how the engine counts length, because a 15-character Japanese name needs 45 bytes and fails a 40-byte limit.
pickup_time becomes a UTC instant plus the city's zone name, so trip durations survive the Chicago clock change and Tokyo trips sort correctly beside Chicago trips.
is_completed becomes a status key into a lookup table, because trips can also be cancelled, disputed or refunded.
trip_id moves to a native UUID column, so IDs written in uppercase by one service join to IDs written in lowercase by another.
The 5 review questions, asked before the first row was written, would have caught all 5 columns.
KEY TAKEAWAYS
Counted values are integers, priced values are DECIMAL or integer minor units with a currency code, and measured values are DOUBLE.
Size text from a standard or from the longest real value, and test whether your engine counts bytes, truncates, or ignores case.
Store events as UTC instants, store plans as a local clock reading plus a zone name, and put the unit of every duration in its column name.
A boolean has 3 states unless it is NOT NULL, a changing list of values belongs in a lookup table, and a UUID belongs in a UUID column.
Ask the 5 questions of every column before the first insert, because a type change on a full table is a rewrite.

Choose column types that refuse bad values: exact money, sized text, unambiguous time, honest flags.

Category
Data Modeling
Difficulty
intermediate
Duration
22 minutes
Challenges
12 hands-on challenges

Topics covered: The FLOAT Money Bug, String Types & Platform Traps, Temporal Types & DST, ENUM Traps, Type Review Framework

Lesson Sections

  1. The FLOAT Money Bug (concepts: Data Types)

    Why 0.10 has no exact DOUBLE 3 numeric families Sizing an integer DECIMAL(p, s) and money Both designs are exact, and both keep the currency beside the amount. Float bugs stay invisible in testing because small sums round correctly on screen. They surface in production as a reconciliation that is off by a cent on a table too large to inspect.

  2. String Types & Platform Traps (concepts: Data Types)

    3 text types Sizing from the real world Size a text column from a standard when one exists, and from the data when none does. A sample of your own contacts is neither. When no standard exists, query the longest value you already hold, then allow several times that. A limit is there to catch garbage, such as a 40,000-character paste into a name field, and belongs far above any real value. Numbers that are text Platform traps Run that length query on your own engine with one accented name and one

  3. Temporal Types & DST (concepts: Data Types)

    On 1 November 2026, clocks in New York ran through 01:00 to 01:59 twice. At 02:00 daylight time they fell back to 01:00 standard time. A courier app that stores pickup and delivery as local clock readings recorded a delivery that finished 20 minutes before it started. 4 temporal types The repeated hour Sorted by the UTC column, the 4 events are in the order they happened. Sorted by the New York column, the 2 readings of 01:15 tie, and the event from 06:15 UTC lands ahead of the event from 05:45

  4. ENUM Traps (concepts: Data Types, Key Generation)

    A boolean has 3 values ENUM: a fixed list of values 4 spellings of one state force every report to list all 4, and the next misspelling is counted nowhere. 2 designs enforce the list, and they fail in different places. Storing a UUID Whether a key should be a UUID is a key generation question. The type question is how to store one. A UUID is a 128-bit number, usually written as 32 hex digits with 4 hyphens, and many schemas keep that written form in a text column. On a table of 100,000,000 rows

  5. Type Review Framework (concepts: Data Types, Constraints)

    5 questions for every column A review, column by column What types cannot catch Run the 5 questions on one table you own this week. A type fixed in review costs one line of SQL.