SQL: Structured Query LanguageSQL FundamentalsData Types and Type Selection
What is a data type in SQL, and why does it matter?
Question 11 of 30 · Updated
On this page
- 1. Common SQL data types
- 2. How data types appear in a table definition
- 3. Inspect the types of SQL expressions
- 4. Why the type matters: preserving business meaning
- 5. Why the type matters: precision and calculation
- 6. Why the type matters: query correctness
- 7. Type safety, validation and conversion
- 8. Type choice, storage and performance
- 9. How to choose a data type
- 10. Interview-ready answer
- Validation and references
A data type specifies the kind of value that an SQL column or expression can represent, the operations that are meaningful for that value, and the rules the database uses to interpret it. Choosing the correct type helps protect data integrity, preserve information, produce correct calculations, and use storage and indexes effectively.
For example, a quantity should normally be an integer, a financial amount may require an exact decimal type, a calendar date should use a date type, and a reference code such as 0012 should remain text if its leading zeros are meaningful. These are different business concepts even when their values contain similar characters.
1. Common SQL data types#
The following table uses PostgreSQL as the reference implementation. Names, limits, storage and conversion rules differ across database products.
| Type family | Common PostgreSQL types | Example use |
|---|---|---|
| Whole numbers | SMALLINT, INTEGER, BIGINT | Counts, quantities, numeric identifiers |
| Exact decimal numbers | NUMERIC, DECIMAL | Prices, balances, measurements requiring specified decimal precision |
| Approximate numbers | REAL, DOUBLE PRECISION | Scientific measurements and numerical analysis where approximation is acceptable |
| Character strings | CHAR, VARCHAR, TEXT | Names, descriptions, reference codes |
| Date and time | DATE, TIME, TIMESTAMP, TIMESTAMPTZ | Birth dates, appointments, event instants |
| Logical values | BOOLEAN | Whether an invoice is paid |
| Unique identifiers | UUID | Distributed application identifiers |
| Binary data | BYTEA | Raw bytes |
| Structured documents | JSON, JSONB | Variable-shape metadata and documents |
SQL types apply to more than columns. Literals, expressions, function parameters, return values and query result columns also have types. PostgreSQL additionally supports arrays, enumerated types, domains and composite types. Use the simplest type that accurately represents the business meaning and expected operations.
2. How data types appear in a table definition#
Imagine an order line containing an identifier, a textual reference, a quantity, a price, an order date and a payment flag. A possible PostgreSQL table definition is:
SQLCREATE TABLE order_lines ( order_id BIGINT PRIMARY KEY, reference_code TEXT NOT NULL, quantity INTEGER NOT NULL CHECK (quantity > 0), unit_price NUMERIC(10, 2) NOT NULL CHECK (unit_price >= 0), ordered_on DATE NOT NULL, paid BOOLEAN NOT NULL DEFAULT FALSE );
This DDL is illustrative; run it only in a disposable database. It was not executed against the publishing database. The examples below use read-only expressions and inline rows to demonstrate actual PostgreSQL type behavior.
Each type describes a different property of the order. BIGINT provides room for a large sequence of numeric identifiers; TEXT preserves the exact reference code; INTEGER represents a whole quantity; NUMERIC(10, 2) represents a decimal amount with ten digits of precision and two fractional digits; DATE represents a calendar day; BOOLEAN represents a true-or-false flag. In PostgreSQL, NUMERIC with a declared scale can round inputs to that scale before enforcing the allowed precision. The column declaration is not a complete business validation policy.
Notice the difference between types and constraints. INTEGER permits negative numbers, so a positive-quantity rule requires CHECK. BOOLEAN allows NULL unless a separate constraint forbids it. A primary key requires uniqueness and non-nullness in addition to the selected type. DEFAULT supplies a value under appropriate insertion conditions; it is not a type or a validation rule.
3. Inspect the types of SQL expressions#
PostgreSQL provides pg_typeof for inspecting the resolved type of an expression. Its output can help explain why two apparently similar values behave differently.
SQLSELECT pg_typeof(42)::text AS integer_type, pg_typeof('42'::text)::text AS text_type, pg_typeof(19.99::numeric(10,2))::text AS amount_type, pg_typeof(DATE '2026-01-15')::text AS date_type, pg_typeof(TRUE)::text AS flag_type;
| integer_type | text_type | amount_type | date_type | flag_type |
|---|---|---|---|---|
| integer | text | numeric | date | boolean |
42 and '42'::text have different types even though both can be displayed as the characters 42. PostgreSQL resolves operators and functions using the types of their operands. The :: syntax is PostgreSQL-style casting; CAST is the more portable SQL syntax. pg_typeof returns the base type name here, not the precision and scale modifier of the NUMERIC expression.
4. Why the type matters: preserving business meaning#
Consider a reference code 0012. It is not a quantity and should not be treated like a number merely because it contains digits. On the other hand, a price and quantity must participate in arithmetic, and an order date must support date operations.
SQLSELECT CAST('0012' AS text) AS reference_code, CAST('0012' AS integer) AS converted_number, CAST(19.99 AS numeric(10,2)) * 3 AS line_total, DATE '2026-01-15' + 7 AS due_date;
| reference_code | converted_number | line_total | due_date |
|---|---|---|---|
| 0012 | 12 | 59.97 | 2026-01-22 |
The numeric conversion discards the leading zeros because they are not part of the integer's mathematical value. The text value preserves them. The numeric price can be multiplied by a quantity, and PostgreSQL's date-plus-integer operator adds calendar days. Other products may require a different date arithmetic syntax.
Use types to model meaning rather than appearance. Telephone numbers, postal codes, account references and externally assigned codes are often better represented as strings, even when they consist entirely of digits. An identifier generated by your own database can reasonably use an integer type if leading zeros and other formatting are not part of its identity.
5. Why the type matters: precision and calculation#
Exact decimal and binary floating-point arithmetic have different characteristics. PostgreSQL NUMERIC is an exact decimal type within its supported precision; DOUBLE PRECISION represents approximate binary floating-point values.
SQLSELECT (0.1::numeric + 0.2::numeric = 0.3::numeric) AS decimal_equal, (0.1::double precision + 0.2::double precision = 0.3::double precision) AS float_equal, pg_column_size(1::smallint) AS smallint_bytes, pg_column_size(1::integer) AS integer_bytes, pg_column_size(1::bigint) AS bigint_bytes;
| decimal_equal | float_equal | smallint_bytes | integer_bytes | bigint_bytes |
|---|---|---|---|---|
| true | false | 2 | 4 | 8 |
The exact decimal comparison returns true. The floating-point comparison returns false in this tested example because 0.1 and 0.2 do not have exact finite binary representations. Floating point is not defective; it trades exact decimal representation for efficient approximate arithmetic over a wide range.
For money, a suitably sized NUMERIC type or an explicitly defined integer minor-unit representation is often appropriate. Currency, scale, rounding and maximum amount must still be specified. Exact numeric types do not make every calculation mathematically exact: division and assignment to a fixed scale can require rounding.
The last three expressions show the PostgreSQL value sizes for these integer types. They are not measurements of the complete physical row or index entry, which also has overhead such as alignment, headers and other metadata.
6. Why the type matters: query correctness#
Correct types support meaningful comparisons and filtering. This read-only example uses explicitly typed inline order rows rather than creating a permanent table.
SQLWITH sample_orders( order_id, reference_code, quantity, unit_price, ordered_on, paid ) AS ( VALUES (1, '0012'::text, 3, 19.99::numeric(10,2), DATE '2026-01-15', TRUE), (2, '0013'::text, 2, 5.50::numeric(10,2), DATE '2026-01-16', FALSE) ) SELECT order_id, reference_code, quantity * unit_price AS line_total FROM sample_orders WHERE paid ORDER BY order_id;
| order_id | reference_code | line_total |
|---|---|---|
| 1 | 0012 | 59.97 |
The Boolean predicate keeps the paid order, multiplication uses the numerical values, and the textual code retains its formatting. Storing everything as text would make these operations dependent on repeated conversions or custom conventions.
Ordering is another example: text comparison generally follows a collation, while numerical comparison follows numerical magnitude. In many ordinary collations the string '10' sorts before '2', whereas the number 10 is greater than 2. Avoid relying on textual ordering for values whose business meaning is numeric.
7. Type safety, validation and conversion#
A database can reject a value that cannot be represented in a target type, or it can apply a supported conversion. Whether conversion happens automatically depends on the database engine and context. In PostgreSQL, an input such as the string 'abc' cannot be converted to INTEGER. A value outside the integer's representable range also fails. Other conversions may succeed but change the value, such as rounding or discarding time-of-day information when converting a timestamp to a date.
PostgreSQL uses a strongly typed system: a column has a defined type, and expression types influence operator and function resolution. SQLite ordinary tables use type affinity and can store values of different storage classes in many columns; its STRICT tables impose additional type rules. Consequently, successful execution in one SQL dialect does not demonstrate identical type enforcement in another.
A type is only one part of validation. A date type cannot know whether a delivery date is acceptable for a particular order. A numeric type cannot know whether a price is allowed by a discount policy. Use CHECK, NOT NULL, foreign keys, uniqueness, and application validation where appropriate.
8. Type choice, storage and performance#
Type decisions can affect row width, index size, caching, CPU work, comparison behavior and data transfer. For example, PostgreSQL SMALLINT, INTEGER and BIGINT have different ranges and storage sizes. Choosing an unnecessarily narrow type can cause overflow and force an expensive future migration; choosing a wider type can increase storage and index footprint at scale.
Compatible data types on related columns help avoid unnecessary conversions during joins and comparisons. A cast applied to an indexed column may prevent the optimizer from using a simple index for that expression, depending on the engine, operator and available indexes. Use execution plans rather than assuming every cast makes a query slow.
Structured types are also useful when their semantics fit the data. PostgreSQL JSONB supports querying variable-shaped documents, but storing every structured field in JSONB can sacrifice the clarity and straightforward relational constraints of ordinary typed columns. The decision should follow the access patterns and data integrity requirements, not simply convenience.
9. How to choose a data type#
| Question to ask | Example decision |
|---|---|
| What does the value mean? | A reference code is text, a quantity is an integer. |
| What range must it support today and later? | Use an integer size that accommodates expected growth. |
| Is exact decimal precision required? | Consider NUMERIC with a defined scale and rounding policy. |
| Does it represent a date, local time, or an instant? | Select the temporal type matching that meaning. |
| Is the value required? | Add NOT NULL when absence is invalid. |
| Are there business rules beyond the type? | Add suitable constraints and validation. |
| How will it be queried and joined? | Choose compatible types and evaluate indexes for real workloads. |
Changing a type after a system has been deployed may require checking existing values, handling incompatible conversions, rebuilding indexes or rewriting table data. In production, plan migrations with backups, rollback strategies, and attention to locks and downtime. Choose a semantically correct type at design time rather than relying on future conversions.
10. Interview-ready answer#
A data type defines the kind of value an SQL column or expression can represent and how the database interprets it. Examples include INTEGER for whole numbers, TEXT or VARCHAR for strings, NUMERIC for exact decimals, DATE for dates and BOOLEAN for logical flags. Correct types protect integrity, preserve meaning, support appropriate calculations and comparisons, and influence storage and query performance. For instance, using a numeric type for a price enables arithmetic, while storing a reference code such as 0012 as text preserves its leading zeros. Types should be combined with constraints to enforce business rules, and exact behavior varies across database engines.
Validation and references#
All four read-only PostgreSQL example statements were executed and returned the displayed results: expression type inspection; text, integer, decimal and date operations; exact-versus-approximate equality and integer value sizes; and the typed inline order query. The CREATE TABLE definition and examples of incompatible inputs are explanatory and were not executed. No educational DDL, application data reads or writes were performed on production tables.
A comparison table was chosen instead of a Mermaid diagram because this topic is primarily a comparison of type families and selection criteria; a diagram would add little instructional value.
Documentation consulted through the Supabase documentation connector:
- Supabase — Tables and data: PostgreSQL column types, storage widths and type casting.
- Supabase — Managing JSON and unstructured data: structured versus variable-shape data and JSON types.
Additional authoritative reading (not live-verified in this session):
Live web browsing was unavailable; the additional references are suggested reading rather than independently consulted sources.
References
- 1.Supabase — Tables and datasupabase.com
- 2.Supabase — Managing JSON and unstructured datasupabase.com
- 3.PostgreSQL — Data Types (not live-verified)postgresql.org
- 4.PostgreSQL — Numeric Types (not live-verified)postgresql.org
- 5.PostgreSQL — Type Conversion (not live-verified)postgresql.org
- 6.SQLite — Datatypes (not live-verified)sqlite.org
Related questions
Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning