SQL Data Types: Numbers, Text, Dates, Booleans and CAST
A practical guide to SQL data types: integers, DECIMAL versus floating point, CHAR, VARCHAR and TEXT, dates and times, booleans, binary data, how type names differ between databases, CAST and implicit conversion, integer division, rounding on conversion and checking conversions safely.
kvi5hnuCode Sprout team member14 min readOn this page
Every column, literal and expression in SQL has a data type. The type decides what values are allowed, how they're stored, how they compare and sort, and what operations work on them. Choosing the right type prevents bad data from getting in. Understanding conversions explains many puzzling results, such as why 7 / 2 is 3, why '10' < '9' is true, and why 0.1 + 0.2 isn't always 0.3.
This article opens Part 8, which covers working with values: text, numbers, dates, regular expressions and JSON. It starts with the types themselves and how to convert between them. Defining types in CREATE TABLE comes in article 52.
The main type families
The SQL standard defines the main types, and every database implements them with its own names and extras. The families that matter in practice:
| Family | Standard types | Used for |
|---|---|---|
| Exact numbers | SMALLINT, INTEGER, BIGINT, DECIMAL(p, s) / NUMERIC(p, s) | counts, IDs, money, quantities |
| Approximate numbers | REAL, DOUBLE PRECISION, FLOAT(p) | measurements, scientific values |
| Text | CHAR(n), VARCHAR(n), plus TEXT / CLOB | names, codes, descriptions |
| Date and time | DATE, TIME, TIMESTAMP, TIMESTAMP WITH TIME ZONE, INTERVAL | events, schedules, durations |
| Boolean | BOOLEAN | flags: true, false or unknown |
| Binary | BINARY, VARBINARY, BLOB | files, images, hashes |
Beyond these, most databases have types for UUIDs (article 54), JSON (article 43) and more. PostgreSQL adds arrays, ranges, network addresses and geometric types.
Exact numbers: integers and DECIMAL
Integer types store whole numbers in a fixed number of bytes:
| Type | Bytes | Range |
|---|---|---|
SMALLINT | 2 | −32,768 to 32,767 |
INTEGER / INT | 4 | about ±2.1 billion |
BIGINT | 8 | about ±9.2 × 10^18 |
Use INTEGER by default and BIGINT for values that can grow past 2 billion, such as IDs in large or fast-growing tables. Running out of INTEGER IDs is a real and painful production incident.
DECIMAL(p, s), also called NUMERIC(p, s), stores numbers as exact decimal digits. p is the precision, the total number of significant digits, and s is the scale, the number of digits after the decimal point. DECIMAL(8, 2) holds values up to 999,999.99, which is why the shop stores prices that way. Use DECIMAL for money and any value that must add up exactly.
-- Exact numbers: integers and DECIMAL / NUMERIC
SELECT 7 / 2 AS integer_division,
7 % 2 AS remainder,
7 / 2.0 AS decimal_division,
CAST(7 AS numeric) / 2 AS cast_first,
0.1 + 0.2 AS decimal_sum,
0.1 + 0.2 = 0.3 AS decimal_equal;
-- Approximate numbers: REAL / DOUBLE PRECISION store binary fractions
SELECT CAST(0.1 AS double precision) + CAST(0.2 AS double precision) AS float_sum,
CAST(0.1 AS double precision) + CAST(0.2 AS double precision) = 0.3 AS float_equal;
-- Values that don't fit are errors, not silently wrapped or cut
SELECT 2147483647 + 1; -- larger than INTEGER allows
SELECT CAST(1234.5 AS numeric(5, 2)); -- needs 4 digits before the point
SELECT CAST(123.456 AS numeric(5, 2)) AS rounded_to_scale;
integer_division | remainder | decimal_division | cast_first | decimal_sum | decimal_equal
------------------+-----------+--------------------+--------------------+-------------+---------------
3 | 1 | 3.5000000000000000 | 3.5000000000000000 | 0.3 | t
(1 row)
float_sum | float_equal
---------------------+-------------
0.30000000000000004 | f
(1 row)
psql:/workspace/solution.sql:14: ERROR: integer out of range
psql:/workspace/solution.sql:15: ERROR: numeric field overflow
DETAIL: A field with precision 5, scale 2 must round to an absolute value less than 10^3.
rounded_to_scale
------------------
123.46
(1 row)
The first query shows the most common surprise: dividing two integers gives an integer. 7 / 2 is 3, with the remainder dropped, in PostgreSQL, SQL Server and SQLite. If either value is a decimal, the result is a decimal: 7 / 2.0 is 3.5. To divide two integer columns precisely, cast one of them first: CAST(a AS numeric) / b, or multiply by 1.0. MySQL and Oracle behave differently: their / always returns a decimal, and MySQL uses DIV for integer division.
The last statements show that values that don't fit are errors, not silent wrap-arounds. 2147483647 + 1 is too large for INTEGER. 1234.5 needs four digits before the point, but NUMERIC(5, 2) allows three. Extra digits after the point are rounded to the scale, though: 123.456 becomes 123.46.
Approximate numbers: REAL and DOUBLE PRECISION
REAL (4 bytes, about 6 significant digits) and DOUBLE PRECISION (8 bytes, about 15 digits) are floating-point types. They store numbers as binary fractions, which makes them fast and gives them a huge range, but most decimal fractions, such as 0.1, have no exact binary representation. The runnable above shows the consequence: as double precision, 0.1 + 0.2 is 0.30000000000000004, and comparing it with 0.3 gives false.

Rules of thumb:
- Use
DECIMALfor money, prices, quantities and anything users add up or compare exactly. - Use floating point for measurements, sensor readings, statistics and scientific values, where tiny errors don't matter.
- Never compare floating-point values with
=. Compare with a tolerance, as inABS(a - b) < 0.000001. FLOATwithout a precision meansDOUBLE PRECISIONin PostgreSQL and SQL Server, but 4-byteREALprecision in MySQL. Write the type you mean.
In PostgreSQL, a literal with a decimal point, like 0.1, is numeric, which is why 0.1 + 0.2 = 0.3 is true there. In MySQL, decimal literals are exact DECIMAL too, but SQLite stores them as floating point, so 0.1 + 0.2 = 0.3 is false in SQLite.
Text: CHAR, VARCHAR and TEXT
VARCHAR(n)stores text up toncharacters. Longer values are rejected (article 31). It's the standard choice for text with a sensible maximum length.CHAR(n)stores exactlyncharacters, padding shorter values with spaces. It's a holdover from fixed-width storage and rarely useful today, except perhaps for fixed-length codes.TEXTstores long text: unlimited in PostgreSQL and SQLite, but up to 64 KB in MySQL, whereMEDIUMTEXTandLONGTEXThold more. SQL Server usesVARCHAR(MAX)andNVARCHAR(MAX), and Oracle usesCLOB.
-- CHAR(n) pads with spaces; VARCHAR(n) and TEXT store what you give them
CREATE TABLE codes (
fixed CHAR(5),
variable VARCHAR(5),
unlimited TEXT
);
INSERT INTO codes VALUES ('ab', 'ab', 'ab');
SELECT fixed = 'ab' AS char_equal,
octet_length(fixed) AS char_bytes,
octet_length(variable) AS varchar_bytes,
'[' || fixed || ']' AS char_concat,
'[' || variable || ']' AS varchar_concat
FROM codes;
char_equal | char_bytes | varchar_bytes | char_concat | varchar_concat
------------+------------+---------------+-------------+----------------
t | 5 | 2 | [ab] | [ab]
(1 row)
CHAR(5) stores 'ab' as 'ab ', 5 bytes. Comparisons ignore the trailing padding, so fixed = 'ab' is true, and in PostgreSQL, converting CHAR to text for || removes it. But other functions and other databases treat the spaces differently, which makes CHAR a steady source of subtle bugs. Prefer VARCHAR or TEXT.
Other text details that vary between databases:
- Length limits: in PostgreSQL,
VARCHAR(n)andTEXTperform the same, and the limit is only a constraint. In MySQL, aVARCHARlength counts towards the 65,535-byte row limit, and indexes have length limits. - Unicode: PostgreSQL, MySQL (with
utf8mb4) and SQLite store Unicode in ordinary text types. SQL Server needsNVARCHAR(or a UTF-8 collation, since SQL Server 2019), and Unicode literals are writtenN'text'. In MySQL, useutf8mb4, not the olderutf8, which can't store emoji. - Empty string versus NULL: Oracle treats
''as NULL.VARCHAR2columns can't store an empty string, andWHERE name = ''never matches. Every other major database keeps them distinct. - Case and accents: whether
'abc' = 'ABC'is true depends on the collation (article 36). It's false in PostgreSQL by default and true in MySQL and SQL Server by default.
Dates, times and intervals
| Type | Holds | Example |
|---|---|---|
DATE | a calendar date | DATE '2026-03-05' |
TIME | a time of day | TIME '14:30:00' |
TIMESTAMP | date and time, no time zone | TIMESTAMP '2026-03-05 14:30:00' |
TIMESTAMP WITH TIME ZONE | an absolute moment in time | TIMESTAMP WITH TIME ZONE '2026-03-05 14:30:00+01' |
INTERVAL | a duration | INTERVAL '3 days' |
Names differ here more than anywhere else. SQL Server uses DATETIME2 and DATETIMEOFFSET. MySQL has DATETIME and a TIMESTAMP that converts to UTC. Oracle's DATE includes a time of day. SQLite has no date types at all and stores dates as text, numbers or Julian days. Articles 39–41 cover dates and times in depth, including time zones.
Store dates in date types, never as text. A date column rejects 30 February, sorts chronologically and supports date arithmetic. A text column accepts anything, sorts '10/01/2026' before '9/01/2026', and needs converting for every calculation.
Booleans
BOOLEAN holds TRUE, FALSE or NULL (unknown), and conditions can use boolean columns directly: WHERE is_active. Support varies:
- PostgreSQL and SQLite 3.23+ accept
TRUEandFALSE. SQLite stores them as 1 and 0. - MySQL:
BOOLEANis an alias forTINYINT(1), andTRUEis just 1. - SQL Server has no boolean column type. Use
BIT, with 1 and 0, and compare explicitly:WHERE is_active = 1. - Oracle 23ai added a real
BOOLEANtype. Earlier versions usedNUMBER(1)orCHAR(1)with a check constraint.
Type names across databases
| Purpose | PostgreSQL | MySQL | SQL Server | Oracle | SQLite |
|---|---|---|---|---|---|
| 4-byte integer | integer | INT | INT | NUMBER(10) | INTEGER |
| exact decimal | numeric(p,s) | DECIMAL(p,s) | DECIMAL(p,s) | NUMBER(p,s) | NUMERIC (stored as integer or float) |
| 8-byte float | double precision | DOUBLE | FLOAT | BINARY_DOUBLE | REAL |
| bounded text | varchar(n) | VARCHAR(n) | NVARCHAR(n) | VARCHAR2(n) | TEXT |
| unbounded text | text | TEXT / LONGTEXT | NVARCHAR(MAX) | CLOB | TEXT |
| date and time | timestamp | DATETIME | DATETIME2 | TIMESTAMP | TEXT (ISO 8601) |
| boolean | boolean | BOOLEAN (= TINYINT(1)) | BIT | BOOLEAN (23ai) | INTEGER 0/1 |
| binary | bytea | BLOB / VARBINARY | VARBINARY(MAX) | BLOB | BLOB |
SQLite is the outlier: it uses type affinity. A column's declared type is a preference, not a rule, and any column can hold any type of value unless the table is declared STRICT (article 31).
CAST: converting between types
CAST(value AS type) converts a value to another type. It's standard and works in every database. PostgreSQL also has the shorthand value::type.
-- CAST(value AS type), and PostgreSQL's shorthand value::type
SELECT CAST('42' AS integer) + 1 AS from_text,
'2026-03-05'::date + 1 AS next_day,
CAST(' 12 ' AS integer) AS spaces_ignored,
CAST('yes' AS boolean) AS yes_bool,
CAST(19.99 AS text) || ' EUR' AS as_text;
-- What type is a value?
SELECT pg_typeof(1) AS a,
pg_typeof(1.5) AS b,
pg_typeof(3000000000) AS c,
pg_typeof(1 / 2.0) AS d,
pg_typeof(CURRENT_DATE) AS e;
-- Text that isn't a valid value of the type is an error
SELECT CAST('12abc' AS integer);
from_text | next_day | spaces_ignored | yes_bool | as_text
-----------+------------+----------------+----------+-----------
43 | 2026-03-06 | 12 | t | 19.99 EUR
(1 row)
a | b | c | d | e
---------+---------+--------+---------+------
integer | numeric | bigint | numeric | date
(1 row)
psql:/workspace/solution.sql:16: ERROR: invalid input syntax for type integer: "12abc"
LINE 1: SELECT CAST('12abc' AS integer);
^
- Text converts to a number, date or boolean when it's a valid value of that type. Spaces around a number are allowed, and PostgreSQL accepts
'yes','no','on','off','1'and'0'as booleans. - Numbers and dates convert to text, which is useful for joining them into strings. Formatting functions such as
TO_CHARgive more control (articles 38 and 39). pg_typeofshows the type of any expression.3000000000is too large forinteger, so PostgreSQL makes it abigintliteral, and1 / 2.0isnumeric.- Invalid text is an error:
'12abc'isn't an integer.
Other databases have their own extras: CONVERT(type, value, style) in SQL Server, CONVERT(value, type) in MySQL, and TO_NUMBER, TO_DATE and TO_CHAR in Oracle and PostgreSQL for conversions with a format.
Conversions that round
-- Casting decimals to integers rounds; casting floats rounds half to even
SELECT CAST(2.7 AS integer) AS from_2_7,
CAST(2.5 AS integer) AS from_2_5,
CAST(-2.5 AS integer) AS from_minus_2_5,
CAST(2.5::double precision AS integer) AS float_2_5,
CAST(3.5::double precision AS integer) AS float_3_5,
TRUNC(2.7) AS truncated;
-- Text compares as text, numbers as numbers
SELECT '10' < '9' AS text_comparison,
10 < 9 AS number_comparison,
CAST('10' AS integer) < CAST('9' AS integer) AS cast_comparison;
from_2_7 | from_2_5 | from_minus_2_5 | float_2_5 | float_3_5 | truncated
----------+----------+----------------+-----------+-----------+-----------
3 | 3 | -3 | 2 | 4 | 2
(1 row)
text_comparison | number_comparison | cast_comparison
-----------------+-------------------+-----------------
t | f | f
(1 row)
Converting a decimal to an integer rounds in PostgreSQL: 2.7 becomes 3, and halves round away from zero, so 2.5 becomes 3 and −2.5 becomes −3. Floating-point values round half to even ("banker's rounding"): 2.5 becomes 2 and 3.5 becomes 4. MySQL and Oracle also round, but SQL Server and SQLite truncate: CAST(2.7 AS INT) is 2 there. To be explicit everywhere, use ROUND, TRUNC or FLOOR before converting (article 38).
The second query shows why types matter for comparisons. '10' < '9' compares text, character by character, and '1' sorts before '9', so it's true. As numbers, 10 < 9 is false. Numbers stored in text columns sort and compare wrongly: product codes 'item10' and 'item9', or text prices, are classic examples. Store numbers in number columns.
Implicit conversion
Databases also convert values automatically when an operation needs a different type. How eagerly they do it differs a lot:
- PostgreSQL is strict. An untyped literal like
'5'takes the type the context needs, so'5' + 3is 8, but atextcolumn plus an integer is an error: "operator does not exist: text + integer". The error forces you to say what you mean. - MySQL converts freely, sometimes alarmingly:
'1abc' + 1is 2, with only a warning, because MySQL reads the leading digits and ignores the rest. Comparing a string column with a number converts every string to a number, which can match unexpected rows and prevents index use. - SQL Server converts by a fixed type precedence: in
'5' + 3, the string becomes an integer and the result is 8, but'abc' + 3is a conversion error. - SQLite converts according to column affinity, and
'1abc' + 1is 2, as in MySQL.
Implicit conversions also hurt performance. If a VARCHAR column holding numbers is compared with a number, the database may convert every row's value, which prevents it from using an index on that column. Compare values of the same type, casting the constant, not the column.
Checking conversions safely
Data imported from files or forms often contains values that won't convert. Converting a whole column fails on the first bad value. Most databases offer a way to test or convert without an error:
\pset null '(null)'
-- Testing whether text converts, without an error (PostgreSQL 16+)
SELECT input,
pg_input_is_valid(input, 'integer') AS valid_integer,
pg_input_is_valid(input, 'date') AS valid_date
FROM (VALUES ('42'), ('12abc'), ('2026-02-28'), ('2026-02-30')) AS t(input);
-- Convert only the valid values; the rest become NULL
SELECT input,
CASE WHEN pg_input_is_valid(input, 'date') THEN CAST(input AS date) END AS as_date
FROM (VALUES ('2026-02-28'), ('2026-02-30'), ('not a date')) AS t(input);
SELECT message, detail FROM pg_input_error_info('2026-02-30', 'date');
input | valid_integer | valid_date
------------+---------------+------------
42 | t | f
12abc | f | f
2026-02-28 | f | t
2026-02-30 | f | f
(4 rows)
input | as_date
------------+------------
2026-02-28 | 2026-02-28
2026-02-30 | (null)
not a date | (null)
(3 rows)
message | detail
--------------------------------------------------+--------
date/time field value out of range: "2026-02-30" | (null)
(1 row)
PostgreSQL 16 added pg_input_is_valid(text, type), which returns true or false instead of raising an error, and pg_input_error_info, which says why a value is invalid. Combined with CASE, they convert valid values and turn the rest into NULL. Note that '2026-02-30' looks like a date but isn't one: February has no 30th.
Other databases:
| Database | Safe conversion |
|---|---|
| SQL Server | TRY_CAST(value AS type) and TRY_CONVERT return NULL on failure |
| Oracle 12.2+ | CAST(value AS type DEFAULT NULL ON CONVERSION ERROR), and VALIDATE_CONVERSION |
| MySQL | invalid dates become NULL with a warning, and '12abc' converts to 12. Validate with a regular expression first (article 42) |
| Snowflake, DuckDB, BigQuery | TRY_CAST, or SAFE_CAST in BigQuery |
What's current
- PostgreSQL 16 added
pg_input_is_validandpg_input_error_infofor testing conversions without errors. - Oracle 23ai added a
BOOLEANcolumn type, and SQLite 3.37 addedSTRICTtables. - SQL Server 2019 added UTF-8 collations, so
VARCHARcan store Unicode. - MySQL 8.0 made
utf8mb4the default character set.utf8(an alias for the 3-byteutf8mb3) is deprecated.
Common questions
Why does 7 / 2 return 3?
Both values are integers, so the division is integer division in PostgreSQL, SQL Server and SQLite. Make one a decimal: 7 / 2.0 or CAST(7 AS numeric) / 2.
Should I store money as FLOAT?
No. Floating point can't represent most decimal fractions exactly, so sums drift. Use DECIMAL, or an integer number of cents.
What's the difference between DECIMAL and NUMERIC?
In practice nothing: every major database treats them as the same type.
VARCHAR(255) or TEXT?
In PostgreSQL they perform the same, so choose by whether you want a length limit. In MySQL and SQL Server, bounded VARCHAR is usually better for columns you index or sort.
Is CAST or :: better in PostgreSQL?
They're equivalent. CAST is standard and portable. :: is shorter.
Why does my number column sort as 1, 10, 2?
It's stored as text. Change the column type, or sort by CAST(column AS integer) until you can.
How do I convert text that might be invalid?
TRY_CAST in SQL Server, DEFAULT NULL ON CONVERSION ERROR in Oracle, pg_input_is_valid with CASE in PostgreSQL 16+.
Summary
- Use
INTEGERorBIGINTfor whole numbers,DECIMAL(p, s)for exact values such as money, and floating point only for approximate measurements. - Integer divided by integer is an integer in PostgreSQL, SQL Server and SQLite.
- Values that don't fit a numeric type are errors. Extra decimal places are rounded to the scale.
- Prefer
VARCHARorTEXTtoCHAR. Oracle treats''as NULL. - Store dates in date types and numbers in number types, never in text.
- Type names differ between databases, and SQLite only has type affinities.
CAST(value AS type)converts explicitly. Casting to integer rounds in PostgreSQL, MySQL and Oracle, and truncates in SQL Server and SQLite.- PostgreSQL rarely converts implicitly, while MySQL and SQLite convert freely. Test risky conversions with
TRY_CASTorpg_input_is_valid.
Practice questions
What do 5 / 4, 5 / 4.0 and 5 % 4 return in PostgreSQL?
Answer
1, 1.2500000000000000 and 1. The first is integer division, the second decimal division, and % gives the remainder.
A table stores prices as DOUBLE PRECISION. A report adds up 1,000 prices of 0.10 and checks whether the total equals 100.00. Why might the check fail, and what's the fix?
Answer
0.10 has no exact binary representation, so each value is slightly off, and the errors accumulate in the sum. The total might be 99.9999999999986 or similar. Store prices as DECIMAL(10, 2). As a stopgap, compare with a tolerance, or round the sum to 2 decimal places before comparing.
What does CAST(2.5 AS INTEGER) return in PostgreSQL and in SQL Server?
Answer
3 in PostgreSQL, which rounds half away from zero for decimals. 2 in SQL Server, which truncates.
Which product does SELECT name FROM products WHERE CAST(price AS integer) = 35 return in PostgreSQL, and why might this WHERE be slower than an alternative?
Answer
The Glow head torch: 34.50 rounds half away from zero to 35. In SQL Server, which truncates, it would become 34, and the query would return nothing.
Applying a function to the column means an ordinary index on price can't be used. A range on the column itself gives the same result and can use an index:
SELECT name
FROM products
WHERE price >= 34.50 AND price < 35.50;
Why is WHERE phone_number = 4155550100 a problem when phone_number is a VARCHAR column in MySQL?
Answer
MySQL converts each phone_number to a number to compare it with the numeric constant. Values with spaces, dashes or a leading + convert unpredictably, so the comparison can match the wrong rows or miss the right ones, and the conversion prevents using an index on the column. Compare with a string: WHERE phone_number = '4155550100'.
Previous: MERGE, Upserts and RETURNING: Insert-or-Update in One Statement
Next: SQL String Functions: Length, Case, Trim, Substring, Replace and Collations

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.