SQL: Structured Query LanguageSQL FundamentalsExact Decimal Data Types

What is a DECIMAL or NUMERIC data type used for?

Question 14 of 30 · Updated

On this page

DECIMAL and NUMERIC are exact numeric SQL data types used for decimal quantities whose digits and fractional precision matter. Common applications include prices, balances, invoice amounts, interest rates, exchange rates and tax calculations. In PostgreSQL, DECIMAL and NUMERIC are aliases for the same type.

Unlike binary floating-point numbers, NUMERIC represents finite decimal values exactly within its supported limits. This makes it suitable for amounts such as 19.99. Exact representation does not eliminate rounding: division, scale restrictions and financial policies can still require it.

1. Understanding precision and scale#

The usual declaration is DECIMAL(p,s) or NUMERIC(p,s). For conventional declarations where scale is between zero and precision:

  • Precision (p): the total number of decimal digits allowed by the declaration.
  • Scale (s): the number of digits after the decimal point.
  • Integer capacity (p - s): the number of digits available before the decimal point. The sign and decimal separator do not count.
DeclarationInteger digitsFractional digitsLargest finite positive value
NUMERIC(5,2)32999.99
DECIMAL(8,3)5399999.999
NUMERIC(10,2)8299999999.99
NUMERIC(6,0)60999999

For these conventional scales, the largest finite value is 10^(p-s) minus 10^(-s). The negative limit has the same magnitude. PostgreSQL also permits negative scales and scales greater than precision, which are product-specific features outside this introductory table. An unconstrained PostgreSQL NUMERIC does not impose a uniform declared scale, although implementation limits still apply.

SQL
SELECT pg_typeof(1.25::decimal)::text AS decimal_type, pg_typeof(1.25::numeric)::text AS numeric_type, 999.99::numeric(5,2) AS maximum_value, (-999.99)::numeric(5,2) AS minimum_value;
decimal_typenumeric_typemaximum_valueminimum_value
numericnumeric999.99-999.99

The PostgreSQL cast shorthand :: is equivalent here to CAST(value AS NUMERIC(p,s)). Other engines may have different maximum precision, defaults and conversion behavior.

2. How scale rounding works#

When PostgreSQL converts an ordinary finite input to a conventional constrained NUMERIC, it rounds to the declared scale and then checks whether the result fits the permitted precision.

Loading diagram…
SQL
SELECT 12.345::numeric(5,2) AS rounded_positive, (-12.345)::numeric(5,2) AS rounded_negative, 12.3::numeric(5,2) AS padded_scale, 999.994::numeric(5,2) AS near_limit;
rounded_positiverounded_negativepadded_scalenear_limit
12.35-12.3512.30999.99

PostgreSQL NUMERIC rounds midpoint ties away from zero. The displayed 12.30 reflects the result scale, not a requirement that all digits be physically stored as characters. If the business rule requires rejecting excess fractional digits rather than rounding them, validate the original input before converting it to the constrained type.

3. Overflow after rounding#

A value can be within the apparent range before rounding yet overflow afterward. For example, 999.995 rounds to 1000.00 and cannot fit NUMERIC(5,2), which permits only three integer digits. PostgreSQL provides pg_input_is_valid in supported versions to check type input without deliberately raising an error in this example.

SQL
SELECT pg_input_is_valid('999.995','numeric(5,2)') AS rounded_overflow_valid, pg_input_is_valid('1000','numeric(5,2)') AS out_of_range_valid, pg_input_is_valid('12.345','numeric(5,2)') AS rounding_valid;
rounded_overflow_validout_of_range_validrounding_valid
falsefalsetrue

An actual conversion of the first two inputs to NUMERIC(5,2) would produce numeric overflow. This validity function is PostgreSQL-specific and does not replace business validation. Choose precision with enough capacity for the largest credible value, including intermediate totals and future growth.

4. Practical example: invoice amounts#

An illustrative schema for invoice lines is:

SQL
CREATE TABLE invoice_lines ( line_id BIGINT PRIMARY KEY, quantity INTEGER NOT NULL CHECK (quantity > 0), unit_price NUMERIC(12,2) NOT NULL CHECK (unit_price >= 0 AND unit_price <> 'NaN'::numeric), currency_code TEXT NOT NULL CHECK (char_length(currency_code) = 3) );

The DDL is illustrative and was not executed. PostgreSQL NUMERIC supports NaN; the explicit check prevents that special value from passing the nonnegative-price condition. A real system also needs a valid currency reference, supported currency scales, rounding rules, and appropriate handling of discounts, returns and credits. A three-character currency field alone does not establish a valid currency.

The following read-only example calculates an invoice using two inline line items, assuming a single currency with two decimal places and a hypothetical 18 percent tax rate solely to illustrate arithmetic.

SQL
WITH lines(quantity, unit_price) AS ( VALUES (3, 19.99::numeric(10,2)), (2, 5.50::numeric(10,2)) ) SELECT SUM(quantity * unit_price) AS subtotal, ROUND(SUM(quantity * unit_price) * 0.18::numeric,2) AS illustrative_tax, SUM(quantity * unit_price) + ROUND(SUM(quantity * unit_price) * 0.18::numeric,2) AS total FROM lines;
subtotalillustrative_taxtotal
70.9712.7783.74

The first line contributes 59.97 and the second contributes 11.00. The subtotal is 70.97. The tax is rounded at the chosen calculation boundary. This is not a tax compliance recommendation or a complete accounting model. Do not sum different currencies without a defined conversion process.

5. Exact numeric does not eliminate rounding policies#

Rounding individual values before addition can produce a different result from summing first and rounding afterward, even when every operand is an exact decimal.

SQL
WITH amounts(amount) AS ( VALUES (0.005::numeric), (0.005::numeric), (0.005::numeric) ) SELECT SUM(ROUND(amount,2)) AS round_each, ROUND(SUM(amount),2) AS round_total, ROUND(1::numeric / 3,4) AS rounded_third FROM amounts;
round_eachround_totalrounded_third
0.030.020.3333

The two sums follow different rounding policies. Dividing one by three also shows that not every rational number has a finite decimal representation. A declared precision on a column does not guarantee that every intermediate calculation has that same precision and scale. Arithmetic results follow operation-specific rules; assignment to a constrained target applies its declared precision and scale.

For financial applications, specify whether rounding occurs per line, invoice or settlement, and document midpoint rules and currency scale. If a policy requires a different midpoint convention than PostgreSQL's numeric ROUND, implement and test it explicitly.

6. When to choose NUMERIC#

RequirementSuitable starting point
Price or balance with fractional currency unitsNUMERIC with suitable precision and scale
Exact decimal rate or percentageNUMERIC with domain-specific scale
Whole inventory quantityINTEGER or BIGINT
Ledger with explicitly defined minor unitsNUMERIC or an integer minor-unit design
Approximate scientific measurementsREAL or DOUBLE PRECISION if approximation is acceptable
Identifier containing digits with meaningful formattingTEXT or VARCHAR

Choose NUMERIC when exact finite decimal representation is important, not simply because a value has a fractional part. Floating point can be efficient for numerical workloads accepting approximation. Integer minor units are another financial design option when units, range and conversion rules are explicitly defined. The detailed comparison of these alternatives is a separate topic.

7. Production considerations#

Choose precision and scale using the largest expected amounts, required fractional resolution and growth. A unit-price field and an exchange-rate field need not have the same scale. Not all currencies have two minor decimal places. Constraints and application validation are separate from the type declaration.

PostgreSQL NUMERIC uses variable-length storage and often requires more computation than native integer or floating-point types. Measure relevant workloads rather than making universal speed claims. Preserve precision at the application boundary: database drivers may return numeric values as strings or decimal objects. Converting these values to binary floating point can reintroduce approximation. Display formatting is separate from the actual numerical value.

8. Interview-ready answer#

DECIMAL and NUMERIC are exact numeric SQL types used for values such as money, taxes and interest rates when decimal precision matters. NUMERIC(p,s) specifies precision and scale; for example, NUMERIC(5,2) permits three digits before the decimal point and two after it, up to 999.99 in magnitude for finite values. In PostgreSQL, DECIMAL and NUMERIC are aliases. Inputs are rounded to the declared scale, and values that overflow after rounding are rejected. Exact decimal representation avoids binary floating-point approximation for finite decimal values, but financial rounding policies and constraints remain necessary.

Interview follow-ups#

  • Are DECIMAL and NUMERIC different in PostgreSQL? No, they are aliases.
  • Does NUMERIC(5,2) reject 12.345? No, PostgreSQL rounds it to 12.35.
  • Can rounding cause overflow? Yes; 999.995 rounds to 1000.00, which does not fit.
  • Does exact decimal arithmetic guarantee exact division? No; some results require rounding.
  • Is a numeric type sufficient for financial validation? No; currency, rounding, finite values, allowed ranges and business rules also matter.

Validation and references#

Five read-only PostgreSQL queries passed: alias and range inspection, scale rounding, input validity and overflow, invoice calculation, and rounding-order comparison. The final aggregation query initially omitted its FROM clause during testing; the corrected version above returned the displayed results. The illustrative DDL and actual error-producing casts were not executed. Overflow was confirmed with pg_input_is_valid. No educational DDL or application data writes were performed.

The Mermaid flowchart uses the required triple-backtick mermaid fence with actual line breaks. A restricted structural check passed and the logic was reviewed against tested inputs. Full Mermaid parser validation and public rendering remain unverified.

Documentation consulted through the Supabase documentation connector:

Additional authoritative reading (not live-verified in this session):

Live web browsing was unavailable; additional links are suggested reading rather than independently consulted sources.

Related questions

Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning