]> begriffs open source - ai-pg/blob - full-docs/txt/datatype-numeric.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / datatype-numeric.txt
1
2 8.1. Numeric Types #
3
4    8.1.1. Integer Types
5    8.1.2. Arbitrary Precision Numbers
6    8.1.3. Floating-Point Types
7    8.1.4. Serial Types
8
9    Numeric types consist of two-, four-, and eight-byte integers, four-
10    and eight-byte floating-point numbers, and selectable-precision
11    decimals. Table 8.2 lists the available types.
12
13    Table 8.2. Numeric Types
14    Name Storage Size Description Range
15    smallint 2 bytes small-range integer -32768 to +32767
16    integer 4 bytes typical choice for integer -2147483648 to +2147483647
17    bigint 8 bytes large-range integer -9223372036854775808 to
18    +9223372036854775807
19    decimal variable user-specified precision, exact up to 131072 digits
20    before the decimal point; up to 16383 digits after the decimal point
21    numeric variable user-specified precision, exact up to 131072 digits
22    before the decimal point; up to 16383 digits after the decimal point
23    real 4 bytes variable-precision, inexact 6 decimal digits precision
24    double precision 8 bytes variable-precision, inexact 15 decimal digits
25    precision
26    smallserial 2 bytes small autoincrementing integer 1 to 32767
27    serial 4 bytes autoincrementing integer 1 to 2147483647
28    bigserial 8 bytes large autoincrementing integer 1 to
29    9223372036854775807
30
31    The syntax of constants for the numeric types is described in
32    Section 4.1.2. The numeric types have a full set of corresponding
33    arithmetic operators and functions. Refer to Chapter 9 for more
34    information. The following sections describe the types in detail.
35
36 8.1.1. Integer Types #
37
38    The types smallint, integer, and bigint store whole numbers, that is,
39    numbers without fractional components, of various ranges. Attempts to
40    store values outside of the allowed range will result in an error.
41
42    The type integer is the common choice, as it offers the best balance
43    between range, storage size, and performance. The smallint type is
44    generally only used if disk space is at a premium. The bigint type is
45    designed to be used when the range of the integer type is insufficient.
46
47    SQL only specifies the integer types integer (or int), smallint, and
48    bigint. The type names int2, int4, and int8 are extensions, which are
49    also used by some other SQL database systems.
50
51 8.1.2. Arbitrary Precision Numbers #
52
53    The type numeric can store numbers with a very large number of digits.
54    It is especially recommended for storing monetary amounts and other
55    quantities where exactness is required. Calculations with numeric
56    values yield exact results where possible, e.g., addition, subtraction,
57    multiplication. However, calculations on numeric values are very slow
58    compared to the integer types, or to the floating-point types described
59    in the next section.
60
61    We use the following terms below: The precision of a numeric is the
62    total count of significant digits in the whole number, that is, the
63    number of digits to both sides of the decimal point. The scale of a
64    numeric is the count of decimal digits in the fractional part, to the
65    right of the decimal point. So the number 23.5141 has a precision of 6
66    and a scale of 4. Integers can be considered to have a scale of zero.
67
68    Both the maximum precision and the maximum scale of a numeric column
69    can be configured. To declare a column of type numeric use the syntax:
70 NUMERIC(precision, scale)
71
72    The precision must be positive, while the scale may be positive or
73    negative (see below). Alternatively:
74 NUMERIC(precision)
75
76    selects a scale of 0. Specifying:
77 NUMERIC
78
79    without any precision or scale creates an “unconstrained numeric”
80    column in which numeric values of any length can be stored, up to the
81    implementation limits. A column of this kind will not coerce input
82    values to any particular scale, whereas numeric columns with a declared
83    scale will coerce input values to that scale. (The SQL standard
84    requires a default scale of 0, i.e., coercion to integer precision. We
85    find this a bit useless. If you're concerned about portability, always
86    specify the precision and scale explicitly.)
87
88 Note
89
90    The maximum precision that can be explicitly specified in a numeric
91    type declaration is 1000. An unconstrained numeric column is subject to
92    the limits described in Table 8.2.
93
94    If the scale of a value to be stored is greater than the declared scale
95    of the column, the system will round the value to the specified number
96    of fractional digits. Then, if the number of digits to the left of the
97    decimal point exceeds the declared precision minus the declared scale,
98    an error is raised. For example, a column declared as
99 NUMERIC(3, 1)
100
101    will round values to 1 decimal place and can store values between -99.9
102    and 99.9, inclusive.
103
104    Beginning in PostgreSQL 15, it is allowed to declare a numeric column
105    with a negative scale. Then values will be rounded to the left of the
106    decimal point. The precision still represents the maximum number of
107    non-rounded digits. Thus, a column declared as
108 NUMERIC(2, -3)
109
110    will round values to the nearest thousand and can store values between
111    -99000 and 99000, inclusive. It is also allowed to declare a scale
112    larger than the declared precision. Such a column can only hold
113    fractional values, and it requires the number of zero digits just to
114    the right of the decimal point to be at least the declared scale minus
115    the declared precision. For example, a column declared as
116 NUMERIC(3, 5)
117
118    will round values to 5 decimal places and can store values between
119    -0.00999 and 0.00999, inclusive.
120
121 Note
122
123    PostgreSQL permits the scale in a numeric type declaration to be any
124    value in the range -1000 to 1000. However, the SQL standard requires
125    the scale to be in the range 0 to precision. Using scales outside that
126    range may not be portable to other database systems.
127
128    Numeric values are physically stored without any extra leading or
129    trailing zeroes. Thus, the declared precision and scale of a column are
130    maximums, not fixed allocations. (In this sense the numeric type is
131    more akin to varchar(n) than to char(n).) The actual storage
132    requirement is two bytes for each group of four decimal digits, plus
133    three to eight bytes overhead.
134
135    In addition to ordinary numeric values, the numeric type has several
136    special values:
137
138    Infinity
139    -Infinity
140    NaN
141
142    These are adapted from the IEEE 754 standard, and represent “infinity”,
143    “negative infinity”, and “not-a-number”, respectively. When writing
144    these values as constants in an SQL command, you must put quotes around
145    them, for example UPDATE table SET x = '-Infinity'. On input, these
146    strings are recognized in a case-insensitive manner. The infinity
147    values can alternatively be spelled inf and -inf.
148
149    The infinity values behave as per mathematical expectations. For
150    example, Infinity plus any finite value equals Infinity, as does
151    Infinity plus Infinity; but Infinity minus Infinity yields NaN (not a
152    number), because it has no well-defined interpretation. Note that an
153    infinity can only be stored in an unconstrained numeric column, because
154    it notionally exceeds any finite precision limit.
155
156    The NaN (not a number) value is used to represent undefined
157    calculational results. In general, any operation with a NaN input
158    yields another NaN. The only exception is when the operation's other
159    inputs are such that the same output would be obtained if the NaN were
160    to be replaced by any finite or infinite numeric value; then, that
161    output value is used for NaN too. (An example of this principle is that
162    NaN raised to the zero power yields one.)
163
164 Note
165
166    In most implementations of the “not-a-number” concept, NaN is not
167    considered equal to any other numeric value (including NaN). In order
168    to allow numeric values to be sorted and used in tree-based indexes,
169    PostgreSQL treats NaN values as equal, and greater than all non-NaN
170    values.
171
172    The types decimal and numeric are equivalent. Both types are part of
173    the SQL standard.
174
175    When rounding values, the numeric type rounds ties away from zero,
176    while (on most machines) the real and double precision types round ties
177    to the nearest even number. For example:
178 SELECT x,
179   round(x::numeric) AS num_round,
180   round(x::double precision) AS dbl_round
181 FROM generate_series(-3.5, 3.5, 1) as x;
182   x   | num_round | dbl_round
183 ------+-----------+-----------
184  -3.5 |        -4 |        -4
185  -2.5 |        -3 |        -2
186  -1.5 |        -2 |        -2
187  -0.5 |        -1 |        -0
188   0.5 |         1 |         0
189   1.5 |         2 |         2
190   2.5 |         3 |         2
191   3.5 |         4 |         4
192 (8 rows)
193
194 8.1.3. Floating-Point Types #
195
196    The data types real and double precision are inexact,
197    variable-precision numeric types. On all currently supported platforms,
198    these types are implementations of IEEE Standard 754 for Binary
199    Floating-Point Arithmetic (single and double precision, respectively),
200    to the extent that the underlying processor, operating system, and
201    compiler support it.
202
203    Inexact means that some values cannot be converted exactly to the
204    internal format and are stored as approximations, so that storing and
205    retrieving a value might show slight discrepancies. Managing these
206    errors and how they propagate through calculations is the subject of an
207    entire branch of mathematics and computer science and will not be
208    discussed here, except for the following points:
209      * If you require exact storage and calculations (such as for monetary
210        amounts), use the numeric type instead.
211      * If you want to do complicated calculations with these types for
212        anything important, especially if you rely on certain behavior in
213        boundary cases (infinity, underflow), you should evaluate the
214        implementation carefully.
215      * Comparing two floating-point values for equality might not always
216        work as expected.
217
218    On all currently supported platforms, the real type has a range of
219    around 1E-37 to 1E+37 with a precision of at least 6 decimal digits.
220    The double precision type has a range of around 1E-307 to 1E+308 with a
221    precision of at least 15 digits. Values that are too large or too small
222    will cause an error. Rounding might take place if the precision of an
223    input number is too high. Numbers too close to zero that are not
224    representable as distinct from zero will cause an underflow error.
225
226    By default, floating point values are output in text form in their
227    shortest precise decimal representation; the decimal value produced is
228    closer to the true stored binary value than to any other value
229    representable in the same binary precision. (However, the output value
230    is currently never exactly midway between two representable values, in
231    order to avoid a widespread bug where input routines do not properly
232    respect the round-to-nearest-even rule.) This value will use at most 17
233    significant decimal digits for float8 values, and at most 9 digits for
234    float4 values.
235
236 Note
237
238    This shortest-precise output format is much faster to generate than the
239    historical rounded format.
240
241    For compatibility with output generated by older versions of
242    PostgreSQL, and to allow the output precision to be reduced, the
243    extra_float_digits parameter can be used to select rounded decimal
244    output instead. Setting a value of 0 restores the previous default of
245    rounding the value to 6 (for float4) or 15 (for float8) significant
246    decimal digits. Setting a negative value reduces the number of digits
247    further; for example -2 would round output to 4 or 13 digits
248    respectively.
249
250    Any value of extra_float_digits greater than 0 selects the
251    shortest-precise format.
252
253 Note
254
255    Applications that wanted precise values have historically had to set
256    extra_float_digits to 3 to obtain them. For maximum compatibility
257    between versions, they should continue to do so.
258
259    In addition to ordinary numeric values, the floating-point types have
260    several special values:
261
262    Infinity
263    -Infinity
264    NaN
265
266    These represent the IEEE 754 special values “infinity”, “negative
267    infinity”, and “not-a-number”, respectively. When writing these values
268    as constants in an SQL command, you must put quotes around them, for
269    example UPDATE table SET x = '-Infinity'. On input, these strings are
270    recognized in a case-insensitive manner. The infinity values can
271    alternatively be spelled inf and -inf.
272
273 Note
274
275    IEEE 754 specifies that NaN should not compare equal to any other
276    floating-point value (including NaN). In order to allow floating-point
277    values to be sorted and used in tree-based indexes, PostgreSQL treats
278    NaN values as equal, and greater than all non-NaN values.
279
280    PostgreSQL also supports the SQL-standard notations float and float(p)
281    for specifying inexact numeric types. Here, p specifies the minimum
282    acceptable precision in binary digits. PostgreSQL accepts float(1) to
283    float(24) as selecting the real type, while float(25) to float(53)
284    select double precision. Values of p outside the allowed range draw an
285    error. float with no precision specified is taken to mean double
286    precision.
287
288 8.1.4. Serial Types #
289
290 Note
291
292    This section describes a PostgreSQL-specific way to create an
293    autoincrementing column. Another way is to use the SQL-standard
294    identity column feature, described at Section 5.3.
295
296    The data types smallserial, serial and bigserial are not true types,
297    but merely a notational convenience for creating unique identifier
298    columns (similar to the AUTO_INCREMENT property supported by some other
299    databases). In the current implementation, specifying:
300 CREATE TABLE tablename (
301     colname SERIAL
302 );
303
304    is equivalent to specifying:
305 CREATE SEQUENCE tablename_colname_seq AS integer;
306 CREATE TABLE tablename (
307     colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
308 );
309 ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
310
311    Thus, we have created an integer column and arranged for its default
312    values to be assigned from a sequence generator. A NOT NULL constraint
313    is applied to ensure that a null value cannot be inserted. (In most
314    cases you would also want to attach a UNIQUE or PRIMARY KEY constraint
315    to prevent duplicate values from being inserted by accident, but this
316    is not automatic.) Lastly, the sequence is marked as “owned by” the
317    column, so that it will be dropped if the column or table is dropped.
318
319 Note
320
321    Because smallserial, serial and bigserial are implemented using
322    sequences, there may be "holes" or gaps in the sequence of values which
323    appears in the column, even if no rows are ever deleted. A value
324    allocated from the sequence is still "used up" even if a row containing
325    that value is never successfully inserted into the table column. This
326    may happen, for example, if the inserting transaction rolls back. See
327    nextval() in Section 9.17 for details.
328
329    To insert the next value of the sequence into the serial column,
330    specify that the serial column should be assigned its default value.
331    This can be done either by excluding the column from the list of
332    columns in the INSERT statement, or through the use of the DEFAULT key
333    word.
334
335    The type names serial and serial4 are equivalent: both create integer
336    columns. The type names bigserial and serial8 work the same way, except
337    that they create a bigint column. bigserial should be used if you
338    anticipate the use of more than 2^31 identifiers over the lifetime of
339    the table. The type names smallserial and serial2 also work the same
340    way, except that they create a smallint column.
341
342    The sequence created for a serial column is automatically dropped when
343    the owning column is dropped. You can drop the sequence without
344    dropping the column, but this will force removal of the column default
345    expression.