Sub topic 2
Choosing Data Types for Columns
This chapter assumes you can write basic SELECT, INSERT, UPDATE, and DELETE statements. It also assumes you know what tables, rows, and columns are. You should have seen the CREATE TABLE statement from the previous chapter. Examples use PostgreSQL syntax, and dialect differences are noted where they matter.
Why the type matters
Every column has one data type. The type is the first constraint on a column, and the database enforces it on every write. A type decides four things:
- Which values are accepted. A
DATEcolumn rejects'banana'. - How much space a value uses. This affects table size, index size, and speed.
- How values compare and sort. The text
'10'sorts before'9', but the integer 10 sorts after 9. - Which operations make sense. You can add two numbers or subtract two dates. You cannot do either with arbitrary text.
Changing a type later is possible but expensive on large tables, because the database may rewrite every row. Choose carefully when you create the table.
Type families
The standard names below work in most systems. The last column lists the usual use.
| Family | Common types | Typical use |
|---|---|---|
| Whole numbers | `SMALLINT`, `INTEGER`, `BIGINT` | Counts, quantities, surrogate keys |
| Exact decimals | `NUMERIC(p, s)`, `DECIMAL(p, s)` | Money, measurements that must not drift |
| Approximate decimals | `REAL`, `DOUBLE PRECISION` | Scientific values, sensor readings |
| Text | `CHAR(n)`, `VARCHAR(n)`, `TEXT` | Names, emails, descriptions |
| Dates and times | `DATE`, `TIME`, `TIMESTAMP`, `TIMESTAMP WITH TIME ZONE` | Birthdays, event times |
| True/false | `BOOLEAN` | Flags |
Whole numbers
Each integer type has a fixed range. In PostgreSQL, SMALLINT holds about ±32 thousand, INTEGER about ±2.1 billion, and BIGINT about ±9.2 quintillion. Inserting a value outside the range fails with an "out of range" error. It does not wrap around.
Use INTEGER by default. Use BIGINT for keys on tables that may pass two billion rows, such as event logs. Changing a key from INTEGER to BIGINT later means altering every foreign key that points to it, so decide early.
Exact and approximate decimals
NUMERIC(p, s) stores exact decimal values. The precision p is the total number of digits. The scale s is how many of those digits come after the decimal point. NUMERIC(10, 2) holds values up to 99,999,999.99.
Floating-point types are approximate, because they store binary fractions. Many decimal values, such as 0.1, have no exact binary form.
SELECT 0.1::double precision + 0.2::double precision = 0.3::double precision AS float_equal,
0.1::numeric + 0.2::numeric = 0.3::numeric AS numeric_equal;In PostgreSQL this returns false for float_equal and true for numeric_equal. That is why money belongs in NUMERIC.
NUMERIC also rounds to the declared scale. Inserting 19.999 into a NUMERIC(10, 2) column stores 20.00. Inserting more digits than the precision allows raises an error such as numeric field overflow.
Text
The three text types differ mainly in length handling:
CHAR(n)is fixed length. Shorter values are padded with spaces. Use it only for values that always have the same length, such as a two-letter country code.VARCHAR(n)is variable length with a maximum ofncharacters. A longer value is rejected, for example withvalue too long for type character varying(5).TEXTis variable length with no declared limit. PostgreSQL and SQL Server'sVARCHAR(MAX)offer this, and MySQL hasTEXTwith size limits. Oracle usesVARCHAR2andCLOB.
In PostgreSQL, VARCHAR(n) and TEXT perform the same. Pick VARCHAR(n) when the limit is a real business rule, such as an email column capped at 255 characters. Pick TEXT when you have no reason for a limit. Do not invent a limit like VARCHAR(50) for a name field. It will eventually reject a real name.
Many identifiers look like numbers but are text. Postal codes, phone numbers, and account numbers can have leading zeros. A value like 02134 stored as an integer becomes 2134. Ask whether you would ever do arithmetic on the value. If not, use text.
Dates and times
DATEstores a calendar day with no time.TIMEstores a time of day.TIMESTAMPstores a date and a time with no time zone information.TIMESTAMP WITH TIME ZONE(TIMESTAMPTZin PostgreSQL) represents an exact instant.
Use DATE for things that are days, such as a birth date or an invoice date. Use a time-zone-aware timestamp for events that happened at a moment, such as a login. PostgreSQL stores such values in UTC and converts them to the session's time zone on display. Plain TIMESTAMP is fine when the time is local by nature, such as a store's opening time. Be aware that Oracle, MySQL, and SQL Server handle time zones differently. MySQL's TIMESTAMP is converted to UTC, and SQL Server uses DATETIMEOFFSET.
Never store dates as text such as '03/04/2026'. The text is ambiguous (March 4 or April 3?), sorts wrongly, and accepts invalid days.
Booleans
BOOLEAN holds TRUE, FALSE, or NULL. PostgreSQL has a true boolean type. MySQL accepts BOOLEAN as an alias for TINYINT(1). SQL Server has no boolean and uses BIT. Oracle added BOOLEAN only in recent versions, and older code uses NUMBER(1) or CHAR(1). Add NOT NULL to a flag column if you want only two states.
A decision flow
A worked example
This table applies the choices above.
CREATE TABLE invoices (
invoice_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
invoice_number VARCHAR(20) NOT NULL,
postal_code VARCHAR(10),
amount NUMERIC(12, 2) NOT NULL,
is_paid BOOLEAN NOT NULL DEFAULT FALSE,
issued_on DATE NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);The reasoning behind each column:
invoice_idisBIGINTbecause invoices accumulate for years.invoice_numberis text because it may contain letters or leading zeros.postal_codeis text and nullable, because it is an identifier and may be unknown.amountisNUMERIC(12, 2)for exact money.is_paidis a boolean with a default ofFALSE.issued_onis aDATE, because an invoice date has no time of day.created_atis an exact instant that the database fills in.
Common errors
Each of these errors comes from a mismatch between a value and its column type.
- Out of range. A value too large for the integer type. Choose a wider type.
- Value too long. A string longer than the
VARCHAR(n)limit. The database does not truncate it silently in PostgreSQL. Some MySQL configurations do truncate unless strict mode is on. - Invalid input syntax. Text that cannot convert to the column type, such as
'abc'into anINTEGER. - Numeric overflow. More integer digits than
p - sallows. - Implicit conversion surprises. Comparing a text column to a number can force the database to convert every row, which can also prevent index use. Compare values of the same type.
Exercise
A table stores product weights in kilograms such as 12.375, and customer phone numbers such as +44 20 7946 0958. Which type fits each column, and why not the obvious alternative for the phone number?
Show answer
Use NUMERIC(8, 3) for the weight, so values are exact and keep three decimal places. Use VARCHAR(20) for the phone number. An integer would drop the leading plus sign and any leading zeros, and you never do arithmetic on a phone number.
Exercise
You insert 123456789.50 into an amount column declared NUMERIC(10, 2). Does it succeed? What does 19.999 become in the same column?
Show answer
It fails. NUMERIC(10, 2) allows 8 digits before the decimal point, so the largest value is 99999999.99, and the database raises a numeric field overflow error. The value 19.999 is rounded to 20.00 and stored.