12. Managing Tables
Data types
(cover the most commonly used PostgreSQL data types.)
Boolean
1, yes, y, t, true => true
0, no, false, f => false
Character
CHAR(n)
fixed length character with space padded. string shorter than length n will be padded by spaces, string longer than length will cause error
VARCHAR(n)
variable length character string. Postgres does not pad spaces when length is shorter than n
TEXT
variable length character string. Theoretically, text data is character string with unlimited length
Numberic
Integers
Small integer (
SMALLINT
) is 2 byte signed integerInteger (
INT
) is 4 byte signed integerSerial is same as integer except that postgres will auto generate and populate values into
SERIAL
column. It is similar toAUTO_INCREMENT
column in MySQL orAUTOINCREMENT
in SqLite
Floating point numbers
float(n)
is floating point number precious at least n upto max 8 bytesreal
orfloat8
is 4 byte floating point numbernumeric
ornumeric(p,s)
is real number with p digits with s number after decimal point
Temporal data types
DATE
stores the dates onlyTIME
stores the time of day valuesTIMESTAMP
stores both date and time valuesTIMESTAMPZ
is timezone aware timestamp data type. It is postgres extension to sql standard temporal data typesINTERVAL
stores periods of time
Arrays
In Postgres, we can store array of strings, array of integers, etc, in array columns. It comes handy in some situations like storing days of week, months of year, etc
JSON
Posgres provides two JSON data types
JSON
stores plain JSON data that require reparsing for each processingJSONB
stores JSON data in binary format which is faster to process but slower to insert. It also supports indexing which can be advantegeous
UUID
It allows us to store Universal Unique Identifiers. The UUID
values guarentee a better uniqueness than SERIAL
and can be used to hide sensitive data exposed to public such as values of id
in URL
Special data types
Postgres provides several special data types related to geometric and netowrk
box
a rectangular boxline
a set of pointspoint
a geometric pair of numberslseg
a line segmentpolygon
a closed geometricinet
an IPv4 addressmacaddr
a MAC address
Create a table
(guide you on how to create a new table in the database.)
We can use the
CREATE TABLE
statement whose syntax is
Constraints
NOT NULL
ensures values can not be NULLUNIQUE
ensures values in a column are unique across rowsPRIMARY KEY
uniquely identifies rows in a table, a table can have one and only one primary keyCHECK
ensures that data must satisfy a boolean expressionFOREIGN KEY
ensures values in a column or a group of columns from a table exists in a column or group of columns in another table. A table can have many foreign keys
Example
Accounts table
Roles table
Account Roles table
Select Into & Create table as
(shows you how to create a new table from the result set of a query.)
PostgreSQL
SELECT INTO
statement creates a new table and inserts data returned from a query into the table.Its syntax is
The TEMP or TEMPORARY keyword is optional; it allows you to create a temporary table instead.
The UNLOGGED keyword if available will make the new table as an unlogged table.
Besides the WHERE clause, you can use other clauses in the SELECT statement for the SELECT INTO statement such as INNER JOIN, LEFT JOIN, GROUP BY, and HAVING.
Note that you cannot use the
SELECT INTO
statement in PL/pgSQL because it interprets the INTO clause differently. In this case, you can use theCREATE TABLE AS
statement which provides more functionality than the SELECT INTO statement. Its syntax is
Example
Suppose we have a film table
Create a new table film_r
that contains film with R rating and rental duration 5 days from film
table
Auto-increment column with SERIAL
(uses SERIAL to add an auto-increment column to a table.)
By assigning the
SERIAL
pseudo-type to theid
column, PostgreSQL performs the following:First, create a sequence object and set the next value generated by the sequence as the default value for the column.
Second, add a NOT NULL constraint to the id column because a sequence always generates an integer, which is a non-null value.
Third, assign the owner of the sequence to the id column; as a result, the sequence object is deleted when the id column or table is dropped
Sequences
(introduce you to sequences and describe how to use a sequence to generate a sequence of numbers.)
A sequence in PostgreSQL is a user-defined schema-bound object that generates a sequence of integers based on a specified specification.
We can use
CREATE SEQUENCE
statementIts syntax is
Identity column
(show you how to use the identity column.)
PostgreSQL version 10 introduced a new constraint GENERATED AS IDENTITY that allows you to automatically assign a unique number to a column.
Its syntax is
The type can be SMALLINT, INT, or BIGINT.
The
GENERATED ALWAYS
instructs PostgreSQL to always generate a value for the identity column. If you attempt to insert (or update) values into the GENERATED ALWAYS AS IDENTITY column, PostgreSQL will issue an error.The
GENERATED BY DEFAULT
also instructs PostgreSQL to generate a value for the identity column. However, if you supply a value for insert or update, PostgreSQL will use that value to insert into the identity column instead of using the system-generated value.PostgreSQL allows you a table to have more than one identity column. Like the SERIAL, the GENERATED AS IDENTITY constraint also uses the
SEQUENCE
object internally.You can add identity columns to an existing table by using the following form of the
ALTER TABLE
statement
Example
Alter table
(modify the structure of an existing table.)
Rename table
(change the name of the table to a new one.)
Last updated