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
TEXTvariable 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
SERIALcolumn. It is similar toAUTO_INCREMENTcolumn in MySQL orAUTOINCREMENTin SqLite
Floating point numbers
float(n)is floating point number precious at least n upto max 8 bytesrealorfloat8is 4 byte floating point numbernumericornumeric(p,s)is real number with p digits with s number after decimal point
Temporal data types
DATEstores the dates onlyTIMEstores the time of day valuesTIMESTAMPstores both date and time valuesTIMESTAMPZis timezone aware timestamp data type. It is postgres extension to sql standard temporal data typesINTERVALstores 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
JSONstores plain JSON data that require reparsing for each processingJSONBstores 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
boxa rectangular boxlinea set of pointspointa geometric pair of numberslsega line segmentpolygona closed geometricinetan IPv4 addressmacaddra MAC address
Create a table
(guide you on how to create a new table in the database.)
We can use the
CREATE TABLEstatement whose syntax is
Constraints
NOT NULLensures values can not be NULLUNIQUEensures values in a column are unique across rowsPRIMARY KEYuniquely identifies rows in a table, a table can have one and only one primary keyCHECKensures that data must satisfy a boolean expressionFOREIGN KEYensures 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 INTOstatement 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 INTOstatement in PL/pgSQL because it interprets the INTO clause differently. In this case, you can use theCREATE TABLE ASstatement 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
SERIALpseudo-type to theidcolumn, 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 SEQUENCEstatementIts 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 ALWAYSinstructs 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 DEFAULTalso 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
SEQUENCEobject internally.You can add identity columns to an existing table by using the following form of the
ALTER TABLEstatement
Example


Alter table
(modify the structure of an existing table.)
Rename table
(change the name of the table to a new one.)
Last updated