PostgreSQL Data Types

PostgreSQL Data Types

PostgreSQL offers a rich set of native data types for users. Users can add new types with the help of CREATE TYPE command. It also makes queries simpler and more readable.

PostgreSQL supports the following data types:

  • Text Types
  • Numeric Types
  • Dates and Times
  • XML
  • JSON
  • Boolean
  • Bits
  • Binary Data
  • Network
  • Arrays
  • Create your Data Type
  • Boolean
  • Temporal
  • UUID
  • Array
  • JSON
  • Special Data types for storing a network address and geometric data.

Let’s study them in detail

Character Datatypes

PostgreSQL supports character data types for storing text values. PostgreSQL builds character data types off of the same internal structures. PostgreSQL offers three character data types: CHAR(n), VARCHAR(n), and TEXT.

NameDescription
varchar(n)Allows you to declare variable-length with a limit
Char(n)Fixed-length, blank padded
TextUse can use this data type to declare a variable with unlimited length

Numeric Datatypes

PostgreSQL supports two distinct types of numbers:

  • Integers
  • Floating-point numbers
NameStore sizeRange
smallest2 bytes-32768 to +32767
integer4 bytes-2147483648 to +2147483647
bigint8 bytes-9223372036854775808 to 9223372036854775807
decimalvariableIf you declared it as decimal datatype ranges from 131072 digits before the decimal point to 16383 digits after the decimal point
numericvariableIf you declare it as the number, you can include number up to 131072 digits before the decimal point to 16383 digits after the decimal point
real4 bytes6 decimal digits precision
double8 bytes15 decimal digits precision

Binary Data Types

A binary string is a sequence of octets or bytes. Binary Data types are divided in two ways.

  • Binary strings allow storing odds of value zero
  • Non- printable octets

Character strings not allow zero octets and also disallows any other octet values and sequences which are invalid as per the database’s character set encoding rules.

NameStorage sizeDescription
Byte1 to 4 bytes plus the size of the binary stringVariable-length binary string

Network Address Type

Many applications store network information like IP address of users or

sensors. PostgreSQL has three native types which help you to optimize the network data.

NameSizeDescription
cider7 or 19 byesIPV4 and IPv6 networks
Inet7 or 19 bytesIPV4 and IPV5 host and networks
macaddr6 bytesMAC addresses

Using Network Address Types has following advantages

  1. Storage Space Saving
  2. Input error checking
  3. Functions like searching data by subnet

Text Search Type

PostgreSQL provides two data types which are designed to support full-text search. Full-text search is searching through a collection of natural-language documents to search those that best match a query.

  • Tsvector text search data type represents a document in a form optimized for text search
  • The query type text search stores the keywords that need to be searched

Date/Time Datatypes

PostgreSQL timestamp offers microsecond precision instead of second precision. Moreover, you also have the option of storing with timezone or without. PostgreSQL will convert timestamp with timezone to UTC on input and store it.

Date and time input is accepted in various format, including traditional Postgres, ISO 8601. SQL-compatible etc.

PostgreSQL supports Day / Month / Year ordering. Formats supported are DMY, MDY, YMD

NameSizeRangeResolution
Timestamp without timezone8 bytes4713 BC to 294276 AD1microsecond/14 digits
Timestamp with timezone8 bytes4713 BC to 294276 AD1microsecond/14 digits
date4 bytes4713 BC to 294276 ADOne day
Time without timezone8 bytes00:00:00 to 24:00:001microsecond/14 digits
Time with timezone12 bytes00:00:00 + 1459 to 24:00:00-14591microsecond/14 digits
Interval12 bytes-178000000 to 178000000 years1microsecond/14 digits

Examples:

InputDescription
2025-09-07ISO 8601, September 7 with any date style (recommended format)
September 7, 2025September 7 with any date style
9/7/2025September 7 with MDY, July 9 with DMY
9/7/25September 7, 2025, with MDY
2025-Sep-7September 7 with any date style
Sep-7-2018September 7 with any date style
7-Sep-25September 7, 2025, with YMD
20250907ISO 8601,7 Sep 20225 in any mode
2025.250year and day of the year, in this case, Sep 7, 2025
J25250Julian date

Time/ Time with Time Zone Input

InputDescription
11:19:38.507 11:19:38 11:19 111938ISO 8601
11:19 AMSame as 11:19
11:19 PMsame as 23:19
23:19-3 23:19-03:00 231900-03ISO 8601, same as 11:19 PM EST
23:19 ESTtime zone specified as EST, same as 11:19 PM EST

Boolean Type

A Boolean data type can hold

  • True
  • False
  • null

values.

You use a bool or boolean keyword to declare a column with the Boolean data type.

When you insert values into a boolean column, Postgre converts values like

  • Yes
  • y
  • 1
  • t
  • true

into 1.

While values like

  • No
  • N
  • 0
  • F
  • False

are converted to 0

While selecting data, the values are again converted back to yes, true, y, etc.

Geometric Data Types

Geometric data types represent two-dimensional spatial objects. They help perform operations like rotations, scaling, translation, etc.

NameStorage SizeRepresentationDescription
Point16 bytesPoint on a plane(x,y)
Line32 bytesInfinite line((xl.yl ).(x2.y2))
Lseg32 bytesFinite line segment((xl.yl ).(x2.y2))
Box32 bytesRectangular Box((xl.yl ).(x2.y2))
Path16n + 16n bytesClose and Open Path((xl.yl),…)
Polygon40 + 16n bytesPolygon[(xl.yl)….]
Circle24 bytesCircle<(x.y).r> (center point and radius)

Enumerated Types

Enumerated Data types in PostgreSQL is useful for representing rarely changing information such as country code or branch id. The Enumerated data type is represented in a table with foreign keys to ensure data integrity.

Example:

Hair color is fairly static in a demographic database

CREATE TYPE hair_color AS ENUM
('brown','black','red','grey','blond')

Range Type

Many business applications require data in ranges. Typically, two columns (example: start date, end date) are defined to deal with ranges. This is both inefficient and difficult to maintain.

Postgre has built range types as follows

  • int4range — Display range of integer
  • int8range — Display range of bigint
  • numrange — Shows the numeric range
  • tstrange — Helps you to display timestamp without time zone
  • strange — Allows you to display timestamp with time zone
  • date range — Range of date

UUID type

Universally Unique Identifies (UUID) is a 128-bit quantity which is generated by an algorithm. It is very unlikely that the same identifier will be generated by another person in the world using the same algorithm. That’s why for the distributed systems, these identifiers are an ideal choice as it offers uniqueness within a single database. A UUID is written as a group of lower-case hexadecimal digits, with various groups separated by hyphens.

PostgreSQL has a native UUID data type which consumes 16 bytes of storage.. UUID is an ideal Data type for primary keys.

Example:

d5f28c97-b962-43be-9cf8-ca1632182e8e

Postgre also accepts alternative forms of UUID inputs like all capital case, no hyphens, braces, etc.

XML type

PostgreSQL allows you to store XML data in a data type, but it is nothing more than an extension to a text data type. But the advantage is that it checks that the input XML is well-formed.

Example:

XMLPARSE (DOCUMENT '<?xml version="1.0"?><tutorial><chapter>Data Type</chapter><chapter>...</chapter></tutorial>')

JSON Type

To store JSON data PostgreSQL offers 2 data types

  1. JSON
  2. JSONB
jsonJsonb
A simple extension of a text data type with JSON validationA binary representation of the JSON data
Insert is fast but data retrieval relatively slow.Insert is slow but select (data retrieval is fast)
Saves inputted data exactly the way it is including whitespace.Supports indexing. May optimize the whitespace to make retrieval faster.
Reprocessing on data retrievalNo reprocessing required on data retrieval

Most widely used JSON data type used us jsonb unless there is some specialized need to use JSON data type.

Example:

CREATE TABLE employee (
  id integer NOT NULL,
  age  integer NOT NULL,
  data jsonb
);

INSERT INTO employee VALUES (1, 35, '{"name": "Tom Price", "tags": ["Motivated", "SelfLearner"], "onboareded": true}'); 

Pseudo-Types

PostgreSQL has many special-purpose entries that are called pseudo-types. You can’t use pseudo-type as a column data type. There are used to declare or function’s argument or return type.

Each of the available pseudo-types is helpful in situations where a function’s behavior docs do not correspond to simply taking or returning a value of a specific SQL data type.

NameDescription
AnyFunction accepts all input data type.
An arrayThe function accepts any array data type.
Any elementThe function accepts any data type.
Any enumThe function accepts any enum data type.
NonarrayThe function accepts any non-array data type.
CstringFunction accepts or returns null-terminated C string.
InternalInternal function accepts or returns server-internal data type.
Language_handlerIt is declared to return language handler.
RecordFind a function which returns an unspecified row type.
TriggerA trigger function is used to return trigger.

It is important that the user who is using this function need to make sure that the function will behave securely when a pseudo-type is used as an argument type.

Best practices using Data types

  • Use “text” data type unless you want to limit the input
  • Never use “char.”
  • Integers use “int.” Use bigint only when you have really big numbers
  • Use “numeric” almost always
  • Use float data type if you have IEEE 754 data source

Summary

  • PostgreSQL offers a rich set of native data types for users
  • PostgreSQL supports character data types for storing text values
  • PostgreSQL supports two distinct types of numbers: 1. Integers, 2. Floating-point numbers
  • A binary string is a sequence of bytes or octets
  • PostgreSQL has Network address type help you to optimize storage of network data
  • Text search data types are designed to support full-text search
  • Date/Time data types are allow date and time information in various formats
  • A Boolean data type can hold three values 1. True 2. False 3. Null
  • Geometric data types represent two-dimensional spatial objects
  • Enumerated Data types in PostgreSQL is useful for representing rarely changing information such as country code or branch id
  • Universally Unique Identifies (UUID) is a 128-bit quantity which is generated by an algorithm
  • PostgreSQL has many special-purpose entries that are called pseudo-types
  • It is best practice to use “text” data type unless you want to limit the input
top
X
Welcome to Our Website
Welcome to WPBot
wpChatIcon