SQL · Module 2 · Lesson 11 min read

Numeric Data Types

Integer types (whole numbers)

TypeRangeUse for
SMALLINT±32,767small counts, ratings
INTEGER / INT±2.1 billionmost IDs and counts ✅
BIGINT±9.2 quintillionIDs in very large tables, big totals

Exact decimals: NUMERIC / DECIMAL

  • NUMERIC(precision, scale) – precision = total digits, scale = digits after the decimal point
  • NUMERIC(10,2) → up to 99,999,999.99
  • Exact – no rounding errors ✅ always use for money
  • Values are rounded to the scale: 12.345 → 12.35
  • Slower than floats, but correctness matters more for money

Approximate: REAL / DOUBLE PRECISION

  • Floating point (like JavaScript numbers)
  • Fast, huge range, but inexact: 0.1 + 0.2 ≠ 0.3
  • Use for scientific measurements, coordinates, sensor data — never money

Auto-incrementing IDs

  • Modern standard: INT GENERATED ALWAYS AS IDENTITY ✅
  • Older PostgreSQL style: SERIAL / BIGSERIAL (still common in tutorials)

Integer division gotcha ⚠️

7 / 2 → 3 (both are integers, so the result is an integer!) Fix: 7 / 2.0 or 7::numeric / 2 → 3.5

Choosing the right type

  • Counting things → INT
  • Money → NUMERIC(12,2)
  • Percentages / ratings with decimals → NUMERIC(5,2)
  • GPS coordinates → DOUBLE PRECISION (or PostGIS)

Example

SQL
-- Floating point is inexact
SELECT 0.1::float8 + 0.2::float8 = 0.3::float8 AS float_equal,   -- false 😬
       0.1::numeric + 0.2::numeric = 0.3     AS numeric_equal;   -- true ✅

-- NUMERIC rounds to its scale
SELECT 12.345::NUMERIC(10,2) AS rounded;       -- 12.35

-- Integer division
SELECT 7 / 2       AS int_division,            -- 3
       7 / 2.0     AS decimal_division,        -- 3.5000000000000000
       7 % 2       AS remainder;               -- 1

-- A table with sensible numeric types
CREATE TABLE products (
  id        INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name      TEXT NOT NULL,
  price     NUMERIC(10,2) NOT NULL,            -- money: exact
  stock     INT NOT NULL DEFAULT 0,            -- whole numbers
  rating    NUMERIC(2,1),                      -- 4.5
  weight_kg REAL                               -- approximate is fine
);

INSERT INTO products (name, price, stock, rating, weight_kg)
VALUES ('Water bottle', 899.99, 40, 4.6, 0.35);

SELECT name, price * 3 AS price_for_three FROM products;  -- 2699.97
DROP TABLE products;