Movatterモバイル変換


[0]ホーム

URL:



Facebook
Postgres Pro
Facebook
Downloads
8.1. Numeric Types
Prev UpChapter 8. Data TypesHome Next

8.1. Numeric Types

Numeric types consist of two-, four-, and eight-byte integers, four- and eight-byte floating-point numbers, and selectable-precision decimals.Table 8.2 lists the available types.

Table 8.2. Numeric Types

NameStorage SizeDescriptionRange
smallint2 bytessmall-range integer-32768 to +32767
integer4 bytestypical choice for integer-2147483648 to +2147483647
bigint8 byteslarge-range integer-9223372036854775808 to +9223372036854775807
decimalvariableuser-specified precision, exactup to 131072 digits before the decimal point; up to 16383 digits after the decimal point
numericvariableuser-specified precision, exactup to 131072 digits before the decimal point; up to 16383 digits after the decimal point
real4 bytesvariable-precision, inexact6 decimal digits precision
double precision8 bytesvariable-precision, inexact15 decimal digits precision
smallserial2 bytessmall autoincrementing integer1 to 32767
serial4 bytesautoincrementing integer1 to 2147483647
bigserial8 byteslarge autoincrementing integer1 to 9223372036854775807

The syntax of constants for the numeric types is described inSection 4.1.2. The numeric types have a full set of corresponding arithmetic operators and functions. Refer toChapter 9 for more information. The following sections describe the types in detail.

8.1.1. Integer Types

The typessmallint,integer, andbigint store whole numbers, that is, numbers without fractional components, of various ranges. Attempts to store values outside of the allowed range will result in an error.

The typeinteger is the common choice, as it offers the best balance between range, storage size, and performance. Thesmallint type is generally only used if disk space is at a premium. Thebigint type is designed to be used when the range of theinteger type is insufficient.

SQL only specifies the integer typesinteger (orint),smallint, andbigint. The type namesint2,int4, andint8 are extensions, which are also used by some otherSQL database systems.

The typenumeric can store numbers with a very large number of digits. It is especially recommended for storing monetary amounts and other quantities where exactness is required. Calculations withnumeric values yield exact results where possible, e.g., addition, subtraction, multiplication. However, calculations onnumeric values are very slow compared to the integer types, or to the floating-point types described in the next section.

We use the following terms below: theprecision of anumeric is the total count of significant digits in the whole number, that is, the number of digits to both sides of the decimal point. Thescale of anumeric is the count of decimal digits in the fractional part, to the right of the decimal point. So the number 23.5141 has a precision of 6 and a scale of 4. Integers can be considered to have a scale of zero.

Both the maximum precision and the maximum scale of anumeric column can be configured. To declare a column of typenumeric use the syntax:

NUMERIC(precision,scale)

The precision must be positive, the scale zero or positive. Alternatively:

NUMERIC(precision)

selects a scale of 0. Specifying:

NUMERIC

without any precision or scale creates a column in which numeric values of any precision and scale can be stored, up to the implementation limit on precision. A column of this kind will not coerce input values to any particular scale, whereasnumeric columns with a declared scale will coerce input values to that scale. (TheSQL standard requires a default scale of 0, i.e., coercion to integer precision. We find this a bit useless. If you're concerned about portability, always specify the precision and scale explicitly.)

If the scale of a value to be stored is greater than the declared scale of the column, the system will round the value to the specified number of fractional digits. Then, if the number of digits to the left of the decimal point exceeds the declared precision minus the declared scale, an error is raised.

Numeric values are physically stored without any extra leading or trailing zeroes. Thus, the declared precision and scale of a column are maximums, not fixed allocations. (In this sense thenumeric type is more akin tovarchar(n) than tochar(n).) The actual storage requirement is two bytes for each group of four decimal digits, plus three to eight bytes overhead.

In addition to ordinary numeric values, thenumeric type allows the special valueNaN, meaningnot-a-number. Any operation onNaN yields anotherNaN. When writing this value as a constant in an SQL command, you must put quotes around it, for exampleUPDATE table SET x = 'NaN'. On input, the stringNaN is recognized in a case-insensitive manner.

Note

In most implementations of thenot-a-number concept,NaN is not considered equal to any other numeric value (includingNaN). In order to allownumeric values to be sorted and used in tree-based indexes,Postgres Pro treatsNaN values as equal, and greater than all non-NaN values.

The typesdecimal andnumeric are equivalent. Both types are part of theSQL standard.

When rounding values, thenumeric type rounds ties away from zero, while (on most machines) thereal anddouble precision types round ties to the nearest even number. For example:

SELECT x,  round(x::numeric) AS num_round,  round(x::double precision) AS dbl_roundFROM generate_series(-3.5, 3.5, 1) as x;  x   | num_round | dbl_round------+-----------+----------- -3.5 |        -4 |        -4 -2.5 |        -3 |        -2 -1.5 |        -2 |        -2 -0.5 |        -1 |        -0  0.5 |         1 |         0  1.5 |         2 |         2  2.5 |         3 |         2  3.5 |         4 |         4(8 rows)

The data typesreal anddouble precision are inexact, variable-precision numeric types. In practice, these types are usually implementations ofIEEE Standard 754 for Binary Floating-Point Arithmetic (single and double precision, respectively), to the extent that the underlying processor, operating system, and compiler support it.

Inexact means that some values cannot be converted exactly to the internal format and are stored as approximations, so that storing and retrieving a value might show slight discrepancies. Managing these errors and how they propagate through calculations is the subject of an entire branch of mathematics and computer science and will not be discussed here, except for the following points:

On most platforms, thereal type has a range of at least 1E-37 to 1E+37 with a precision of at least 6 decimal digits. Thedouble precision type typically has a range of around 1E-307 to 1E+308 with a precision of at least 15 digits. Values that are too large or too small will cause an error. Rounding might take place if the precision of an input number is too high. Numbers too close to zero that are not representable as distinct from zero will cause an underflow error.

Note

Theextra_float_digits setting controls the number of extra significant digits included when a floating point value is converted to text for output. With the default value of0, the output is the same on every platform supported by Postgres Pro. Increasing it will produce output that more accurately represents the stored value, but may be unportable.

In addition to ordinary numeric values, the floating-point types have several special values:


Infinity
-Infinity
NaN

These represent the IEEE 754 special valuesinfinity,negative infinity, andnot-a-number, respectively. (On a machine whose floating-point arithmetic does not follow IEEE 754, these values will probably not work as expected.) When writing these values as constants in an SQL command, you must put quotes around them, for exampleUPDATE table SET x = 'Infinity'. On input, these strings are recognized in a case-insensitive manner.

Note

IEEE754 specifies thatNaN should not compare equal to any other floating-point value (includingNaN). In order to allow floating-point values to be sorted and used in tree-based indexes,Postgres Pro treatsNaN values as equal, and greater than all non-NaN values.

Postgres Pro also supports the SQL-standard notationsfloat andfloat(p) for specifying inexact numeric types. Here,p specifies the minimum acceptable precision inbinary digits.Postgres Pro acceptsfloat(1) tofloat(24) as selecting thereal type, whilefloat(25) tofloat(53) selectdouble precision. Values ofp outside the allowed range draw an error.float with no precision specified is taken to meandouble precision.

Note

The assumption thatreal anddouble precision have exactly 24 and 53 bits in the mantissa respectively is correct for IEEE-standard floating point implementations. On non-IEEE platforms it might be off a little, but for simplicity the same ranges ofp are used on all platforms.

8.1.4. Serial Types

The data typessmallserial,serial andbigserial are not true types, but merely a notational convenience for creating unique identifier columns (similar to theAUTO_INCREMENT property supported by some other databases). In the current implementation, specifying:

CREATE TABLEtablename (colname SERIAL);

is equivalent to specifying:

CREATE SEQUENCEtablename_colname_seq;CREATE TABLEtablename (colname integer NOT NULL DEFAULT nextval('tablename_colname_seq'));ALTER SEQUENCEtablename_colname_seq OWNED BYtablename.colname;

Thus, we have created an integer column and arranged for its default values to be assigned from a sequence generator. ANOT NULL constraint is applied to ensure that a null value cannot be inserted. (In most cases you would also want to attach aUNIQUE orPRIMARY KEY constraint to prevent duplicate values from being inserted by accident, but this is not automatic.) Lastly, the sequence is marked asowned by the column, so that it will be dropped if the column or table is dropped.

Note

Becausesmallserial,serial andbigserial are implemented using sequences, there may be "holes" or gaps in the sequence of values which appears in the column, even if no rows are ever deleted. A value allocated from the sequence is still "used up" even if a row containing that value is never successfully inserted into the table column. This may happen, for example, if the inserting transaction rolls back. Seenextval() inSection 9.16 for details.

To insert the next value of the sequence into theserial column, specify that theserial column should be assigned its default value. This can be done either by excluding the column from the list of columns in theINSERT statement, or through the use of theDEFAULT key word.

The type namesserial andserial4 are equivalent: both createinteger columns. The type namesbigserial andserial8 work the same way, except that they create abigint column.bigserial should be used if you anticipate the use of more than 231 identifiers over the lifetime of the table. The type namessmallserial andserial2 also work the same way, except that they create asmallint column.

The sequence created for aserial column is automatically dropped when the owning column is dropped. You can drop the sequence without dropping the column, but this will force removal of the column default expression.


Prev Home Next
Chapter 8. Data Types Up 8.2. Monetary Types
pdfepub
Go to Postgres Pro Standard 9.6
By continuing to browse this website, you agree to the use of cookies. Go toPrivacy Policy.

[8]ページ先頭

©2009-2025 Movatter.jp