Learning navigation

Code with Animation

SQL Data Types

Choose the right column type for whole numbers, decimals and text, and see what happens when a value does not fit.

SQL5 min readConcept 2 of 44

A type says what a column can hold

Every column has a data type. The type limits which values the column accepts and decides what you can do with them. Numbers can be added. Text can be joined and sorted by its characters.

Common types are integer, numeric, text, date, time and timestamp. Whole numbers come in three sizes: smallint, integer and bigint. Bigger types take more space and hold bigger values.

For exact decimals, use numeric(precision, scale). Precision is the total number of digits. Scale is how many of them come after the decimal point.

The type protects your data

A column typed integer refuses a name. A column typed date refuses a nonsense date. The database stops bad values at the door, so you do not clean them up later.

The type also decides behaviour. The text '10' and the number 10 sort differently, as you will see below.

Fit the value to the type

integer holds -2147483648 to 2147483647. smallint holds -32768 to 32767. A value outside the range is refused with an error, never cut down to fit.

numeric(3,1) keeps 3 digits in total and 1 after the point. If a value has extra decimals, PostgreSQL rounds them first. Then it checks that the number is small enough:

CREATE TABLE items (price numeric(3,1));
INSERT INTO items VALUES (12.345);  -- stored as 12.3
INSERT INTO items VALUES (100.0);   -- error: numeric field overflow

The second insert fails because numeric(3,1) leaves only 2 digits before the point, so the biggest value is below 100.

Store a value, then sort some numbers

Pick a column type and a value to see what PostgreSQL stores or why it refuses. Then switch to Sort numbers and compare an integer column with a text column.

CREATE TABLE items (
price numeric(3,1)
);
 
INSERT INTO items VALUES (12.345);
items
pricenumeric(3,1)
12.3
INSERT 0 1 (stored as 12.3)

numeric(3,1) keeps 3 digits in total, 1 after the point. Extra digits are rounded first, then the size is checked.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1You insert 40000 into a `smallint` column. What happens?
  2. 2A column is `numeric(3,1)`. What is stored when you insert 12.345?
  3. 3The numbers 2, 9 and 10 are stored in a `text` column. What order does `ORDER BY` return?

Remember this

  • A data type limits which values a column accepts and what you can do with them.
  • smallint, integer and bigint have fixed ranges, and a value outside the range is refused.
  • numeric(precision, scale) rounds extra decimals first, then refuses a value with too many digits before the point.
  • Numbers kept as text sort one character at a time, so use a number type for numbers.

Done with this concept?

Mark it complete to track your progress. No login needed.