Scott Marlowe Serial is a 'macro' that makes postgresql do a couple of things all at once. Let's take a look at the important parts of that by running a create table with a serial keyword, and then examining the table, shall we? Est= create table test (id serial primary key, info text); NOTICE: CREATE TABLE will create implicit sequence 'testidseq' for 'serial' column 'test.id' NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index 'testpkey' for table 'test' CREATE TABLE test= d test Table. On Tue, 2004-07-27 at 11:16, Prabu Subroto wrote: Dear my friends.
I am using postgres 7.4 and SuSE 9.1. I want to use autoincrement as on MySQL. I look up the documentation on www.postgres.com and I found 'serial'. But I don't know how to create autoincrement. Here is my try: ' kv=# alter table sales alter column salesid int4 serial; ERROR: syntax error at or near 'int4' at character 40 'Serial is a 'macro' that makes postgresql do a couple of things all at once. Let's take a look at the important parts of that by running a create table with a serial keyword, and then examining the table, shall we? Prabu Subroto Dear Scott.
So I can not use 'alter table' to define a column with int data type? Here is the detail condition: I have created a table 'sales'. And I forgot to define autoincrement for primary key 'salesid' (int4). The table has already contented the data. I built an application with Qt.
I thougt that I can define a column with autoincrement function afterall. I want my application program only has to insert 'firstname', 'lastname' etc. And the database server (postgres) will put. So I can not use 'alter table' to define a column with int data type?
Here is the detail condition: I have created a table 'sales'. And I forgot to define autoincrement for primary key 'salesid' (int4). The table has already contented the data. I built an application with Qt. I thougt that I can define a column with autoincrement function afterall. I want my application program only has to insert 'firstname', 'lastname' etc. And the database server (postgres) will put the increment value into the salesid automatically.
If I read your suggestion, that means.I have drop the column 'salesid' and re-create the column 'salesid'. And it means, I will the data in the current 'salesid' column. Do you have further suggestion? Thank you very much in advance. Scott Marlowe wrote. On Tue, 2004-07-27 at 11:16, Prabu Subroto wrote: Dear my friends. I am using postgres 7.4 and SuSE 9.1.
I want to use autoincrement as on MySQL. I look up the documentation on www.postgres.com and I found 'serial'. But I don't know how to create autoincrement. Here is my try: ' kv=# alter table sales alter column salesid int4 serial; ERROR: syntax error at or near 'int4' at character 40 'Serial is a 'macro' that makes postgresql do a couple of things all at once. Let's take a look at the important parts of that by running a create table with a serial keyword, and then examining the table, shall we?
Prabu Subroto writes: If I read your suggestion, that means.I have drop the column 'salesid' and re-create the column 'salesid'. And it means, I will the data in the current 'salesid' column. Do you have further suggestion?You can do it 'by hand' without dropping the column: CREATE SEQUENCE salesidseq; SELECT setval('salesidseq', (SELECT max(salesid) FROM sales) + 1); ALTER TABLE sales ALTER COLUMN salesid DEFAULT nextval('salesidseq'); This is the same thing that the SERIAL datatype does 'behind the scenes'. I can't vouch for the exact syntax of the above but that should get you started.
If I read your suggestion, that means.I have drop the column 'salesid' and re-create the column 'salesid'. And it means, I will the data in the current 'salesid' column. Do you have further suggestion?You can do it 'by hand' without dropping the column: CREATE SEQUENCE salesidseq; SELECT setval('salesidseq', (SELECT max(salesid) FROM sales) + 1); ALTER TABLE sales ALTER COLUMN salesid DEFAULT nextval('salesidseq'); This is the same thing that the SERIAL datatype does 'behind the scenes'. I can't vouch for the exact syntax of the above but that should get you started.Doug - Let us cross over the river, and rest under the shade of the trees. Jackson, 1863 Do you Yahoo!? Prabu Subroto OK I did it: create sequence salessalesidseq; alter table sales alter column salesid set default nextval('salessalesidseq'); but a new problem comes, because the table 'sales' is not empty.
If the sequence counter reach a value that already exists in the table 'sales' than of course comes this error message: ' kv=# insert into sales (firstname) values ('baru5'); ERROR: duplicate key violates unique constraint 'salespkey' ' so now I think the only one solution is to set the starting. OK I did it: create sequence salessalesidseq; alter table sales alter column salesid set default nextval('salessalesidseq'); but a new problem comes, because the table 'sales' is not empty. If the sequence counter reach a value that already exists in the table 'sales' than of course comes this error message: ' kv=# insert into sales (firstname) values ('baru5'); ERROR: duplicate key violates unique constraint 'salespkey' ' so now I think the only one solution is to set the starting counter for the 'serial' macro, for instance to: '501' (the maximum current values of column salesid is 500). Anybody has a solution?
Thank you very much in advance. Prabu Subroto wrote.
So I can not use 'alter table' to define a column with int data type? Here is the detail condition: I have created a table 'sales'. And I forgot to define autoincrement for primary key 'salesid' (int4). The table has already contented the data. I built an application with Qt. I thougt that I can define a column with autoincrement function afterall. I want my application program only has to insert 'firstname', 'lastname' etc.
And the database server (postgres) will put the increment value into the salesid automatically. If I read your suggestion, that means.I have drop the column 'salesid' and re-create the column 'salesid'. And it means, I will the data in the current 'salesid' column. Do you have further suggestion? Thank you very much in advance. Scott Marlowe wrote.
But I don't know how to create autoincrement. Here is my try: ' kv=# alter table sales alter column salesid int4 serial; ERROR: syntax error at or near 'int4' at character 40 'Serial is a 'macro' that makes postgresql do a couple of things all at once. Let's take a look at the important parts of that by running a create table with a serial keyword, and then examining the table, shall we? Est= create table test (id serial primary key, info text); NOTICE: CREATE TABLE will create implicit sequence 'testidseq' for 'serial' column 'test.id' NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index 'testpkey' for table 'test' CREATE TABLE test= d test Table 'public.test' Column Type Modifiers-+-+. Id integer not null default nextval('public.testidseq'::text) info text Indexes: 'testpkey' primary key, btree (id) test= ds List of relations Schema Name Type Owner -+-+-+- public testidseq sequence smarlowe (1 row) Now, as well as creating the table and sequence, postgresql has, in the background, created a dependency for the sequence on the table. This means that if we drop the table, the sequence created by the create table statement will disappear as well.
Now, you were close, first you need to add a column of the proper type, create a sequence and tell the table to use that sequence as the default. Let's assume I'd made the table test like this: test= create table test (info text); CREATE TABLE test= And now I want to add an auto incrementing column. OK I did it: create sequence salessalesidseq; alter table sales alter column salesid set default nextval('salessalesidseq'); but a new problem comes, because the table 'sales' is not empty. If the sequence counter reach a value that already exists in the table 'sales' than of course comes this error message: ' kv=# insert into sales (firstname) values ('baru5'); ERROR: duplicate key violates unique constraint 'salespkey' ' so now I think the only one solution is to set the starting counter for the 'serial' macro, for instance to: '501' (the maximum current values of column salesid is 500). Anybody has a solution? Thank you very much in advance. Prabu Subroto wrote.
So I can not use 'alter table' to define a column with int data type? Here is the detail condition: I have created a table 'sales'. And I forgot to define autoincrement for primary key 'salesid' (int4).
The table has already contented the data. I built an application with Qt. I thougt that I can define a column with autoincrement function afterall.
I want my application program only has to insert 'firstname', 'lastname' etc. And the database server (postgres) will put the increment value into the salesid automatically. If I read your suggestion, that means.I have drop the column 'salesid' and re-create the column 'salesid'. And it means, I will the data in the current 'salesid' column. Do you have further suggestion? Thank you very much in advance. Scott Marlowe wrote.
But I don't know how to create autoincrement. Here is my try: ' kv=# alter table sales alter column salesid int4 serial; ERROR: syntax error at or near 'int4' at character 40 'Serial is a 'macro' that makes postgresql do a couple of things all at once. Let's take a look at the important parts of that by running a create table with a serial keyword, and then examining the table, shall we? Est= create table test (id serial primary key, info text); NOTICE: CREATE TABLE will create implicit sequence 'testidseq' for 'serial' column 'test.id' NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index 'testpkey' for table 'test' CREATE TABLE test= d test Table 'public.test' Column Type Modifiers-+-+. Zebra card studio free download. Id integer not null default nextval('public.testidseq'::text) info text Indexes: 'testpkey' primary key, btree (id) test= ds List of relations Schema Name Type Owner -+-+-+- public testidseq sequence smarlowe (1 row) Now, as well as creating the table and sequence, postgresql has, in the background, created a dependency for the sequence on the table.
This means that if we drop the table, the sequence created by the create table statement will disappear as well. Now, you were close, first you need to add a column of the proper type, create a sequence and tell the table to use that sequence as the default. Let's assume I'd made the table test like this: test= create table test (info text); CREATE TABLE test= And now I want to add an auto incrementing column. OK I did it: create sequence salessalesidseq; alter table sales alter column salesid set default nextval('salessalesidseq'); but a new problem comes, because the table 'sales' is not empty. If the sequence counter reach a value that already exists in the table 'sales' than of course comes this error message: ' kv=# insert into sales (firstname) values ('baru5'); ERROR: duplicate key violates unique constraint 'salespkey' ' so now I think the only one solution is to set the starting counter for the 'serial' macro, for instance to: '501' (the maximum current values of column salesid is 500).
Anybody has a solution? Thank you very much in advance.
Prabu Subroto wrote. Id integer not null default nextval('public.testidseq'::text) info text Indexes: 'testpkey' primary key, btree (id) test= ds List of relations Schema Name Type Owner -+-+-+- public testidseq sequence smarlowe (1 row) Now, as well as creating the table and sequence, postgresql has, in the background, created a dependency for the sequence on the table. This means that if we drop the table, the sequence created by the create table statement will disappear as well. Now, you were close, first you need to add a column of the proper type, create a sequence and tell the table to use that sequence as the default. Beachbody insanity affiliate program. Let's assume I'd made the table test like this: test= create table test (info text); CREATE TABLE test= And now I want to add an auto incrementingcolumn. We can't just add a serial because postgresql doesn't support setting defaults in an alter table, so we just add an int4, make a sequence, and assign the default: test= alter table test add id int4 unique; NOTICE: ALTER TABLE / ADD UNIQUE will create implicit index 'testidkey' for table 'test' ALTER TABLE test= create sequence testidseq; CREATE SEQUENCE test= alter table test alter column id set default nextval('testidseq'::text); ALTER TABLE message truncated Do you Yahoo!? Scott Marlowe As a followup, I thought you should know that in MySQL (on my box I'm running 3.23.58) if you do the following, you get some unintended consequences: mysql create table test (id varchar(10)); Query OK, 0 rows affected (0.01 sec) mysql insert into test values ('123'); Query OK, 1 row affected (0.00 sec) mysql insert into test values ('abc'); Query OK, 1 row affected (0.00 sec) mysql insert into test values ('a001'); Query OK, 1 row affected (0.00 sec) mysql insert into test values ('001a').
On Wed, 2004-07-28 at 06:09, Prabu Subroto wrote: Dear Scott. So I can not use 'alter table' to define a column with int data type? Here is the detail condition: I have created a table 'sales'. And I forgot to define autoincrement for primary key 'salesid' (int4). Id +-+ 123 0 0 1 +-+ 4 rows in set (0.00 sec) Notice that 123 and 001a got converted. Abc and a001 got plain dropped.
If you needed the data in that column, it's now gone. If you change the column back to varchar(10) the data is still gone. No error, so no chance to abort the change. Dear my friends. I am using postgres 7.4 and SuSE 9.1.
I want to use autoincrement as on MySQL. I look up the documentation on www.postgres.com and I found 'serial'. But I don't know how to create autoincrement. Here is my try: ' kv=# alter table sales alter column salesid int4 serial; ERROR: syntax error at or near 'int4' at character 40 ' Please tell me the correct command to that. Thank you very much in advance.
Do you Yahoo!? Mail - Helps protect you from nasty viruses.(end of broadcast)- TIP 6: Have you searched our list archives?
The types smallint, integer, and bigint 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 type integer is the common choice, as it offers the best balance between range, storage size, and performance. The smallint type is generally only used if disk space is at a premium. The bigint type is designed to be used when the range of the integer type is insufficient. SQL only specifies the integer types integer (or int), smallint, and bigint.
The type names int2, int4, and int8 are extensions, which are also used by some other SQL database systems. The type numeric 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. Snk vs capcom ultimate mugen. Calculations with numeric values yield exact results where possible, e.g. Addition, subtraction, multiplication.
However, calculations on numeric 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: The scale of a numeric is the count of decimal digits in the fractional part, to the right of the decimal point. The precision of a numeric is the total count of significant digits in the whole number, that is, the number of digits to both sides 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 a numeric column can be configured.
To declare a column of type numeric 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, whereas numeric columns with a declared scale will coerce input values to that scale. (The SQL 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.).
Note: The maximum allowed precision when explicitly specified in the type declaration is 1000; NUMERIC without a specified precision is subject to the limits described in. 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 the numeric type is more akin to varchar( n) than to char( 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, the numeric type allows the special value NaN, meaning 'not-a-number'.
Any operation on NaN yields another NaN. When writing this value as a constant in an SQL command, you must put quotes around it, for example UPDATE table SET x = 'NaN'. On input, the string NaN is recognized in a case-insensitive manner. Note: In most implementations of the 'not-a-number' concept, NaN is not considered equal to any other numeric value (including NaN). In order to allow numeric values to be sorted and used in tree-based indexes, PostgreSQL treats NaN values as equal, and greater than all non- NaN values. The types decimal and numeric are equivalent. Both types are part of the SQL standard.
When rounding values, the numeric type rounds ties away from zero, while (on most machines) the real and double precision types round ties to the nearest even number. For example: SELECT x, round(x::numeric) AS numround, round(x::double precision) AS dblround FROM generateseries(-3.5, 3.5, 1) as x; x numround dblround -+-+- -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 types real and double precision are inexact, variable-precision numeric types. In practice, these types are usually implementations of IEEE 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:. If you require exact storage and calculations (such as for monetary amounts), use the numeric type instead. If you want to do complicated calculations with these types for anything important, especially if you rely on certain behavior in boundary cases (infinity, underflow), you should evaluate the implementation carefully. Comparing two floating-point values for equality might not always work as expected. On most platforms, the real type has a range of at least 1E-37 to 1E+37 with a precision of at least 6 decimal digits. The double 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: The setting controls the number of extra significant digits included when a floating point value is converted to text for output. With the default value of 0, the output is the same on every platform supported by PostgreSQL.
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 NaNThese represent the IEEE 754 special values 'infinity', 'negative infinity', and 'not-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 example UPDATE table SET x = 'Infinity'. On input, these strings are recognized in a case-insensitive manner. Note: IEEE754 specifies that NaN should not compare equal to any other floating-point value (including NaN). In order to allow floating-point values to be sorted and used in tree-based indexes, PostgreSQL treats NaN values as equal, and greater than all non- NaN values.
PostgreSQL also supports the SQL-standard notations float and float( p) for specifying inexact numeric types. Here, p specifies the minimum acceptable precision in binary digits.
PostgreSQL accepts float(1) to float(24) as selecting the real type, while float(25) to float(53) select double precision. Values of p outside the allowed range draw an error. Float with no precision specified is taken to mean double precision. The data types smallserial, serial and bigserial are not true types, but merely a notational convenience for creating unique identifier columns (similar to the AUTOINCREMENT property supported by some other databases). In the current implementation, specifying: CREATE TABLE tablename ( colname SERIAL ); is equivalent to specifying: CREATE SEQUENCE tablename colnameseq; CREATE TABLE tablename ( colname integer NOT NULL DEFAULT nextval(' tablename colnameseq') ); ALTER SEQUENCE tablename colnameseq OWNED BY tablename. Colname; Thus, we have created an integer column and arranged for its default values to be assigned from a sequence generator. A NOT NULL constraint is applied to ensure that a null value cannot be inserted.
(In most cases you would also want to attach a UNIQUE or PRIMARY KEY constraint to prevent duplicate values from being inserted by accident, but this is not automatic.) Lastly, the sequence is marked as 'owned by' the column, so that it will be dropped if the column or table is dropped. Note: Because smallserial, serial and bigserial 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. See nextval in for details. To insert the next value of the sequence into the serial column, specify that the serial column should be assigned its default value. This can be done either by excluding the column from the list of columns in the INSERT statement, or through the use of the DEFAULT key word.
The type names serial and serial4 are equivalent: both create integer columns. The type names bigserial and serial8 work the same way, except that they create a bigint column. Bigserial should be used if you anticipate the use of more than 2 31 identifiers over the lifetime of the table. The type names smallserial and serial2 also work the same way, except that they create a smallint column. The sequence created for a serial 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.
The types smallint, integer, and bigint 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 type integer is the common choice, as it offers the best balance between range, storage size, and performance. The smallint type is generally only used if disk space is at a premium. The bigint type should only be used if the range of the integer type is insufficient, because the latter is definitely faster.
On very minimal operating systems the bigint type might not function correctly, because it relies on compiler support for eight-byte integers. On such machines, bigint acts the same as integer, but still takes up eight bytes of storage. (We are not aware of any modern platform where this is the case.) SQL only specifies the integer types integer (or int), smallint, and bigint. The type names int2, int4, and int8 are extensions, which are also used by some other SQL database systems. The type numeric can store numbers with a very large number of digits and perform calculations exactly.
It is especially recommended for storing monetary amounts and other quantities where exactness is required. However, arithmetic on numeric values is very slow compared to the integer types, or to the floating-point types described in the next section. We use the following terms below: The scale of a numeric is the count of decimal digits in the fractional part, to the right of the decimal point.
The precision of a numeric is the total count of significant digits in the whole number, that is, the number of digits to both sides 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 a numeric column can be configured. To declare a column of type numeric 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, whereas numeric columns with a declared scale will coerce input values to that scale.
(The SQL 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.). Note: The maximum allowed precision when explicitly specified in the type declaration is 1000; NUMERIC without a specified precision is subject to the limits described in. 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 the numeric type is more akin to varchar( n) than to char( 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, the numeric type allows the special value NaN, meaning 'not-a-number'. Any operation on NaN yields another NaN.
When writing this value as a constant in an SQL command, you must put quotes around it, for example UPDATE table SET x = 'NaN'. On input, the string NaN is recognized in a case-insensitive manner. The data types real and double precision are inexact, variable-precision numeric types. In practice, these types are usually implementations of IEEE 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:.
If you require exact storage and calculations (such as for monetary amounts), use the numeric type instead. If you want to do complicated calculations with these types for anything important, especially if you rely on certain behavior in boundary cases (infinity, underflow), you should evaluate the implementation carefully. Comparing two floating-point values for equality might not always work as expected. On most platforms, the real type has a range of at least 1E-37 to 1E+37 with a precision of at least 6 decimal digits. The double 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: The setting controls the number of extra significant digits included when a floating point value is converted to text for output. With the default value of 0, the output is the same on every platform supported by PostgreSQL.
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 NaNThese represent the IEEE 754 special values 'infinity', 'negative infinity', and 'not-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 example UPDATE table SET x = 'Infinity'.
On input, these strings are recognized in a case-insensitive manner. Note: IEEE754 specifies that NaN should not compare equal to any other floating-point value (including NaN).
In order to allow floating-point values to be sorted and used in tree-based indexes, PostgreSQL treats NaN values as equal, and greater than all non- NaN values. PostgreSQL also supports the SQL-standard notations float and float( p) for specifying inexact numeric types. Here, p specifies the minimum acceptable precision in binary digits. PostgreSQL accepts float(1) to float(24) as selecting the real type, while float(25) to float(53) select double precision. Values of p outside the allowed range draw an error. Float with no precision specified is taken to mean double precision. The data types serial and bigserial are not true types, but merely a notational convenience for creating unique identifier columns (similar to the AUTOINCREMENT property supported by some other databases).
In the current implementation, specifying: CREATE TABLE tablename ( colname SERIAL ); is equivalent to specifying: CREATE SEQUENCE tablename colnameseq; CREATE TABLE tablename ( colname integer NOT NULL DEFAULT nextval(' tablename colnameseq') ); ALTER SEQUENCE tablename colnameseq OWNED BY tablename. Colname; Thus, we have created an integer column and arranged for its default values to be assigned from a sequence generator. A NOT NULL constraint is applied to ensure that a null value cannot be inserted. (In most cases you would also want to attach a UNIQUE or PRIMARY KEY constraint to prevent duplicate values from being inserted by accident, but this is not automatic.) Lastly, the sequence is marked as 'owned by' the column, so that it will be dropped if the column or table is dropped.
Note: Prior to PostgreSQL 7.3, serial implied UNIQUE. This is no longer automatic. If you wish a serial column to have a unique constraint or be a primary key, it must now be specified, just like any other data type. To insert the next value of the sequence into the serial column, specify that the serial column should be assigned its default value.
This can be done either by excluding the column from the list of columns in the INSERT statement, or through the use of the DEFAULT key word. The type names serial and serial4 are equivalent: both create integer columns. The type names bigserial and serial8 work the same way, except that they create a bigint column. Bigserial should be used if you anticipate the use of more than 2 31 identifiers over the lifetime of the table. The sequence created for a serial 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.
The types smallint, integer, and bigint 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 type integer is the common choice, as it offers the best balance between range, storage size, and performance. The smallint type is generally only used if disk space is at a premium. The bigint type should only be used if the range of the integer type is insufficient, because the latter is definitely faster.
On very minimal operating systems the bigint type might not function correctly, because it relies on compiler support for eight-byte integers. On such machines, bigint acts the same as integer, but still takes up eight bytes of storage. (We are not aware of any modern platform where this is the case.) SQL only specifies the integer types integer (or int), smallint, and bigint. The type names int2, int4, and int8 are extensions, which are also used by some other SQL database systems. The type numeric can store numbers with a very large number of digits and perform calculations exactly.
It is especially recommended for storing monetary amounts and other quantities where exactness is required. However, arithmetic on numeric values is very slow compared to the integer types, or to the floating-point types described in the next section. We use the following terms below: The scale of a numeric is the count of decimal digits in the fractional part, to the right of the decimal point. The precision of a numeric is the total count of significant digits in the whole number, that is, the number of digits to both sides 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 a numeric column can be configured.
To declare a column of type numeric 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, whereas numeric columns with a declared scale will coerce input values to that scale.
(The SQL 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.). Note: The maximum allowed precision when explicitly specified in the type declaration is 1000; NUMERIC without a specified precision is subject to the limits described in. 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 the numeric type is more akin to varchar( n) than to char( 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, the numeric type allows the special value NaN, meaning 'not-a-number'. Any operation on NaN yields another NaN. When writing this value as a constant in an SQL command, you must put quotes around it, for example UPDATE table SET x = 'NaN'.
On input, the string NaN is recognized in a case-insensitive manner. The data types real and double precision are inexact, variable-precision numeric types. In practice, these types are usually implementations of IEEE 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:. If you require exact storage and calculations (such as for monetary amounts), use the numeric type instead. If you want to do complicated calculations with these types for anything important, especially if you rely on certain behavior in boundary cases (infinity, underflow), you should evaluate the implementation carefully. Comparing two floating-point values for equality might not always work as expected.
On most platforms, the real type has a range of at least 1E-37 to 1E+37 with a precision of at least 6 decimal digits. The double 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: The setting controls the number of extra significant digits included when a floating point value is converted to text for output.
With the default value of 0, the output is the same on every platform supported by PostgreSQL. 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 NaNThese represent the IEEE 754 special values 'infinity', 'negative infinity', and 'not-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 example UPDATE table SET x = 'Infinity'. On input, these strings are recognized in a case-insensitive manner. Note: IEEE754 specifies that NaN should not compare equal to any other floating-point value (including NaN). In order to allow floating-point values to be sorted and used in tree-based indexes, PostgreSQL treats NaN values as equal, and greater than all non- NaN values.
PostgreSQL also supports the SQL-standard notations float and float( p) for specifying inexact numeric types. Here, p specifies the minimum acceptable precision in binary digits. PostgreSQL accepts float(1) to float(24) as selecting the real type, while float(25) to float(53) select double precision. Values of p outside the allowed range draw an error. Float with no precision specified is taken to mean double precision.
The data types serial and bigserial are not true types, but merely a notational convenience for creating unique identifier columns (similar to the AUTOINCREMENT property supported by some other databases). In the current implementation, specifying: CREATE TABLE tablename ( colname SERIAL ); is equivalent to specifying: CREATE SEQUENCE tablename colnameseq; CREATE TABLE tablename ( colname integer NOT NULL DEFAULT nextval(' tablename colnameseq') ); ALTER SEQUENCE tablename colnameseq OWNED BY tablename. Colname; Thus, we have created an integer column and arranged for its default values to be assigned from a sequence generator.
A NOT NULL constraint is applied to ensure that a null value cannot be inserted. (In most cases you would also want to attach a UNIQUE or PRIMARY KEY constraint to prevent duplicate values from being inserted by accident, but this is not automatic.) Lastly, the sequence is marked as 'owned by' the column, so that it will be dropped if the column or table is dropped. Note: Prior to PostgreSQL 7.3, serial implied UNIQUE.
This is no longer automatic. If you wish a serial column to have a unique constraint or be a primary key, it must now be specified, just like any other data type. To insert the next value of the sequence into the serial column, specify that the serial column should be assigned its default value.
This can be done either by excluding the column from the list of columns in the INSERT statement, or through the use of the DEFAULT key word. The type names serial and serial4 are equivalent: both create integer columns. The type names bigserial and serial8 work the same way, except that they create a bigint column. Bigserial should be used if you anticipate the use of more than 2 31 identifiers over the lifetime of the table.
The sequence created for a serial 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.
Table of Contents 8.1. PostgreSQL has a rich set of native data types available to users. Users may add new types to PostgreSQL using the command.
Shows all the built-in general-purpose data types. Most of the alternative names listed in the 'Aliases' column are the names used internally by PostgreSQL for historical reasons. In addition, some internally used or deprecated types are available, but they are not listed here. Compatibility: The following types (or spellings thereof) are specified by SQL: bit, bit varying, boolean, char, character varying, character, varchar, date, double precision, integer, interval, numeric, decimal, real, smallint, time (with or without time zone), timestamp (with or without time zone).
Each data type has an external representation determined by its input and output functions. Many of the built-in types have obvious external formats. However, several types are either unique to PostgreSQL, such as geometric paths, or have several possibilities for formats, such as the date and time types. Some of the input and output functions are not invertible. That is, the result of an output function may lose accuracy when compared to the original input. The types smallint, integer, and bigint 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 type integer is the usual choice, as it offers the best balance between range, storage size, and performance. The smallint type is generally only used if disk space is at a premium. The bigint type should only be used if the integer range is not sufficient, because the latter is definitely faster. The bigint type may not function correctly on all platforms, since it relies on compiler support for eight-byte integers. On a machine without such support, bigint acts the same as integer (but still takes up eight bytes of storage). However, we are not aware of any reasonable platform where this is actually the case. SQL only specifies the integer types integer (or int) and smallint.
The type bigint, and the type names int2, int4, and int8 are extensions, which are shared with various other SQL database systems. The type numeric can store numbers with up to 1000 digits of precision and perform calculations exactly.
It is especially recommended for storing monetary amounts and other quantities where exactness is required. However, arithmetic on numeric values is very slow compared to the integer types, or to the floating-point types described in the next section. In what follows we use these terms: The scale of a numeric is the count of decimal digits in the fractional part, to the right of the decimal point. The precision of a numeric is the total count of significant digits in the whole number, that is, the number of digits to both sides 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 a numeric column can be configured. To declare a column of type numeric 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, whereas numeric columns with a declared scale will coerce input values to that scale. (The SQL 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 the numeric type is more akin to varchar( n) than to char( n).) The actual storage requirement is two bytes for each group of four decimal digits, plus eight bytes overhead. In addition to ordinary numeric values, the numeric type allows the special value NaN, meaning 'not-a-number'.
Any operation on NaN yields another NaN. When writing this value as a constant in a SQL command, you must put quotes around it, for example UPDATE table SET x = 'NaN'. On input, the string NaN is recognized in a case-insensitive manner.
The types decimal and numeric are equivalent. Both types are part of the SQL standard. The data types real and double precision are inexact, variable-precision numeric types. In practice, these types are usually implementations of IEEE 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 printing back out a value may 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 further here, except for the following points:.
If you require exact storage and calculations (such as for monetary amounts), use the numeric type instead. If you want to do complicated calculations with these types for anything important, especially if you rely on certain behavior in boundary cases (infinity, underflow), you should evaluate the implementation carefully. Comparing two floating-point values for equality may or may not work as expected. On most platforms, the real type has a range of at least 1E-37 to 1E+37 with a precision of at least 6 decimal digits. The double precision type typically has a range of around 1E-307 to 1E+308 with a precision of at least 15 digits.
Date/Time Types
Values that are too large or too small will cause an error. Rounding may 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.
In addition to ordinary numeric values, the floating-point types have several special values: Infinity -Infinity NaNThese represent the IEEE 754 special values 'infinity', 'negative infinity', and 'not-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 a SQL command, you must put quotes around them, for example UPDATE table SET x = 'Infinity'. On input, these strings are recognized in a case-insensitive manner. PostgreSQL also supports the SQL-standard notations float and float( p) for specifying inexact numeric types. Here, p specifies the minimum acceptable precision in binary digits. PostgreSQL accepts float(1) to float(24) as selecting the real type, while float(25) to float(53) select double precision.
Values of p outside the allowed range draw an error. Float with no precision specified is taken to mean double precision.
The data types serial and bigserial are not true types, but merely a notational convenience for setting up unique identifier columns (similar to the AUTOINCREMENT property supported by some other databases). In the current implementation, specifying CREATE TABLE tablename ( colname SERIAL ); is equivalent to specifying: CREATE SEQUENCE tablename colnameseq; CREATE TABLE tablename ( colname integer DEFAULT nextval(' tablename colnameseq') NOT NULL ); Thus, we have created an integer column and arranged for its default values to be assigned from a sequence generator. A NOT NULL constraint is applied to ensure that a null value cannot be explicitly inserted, either. In most cases you would also want to attach a UNIQUE or PRIMARY KEY constraint to prevent duplicate values from being inserted by accident, but this is not automatic.
Note: Prior to PostgreSQL 7.3, serial implied UNIQUE. This is no longer automatic.
Bit String Types
If you wish a serial column to be in a unique constraint or a primary key, it must now be specified, same as with any other data type. To insert the next value of the sequence into the serial column, specify that the serial column should be assigned its default value. This can be done either by excluding the column from the list of columns in the INSERT statement, or through the use of the DEFAULT key word. The type names serial and serial4 are equivalent: both create integer columns. The type names bigserial and serial8 work just the same way, except that they create a bigint column. Bigserial should be used if you anticipate the use of more than 2 31 identifiers over the lifetime of the table. The sequence created for a serial column is automatically dropped when the owning column is dropped, and cannot be dropped otherwise.
(This was not true in PostgreSQL releases before 7.3. Note that this automatic drop linkage will not occur for a sequence created by reloading a dump from a pre-7.3 database; the dump file does not contain the information needed to establish the dependency link.) Furthermore, this dependency between sequence and column is made only for the serial column itself. If any other columns reference the sequence (perhaps by manually calling the nextval function), they will be broken if the sequence is removed.
Using a serial column's sequence in such a fashion is considered bad form; if you wish to feed several columns from the same sequence generator, create the sequence as an independent object.