Data Types

Casting values

You can cast values in postgres with ::.

triangle-exclamation
-- This way postgres will treat it as `integer` instead of `numeric`
SELECT (2.0::integer)

Data Types

Array

Every data type has its own companion array type e.g. text[], integer[][].

circle-exclamation
Type
Description

type[]

One-dimensional or multi-dimensional arrays

How values are inserted

INSERT INTO table_name (col_array)
VALUES (ARRAY ['a', 'b', 'c'])
;
circle-info

Inside the table, their are stored between brackets like {a,b,c}.

Selecting values

triangle-exclamation
circle-info

If specfic index don't exists NULL is returned.

Comparing arrays

Using comparison operators like =, !=, <, > between array values, will run them in the array's values and the length.

Use ALL or ANY/SOME apply a condition method to all or some of the array values.

Combining arrays

Use || to combine arrays.

Adding values to array

Also use || to add values to arrays.

circle-exclamation

Remove values from array

Get arrays metadata

Search values in array

Unesting array values

unnest will split the array data into separate rows when selecting.

Bit String

Type
Description

bit(n)

Fixed-length bit string

bit varying(n)

Variable-length bit string

Boolean

circle-info

Some values are valid literals for booleans, but must be enclosed in single quotes.

  • 'true', 'false'

  • 't', 'f'

  • 'y', 'n'

  • 'yes', 'no'

  • '1', '0'

Type
Description

boolean

Stores TRUE, FALSE, or NULL

Composite (Objects)

These are user defined data types that can hold multiple types of value.

Type
Description

row

Custom record-like structures

How to insert with this data type

Use the ROW() to insert values for a composite type.

How to select the data

Character

circle-exclamation
circle-exclamation
circle-exclamation
Type
Description

char(n)

Fixed-length string (Spaces are added to pad at the end)

varchar(n)

Variable-length string, with limit

text

Variable unlimited-length string

Convert function (to_chararrow-up-right)

Convert an expression that can be multiple types of data to string. (Check format options in the docs)

Date/Time

Type
Description

timestamp

Date and time (no timezone)

timestamptz

Timestamp with timezone (default to system's TimeZone parameter)

date

Calendar date (year, month, day)

time

Time of day (no date, no timezone)

timetz

Time with timezone

interval

Time span (e.g., 3 days, 2 hours)

circle-exclamation
circle-info

Get the current date with the keyword CURRENT_DATE.

Get the current timestamp with NOW() or CURRENT_TIMESTAMP. (NOW also brings the timezone)

Get the current time with CURRENT_TIME.

Get the local time with LOCALTIME.

Operations with dates and times

circle-info

interval accept values like interval 'n type' where:

  • n is a desired number.

  • type is value type like "second", "minute", "hour", "day", "month", "year", ...

Operations with timezones

Using timezone() to convert time, based on a timezone.

Showing Postgres timezone

Handling timezones

circle-exclamation

Converts a string to date. (Check format options in the docs)

Convert dates to formats

With Convert function (to_char).

Extracting data from a date value

Check more types of fields on the docsarrow-up-right.

Check for date ranges overlap

Will check if date-range2 overlaps with date-range1.

circle-info

date-range2 doesn't have to be totally inside date-range1.

Showing Age between two dates

AGE returns the number of years, months and days between two dates.

Using infinity as date value

Use infinity or -infinity as values in dates or timestamps to indicate the highest or lowest value possible.

Enumerated

Type
Description

enum

Custom, user-defined list of valid string values

Add more values to the Enum

How to insert values with Enum

Drop Enum types

Geometric

Type
Description

point

(x, y) coordinate

line

Infinite line

lseg

Line segment

box

Rectangular box

path

Closed/open path

polygon

Polygon

circle

Center and radius

Json & Jsonb

The json datatype is actually text under the hood, with a verification that the format is valid json. Being a text, it stores presentation exactly as it is sent to Postgres, including whitespaces and identation, and also multiple-keys when present. No processing at all is done on the content, only validation.

triangle-exclamation
circle-check

The jsonb is an advanced binary storage format with full processing, indexing and searching capabilities, and as such pre-processes the json data to an internal format, which does include a single values per key; and also isn't sensible to extra whitespace or identation.

circle-info

jsonb will be faster with functions and operators, sinde it process the input data.

triangle-exclamation
Type
Description

json

Text-based JSON (slower, preserves formatting)

jsonb

Binary JSON (faster, no formatting preserved)

How values are inserted

Selecting values

circle-info

With json types, the returned value is always text. So you cannot extract data from it from inside Postgres.

To handle this use jsonb.

Use -> and ->> operators to select the json fields.

-> returns the json object field as a field in quotes, while ->> returns the object field as text.

Update existing object values

Adding new object values

Add arrays also like:

Delete object values

If the object values is an array, delete specific array's index values with #-:

Output a table contents in json

With row_to_json function, output an entire table in json, where each row of the select will be a json object with the columns being the key.

Network Address

circle-exclamation
circle-info

When sorting inet or cidr types, ipv4 addresses will always sort before ipv6, including ipv4 addresses encapsulated or mapped to ipv6.

Type
Description

cidr

IP network

inet

IP address

macaddr

MAC address

macaddr8

MAC address (EUI-64)

Numeric

Type
Subtype
Description

smallint

Integer

2-byte, range: -32,768 to +32,767

integer

Integer

4-byte, range: -2B to +2B

bigint

Integer

8-byte, large range

decimal / numeric

Fixed-Precision

Arbitrary precision exact numbers

real / float

Floating-Point

4-byte, approx precision ~6 decimal digits

double precision

Floating-Point

8-byte, approx precision ~15 digits

serial, bigserial, smallserial

Auto-increment

Integer auto sequences

circle-info

For decimal or numeric you define two parameters:

decimal(precision, scale) where:

  • precision is the maximum number of digits to the left and right of the decimal point;

  • scale is the number of digits allowable on the right of the decimal point.

Convert function (to_numberarrow-up-right)

Convert a string to number. (Check formats in the docs)

Range

circle-exclamation
circle-info

Ranges are not arrays, you will not access a specific range's value.

They are useful for instance, to reduce two date columns that should indicate a start and end date, to a single column that will have this same begin and end range.

Range Type
Description

int4range

Range of integers (4-byte)

int8range

Range of integers (8-byte)

tsrange

Range of timestamps (no timezone)

tstzrange

Range of timestamps (with timezone)

daterange

Range of dates

open_close parameter is defined as:

  • []: Both upper and lower bounds is closed.

  • [): Lower bound closed and upper bound open. (Default)

  • (]: Lower bound open and upper bound closed.

  • (): Both bounds opened.

Where opened means that the value is not included in the range, and closed means that it is part of the range.

circle-info

If not specified the default open_close is [).

Checking for date range overlap

Use && to check if two ranges overlap.

UUID

Type
Description

uuid

Universally Unique Identifier (By default uses uuidv4)

Last updated