Page Content

Tutorials

Understanding The Data Types in PostgreSQL With Example

Data Types in PostgreSQL

Data types are essential for specifying the structure and behaviour of data in a database, and PostgreSQL provides a wide variety of them. In order to enable the stored data for different computations, each data type lends a certain semantic to the data and limits the range of values that can be supplied to a column. In contrast, a character string type will accept nearly any data but is not appropriate for mathematical computations, although it can perform operations such as string concatenation.However, a numerical type column can be used for mathematical exercises and does not allow arbitrary text strings.

Data Types in PostgreSQL
Data Types in PostgreSQL

Selecting the proper data type during database table design is critical since changing a column’s data type after production can be costly and require table locking and rewriting, especially for heavily loaded databases. Thus, extensibility (can the maximum length be changed without rebuilding the table?). and storage utilisation (bigints take up more space than integers) must be balanced. With support for user-defined types and mixed-type expressions, PostgreSQL’s extensible type system is more versatile and general than other SQL implementations.

An outline of some of PostgreSQL’s most important native data type categories and ideas is provided below:

Native Data Types

Numerical types PostgreSQL supports several number types:

Integers: Bigint (8 bytes), integer (4 bytes), and smallint (2 bytes) integers represent full values. Because it balances range, storage capacity, and performance, integer is popular.

Arbitrary Precision Numbers: Numerical and decimal store numbers with a lot of digits are called “arbitrary precision numbers,” and they are advised for amounts that need to be precise or for monetary amounts. These types are much slower than integer or floating-point types, but they produce accurate calculations.

Floating-Point Types: Types of floating points are inexact, variable-precision types: real (4 bytes, ~6 decimal digit precision) and double precision (8 bytes, ~15 decimal digit precision). It is not possible to convert all of the values to the internal binary format because they save them as approximations. In general, these kinds operate more quickly than numeric types.

Serial Types: The auto-incrementing integer types known as serial types smallserial, serial, and bigserial automatically append a corresponding sequence object to the database schema.

Different Types of Money The database’s lc monetary parameter determines the money type, which maintains currency quantities with fixed fractional accuracy.

Character Types:

Sorts of Characters Among the most widely used data kinds are these. What PostgreSQL has to offer:

Character(n) / char(n): Fixed-length strings that, in the event that the value is shorter, are blank-padded to the designated length n. Trailing spaces are ignored when working with char types.

Character varying(n) / varchar(n): Strings of variable lengths up to n are represented by the expression character varying(n) / varchar(n). Only the actual characters in the string are stored by them.

Text: Character strings that are variable in length and have an infinite length. Its flexibility and the fact that it doesn’t affect PostgreSQL speed make it a popular choice over varchar(n).

In order to store data outside of a record page in connected tables, PostgreSQL employs TOAST (The Oversized-Attribute Storage Technique) to break up huge values into smaller pieces for strings that are longer than the allotted 8KB.

Date/Time Types: Time/Date Types For temporal data, PostgreSQL has extensive functionality, date, time (both in and out of time zones), timestamp (both ways), and interval. Unless otherwise noted, a timestamp with time zone (shorthand timestamptz) is kept in UTC and shown in the server’s time zone. Epoch for Unix system time zero and infinity and -infinity for dates and timestamps are likewise accepted.

Boolean Type: NULL, true, or false are booleans. With string inputs like true, t, yes, on, and 1, it always returns t or f.

Geometric Types: Types of Geometry Circles, polygons, boxes, routes, points, lines, and lsegs are shown. Maps and graphs display spatial data.

Network Address Types: The types of network addresses.PostgreSQL supports IPv4/IPv6 networks, host data (cidr, inet), and MAC addresses. These outperform plain text for specialised procedures including input error checking.

Code Example:

-- Create a table for products
CREATE TABLE products (
    product_id SERIAL PRIMARY KEY,
    product_name VARCHAR(255) NOT NULL,
    price NUMERIC(10,2),
    quantity_in_stock SMALLINT,
    last_updated TIMESTAMP
);
-- Insert a new product
INSERT INTO products (product_name, price, quantity_in_stock, last_updated)
VALUES ('Electric Kettle', 45.99, 120, NOW());
-- Update the stock quantity and timestamp for a product
UPDATE products
SET quantity_in_stock = quantity_in_stock - 1,
    last_updated = NOW()
WHERE product_name = 'Electric Kettle'
  AND quantity_in_stock > 0;  -- optional safety check
-- Select all products to show the updated data
SELECT
    product_id,
    product_name,
    price,
    quantity_in_stock,
    last_updated
FROM products;

Output:

CREATE TABLE
INSERT 0 1
UPDATE 1
 product_id |  product_name   | price | quantity_in_stock |        last_updated        
------------+-----------------+-------+-------------------+----------------------------
          1 | Electric Kettle | 45.99 |               119 | 2025-08-22 10:17:55.528603
(1 row)

Advanced and User-Defined Data Types

Arrays: An array Any enum, user-defined, or built-in type can be used to form an array. An array’s dimensions and length are unbounded by default. Scientific data can be stored in arrays, and they can also be used to make coding tasks like giving several arguments to functions easier.

Composite Types: Mixtures of Types Row types, as they are also called, can be manually created with CREATE TYPE or are generated automatically whenever a table is formed. Values are rows or records of field values, while composite types are lists of types with related field names.

Range Types: Types of Range Reflect a range of values of a certain element type (subtype). Timestamp range (tsrange) and daterange are two examples. Columns of range kinds can have GiST and SP-GiST indexes made for them.

Domain Types: Categories of Domains A domain is a user-defined data type that is derived from an underlying type. The underlying type may contain constraints that limit the domain’s permissible values to a subset of those permitted by the underlying type. Can be made more modular by creating domains with the CREATE DOMAIN command.

Text Search Types: Text Search Categories Tsvector and tsquery data types are supported for full-text search in PostgreSQL. A text query with tsquery supports phrase search (<->) and boolean operators (&, |,!). A tsvector is an optimised document (sorted list of different lexemes and optional positions). You can use indexes to speed up full-text search.

XML Type: XML data is stored in the xml data type, which also offers support functions for type-safe operations and input validation for well-formedness.

JSON Types: Data types in PostgreSQL include JSON and JSONB. JSONB (binary JSON) is more efficient for querying and supports indexing and confinement operators since it saves a deconstructed binary form, even though both accept equivalent input values.

UUID Type: Issues such as offline data generation in databases are addressed by storing 128-bit numbers using the uuid (universally unique identifier) type.

BLOBs, or large objects Any operating system file, including huge text files or graphics, can be stored in the database using these. When values surpass the internal page capacity (usually 8KB), PostgreSQL stores them in chunks across many pages using TOAST in a transparent manner.

Type Conversion

SQL is a heavily typed language, thus data items’ behaviour depends on their type. PostgreSQL has many implicit conversion and mixed-type expression utilities. Avoid confusion when sending binary argument values by explicitly type casting with CAST() or ::.

Meta-commands are available in the psql command-line tool to examine database objects and data types:

\d+ [object_name]:In PostgreSQL, the \d+ [object_name] command is a meta-command that offers comprehensive and in-depth details about a given database object. This command is an improved version of \d that provides more information, including object and column comments.

\dT: In PostgreSQL, the \dT command is a meta-command that lists every data type that is available. It offers a thorough display of data kinds when run without any extra arguments. The \dT+ variant of the command, which contains additional information like the size of each data type, is available for a more thorough result.

\dT+: In contrast to the standard \dT command, the \dT+ command in PostgreSQL is a psql meta-command that lists all of the data types that are accessible and provides more comprehensive information. In particular, additional information like the size of each data type is included in the \dT+ form.

Conclusion

PostgreSQL’s extensive and extensible type system, in summary, offers the ability to store, handle, and process almost any form of data, from basic texts and integers to more complex structures like arrays, JSONB, and user-defined types. Selecting the appropriate data type during the design phase is essential for scalability, accuracy, and performance since it influences query speed, storage efficiency, and data integrity enforcement. The features of numerical, character, temporal, and specialised types as well as the strong indexing and conversion capabilities allow developers to create reliable databases that can effectively and precisely manage a variety of workloads. Due to its adaptability, PostgreSQL is a popular option for workloads involving analysis and science as well as transactional systems.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index