Schema Types
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.
| double_sum | decimal_sum |
|---|---|
| 0.30000000000000004 | 0.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
| Family | Types | Stores | Use for |
|---|---|---|---|
| Integer | SMALLINT, INTEGER, BIGINT | Whole numbers, exact | Counts, quantities, keys, money in cents |
| Fixed-point | DECIMAL(p, s) | Decimal digits, exact | Prices, tax rates, exchange rates |
| Floating-point | REAL, DOUBLE | Binary approximation | Sensor 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
| Type | Bytes | Largest value |
|---|---|---|
| SMALLINT | 2 | 32,767 |
| INTEGER | 4 | 2,147,483,647 |
| BIGINT | 8 | 9,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.
- 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
- 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
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?
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
| Type | Behavior | Fits |
|---|---|---|
| CHAR(n) | Always n characters, padded with spaces | Fixed-width codes such as country and currency |
| VARCHAR(n) | Up to n characters, stores what is written | Names, emails and titles with a known ceiling |
| VARCHAR | No declared limit | Free 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
| Column | Real ceiling | Reasonable type |
|---|---|---|
| 254 characters, from the mail standards | VARCHAR(254) | |
| phone_number | 15 digits plus a leading + in E.164 form | VARCHAR(16) |
| country_code | 2 letters in ISO 3166 | CHAR(2) |
| currency_code | 3 letters in ISO 4217 | CHAR(3) |
| full_name | No standard, and 100-character names exist | VARCHAR(200) or more |
| postal_code | Letters, spaces and leading zeros | VARCHAR(12) |
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.
- 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.
| city | characters | bytes |
|---|---|---|
| Lima | 4 | 4 |
| Zürich | 6 | 7 |
| 東京 | 2 | 6 |
On an engine that counts bytes, VARCHAR(6) accepts Lima, rejects Zürich, and holds 2 Japanese characters where the designer expected 6.
An engine counts VARCHAR length in bytes, and city is declared VARCHAR(8). Which city name is too long for the column?
4 temporal types
| Type | One value means | Example |
|---|---|---|
| DATE | A calendar day, with no time of day | 2026-11-01 |
| TIMESTAMP | A clock reading, with no zone attached | 2026-11-01 01:30:00 |
| TIMESTAMP WITH TIME ZONE | One instant on the shared global timeline | 2026-11-01 05:30:00 UTC |
| INTERVAL or integer | A length of time | 40 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 UTC | New York clock | Offset |
|---|---|---|
| 05:15 | 01:15 | UTC-4, daylight |
| 05:45 | 01:45 | UTC-4, daylight |
| 06:15 | 01:15 | UTC-5, standard |
| 06:45 | 01:45 | UTC-5, standard |
| utc_minutes | local_minutes |
|---|---|
| 40 | -20 |
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
- 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
- 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.
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_subscribed | users |
|---|---|
| TRUE | 6 |
| FALSE | 3 |
| NULL | 1 |
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.
A devices table has 20 rows: is_online is TRUE in 12, FALSE in 5 and NULL in 3. What does this query return?
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.
| status | orders |
|---|---|
| shipped | 41,208 |
| Shipped | 1,377 |
| SHIPPED | 212 |
| shiped | 9 |
- 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
- 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
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.
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
| text_match | uuid_match |
|---|---|
| false | true |
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.
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
- 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.
| Declared | A value it accepts | Reviewed |
|---|---|---|
| shipment_id VARCHAR | The same UUID in 2 spellings | shipment_id UUID |
| weight DOUBLE | 2.2, in pounds or kilograms | weight_kg DOUBLE |
| cost DOUBLE | 12.989999999 | cost_minor BIGINT, currency_code CHAR(3) |
| shipped VARCHAR | Y, yes, TRUE, 1 | shipped_at TIMESTAMP WITH TIME ZONE |
| dest_zip INTEGER | 2134 for the postal code 02134 | destination_postal_code VARCHAR(12) |
| created VARCHAR | 03/04/2026 | created_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.
A streaming startup built its `subscriptions` table in an afternoon. 2 new requirements arrive, and each one tests a type.
| subscription_idUUIDPK | user_idBIGINTFK | monthly_priceDOUBLE | is_activeBOOLEAN | started_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`?
> 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.DECIMAL or integer minor units with a currency code, and measured values are DOUBLE.NOT NULL, a changing list of values belongs in a lookup table, and a UUID belongs in a UUID column.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
- 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.
- 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
- 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
- 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
- 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.