Using the SUBSTRING function in PostgreSQL

Updated: January 6, 2024 By: Guest Contributor Post a comment

Overview

The SUBSTRING function is a powerful feature available for string manipulation in PostgreSQL databases. Its usefulness is recognized across various domains where data manipulation is an integral part of managing databases. Introduction

The SUBSTRING function has been a part of the SQL standard for many years and has been implemented in PostgreSQL along with its inception. Well-documented since the early versions, its functionality has been essential for any text processing within the database. Purpose of SUBSTRING

Uses

This function is used to extract a substring from a string based on a specified position and length. It is a key tool for string data manipulation, allowing users to easily retrieve portions of text for analysis, reports, and data transformation. Syntax and Parameters

Syntax & Parameters

The basic syntax of the SUBSTRING function in PostgreSQL is as follows:

SUBSTRING(string FROM start FOR length)

Where:

  • string: The source string from which you want to extract the substring.
  • start: The start position for the substring extraction. Positions start at 1.
  • length: The number of characters to extract.

The function returns the specified portion of the string passed in the ‘string’ argument.

Practical Examples

Example 1: Basic Substring Extraction

This example shows the basic usage of the SUBSTRING function to get a portion of the text.

SELECT SUBSTRING('PostgreSQL' FROM 1 FOR 5);
-- Output: 'PostG'

Example 2: Substring Extraction with SQL Variables

The SUBSTRING function can also be combined with SQL variables.

DO $
DECLARE
    my_str VARCHAR := 'Data Extraction';
    start_pos INT := 6;
    len INT := 10;
BEGIN
    RAISE NOTICE '%', SUBSTRING(my_str FROM start_pos FOR len);
END$;
-- Output: 'Extraction'

Example 3: Substring from Pattern Matching

PostgreSQL allows extracting substrings by pattern matching with regular expressions.

SELECT SUBSTRING('Foo1234 Bar5678', 'Bar(\d+)');
-- Output: 'Bar5678'

Conclusion

The SUBSTRING function in PostgreSQL is an indispensable tool for developers and database administrators alike. It allows for flexible string manipulation, contributing to data parsing, formatting, and analysis tasks. By mastering this function, one can significantly manipulate and understand their database text data with greater precision.