POSTGRESQL

Text Extraction Made Easy With SUBSTRING in PostgreSQL

intro

Extract text using the SUBSTRING in PostgreSQL or SUBSTR. Set 1-based start positions, optional lengths, and leverage regex for advanced string parsing.

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT

If you need to extract part of a string in PostgreSQL, you'll be using its substring functions. Specifically, you'll either use the SUBSTRING function or SUBSTR. So, what's the difference between the two, and how do they work? Let's find out!

What Is SUBSTRING in PostgreSQL?

In PostgreSQL, SUBSTRING is a function (with SQL-standard syntax) to get the portion of a given string. SUBSTRING also has a shorthand alias SUBSTR, so both do the same thing.

For example, these PostgreSQL string functions are handy when you want the first 5 characters of a string field or a slice of a string from one position to another.

How to Use the SUBSTRING PostgreSQL Function

You can use the SUBSTRING function with this format:

Copy
        
1 SUBSTRING(string FROM start FOR length)

Where:

  • string is the input text you want to extract from.
  • start is the position (1-based index) where the extraction should begin.
  • length is the number of characters to extract.

Example:

Copy
        
1 SELECT SUBSTRING('PostgreSQL' FROM 1 FOR 4) AS sub; 2 -- Result: 'Post'

Equivalently, you can use it with this function-style syntax:

Copy
        
1 SUBSTRING(string, start, length)

For example:

Copy
        
1 SELECT SUBSTRING('PostgreSQL' FROM 1 FOR 4) AS sub; 2 -- Result: 'Post'
Executing the SUBSTRING query with the two possible syntax options in DbVisualizer
Executing the SUBSTRING query with the two possible syntax options in DbVisualizer

As you can see in a PostgreSQL client like DbVisualizer, both example returns the first 4 characters of the string 'PostgreSQL', starting at position 1. In PostgreSQL (as in standard SQL), string positions are 1-based, meaning the first character is position 1.

Note that the same result can be achieved with SUBSTR:

Copy
        
1 SELECT SUBSTR('PostgreSQL', 1, 4) AS sub; 2 -- Result: 'Post'

Again, the result will be “Post”:

Executing the SUBSTR query in DbVisualizer
Executing the SUBSTR query in DbVisualizer

SUBSTR is simply an alias for SUBSTRING in PostgreSQL, so you can use whichever you prefer.

Note: The length part in both syntax options is optional. If you omit it, the function will return everything from the start position to the end of the string. For example, SUBSTRING('Hello World' FROM 7) would give 'World' (from position 7 to the end).

Key Points About SUBSTRING in PostgreSQL

  • Start position: It’s 1-indexed. FROM 1 means start at the first character. If you specify 0, PostgreSQL treats it as 1 (effectively ignoring the 0). If you add a start argument beyond the string length, the result will be an empty string.
  • Length: The length argument must be a positive integer. If the length goes past the end of the string, you simply get the substring up to the end of the string (no error). If you omit length, you get the rest of the string from the start position. If you use a negative length, the PostgreSQL SUBSTRING query will fail with ERROR: negative substring length not allowed.
  • You can also use SUBSTRING with a pattern (regex) matching, e.g. SUBSTRING(string FROM 'pattern'), which is a more advanced usage to extract based on a regular expression. For instance, SUBSTRING('abc123' FROM '[0-9]+') would extract '123'. This is specific to PostgreSQL and follows SQL’s pattern matching rules.
  • If the input string is NULL, the result of SUBSTRING in PostgreSQL will be NULL.

PostgreSQL SUBSTRING Examples

Now that you know what SUBSTRING is and how it works, you’re ready to see it in action in some examples.

Example 1: Basic usage

Copy
        
1 SELECT SUBSTRING('abcdef', 3, 2); -- start at 3rd character, length 2

The result will be ‘cd’:

Note that the result is cd
Note that the result is ‘cd’

Example 2: Omitting the Length Argument

Copy
        
1 SELECT SUBSTRING('abcdef', 4); -- only the start argument is provided

This time the result will be 'def' (from 4th char to end):

Note that the result is def
Note that the result is ‘def’

Example 3: Using the SUBSTR Alias

Copy
        
1 SELECT SUBSTR('abcdef', 4);

Again, the result will be the same as before ('def'):

The result is the same as before
The result is the same as before

Comparison with Other Databases

  • MySQL/MariaDB: Use SUBSTRING(str, start, length) or the alias SUBSTR() (same as Postgres). If start is 0 in MySQL, it’s treated as 0 (which results in an empty string), whereas in PostgreSQL 0 is treated as 1.
  • Oracle: Oracle’s equivalent function is SUBSTR (Oracle doesn’t support the full word SUBSTRING in SQL). Oracle’s SUBSTR does allow negative start positions to count from the end. For example, Oracle SUBSTR('TechOnTheNet', -3, 3) returns 'Net'. In PostgreSQL, to get the last 3 chars, you could use SUBSTR(str, char_length(str)-2, 3) or simply RIGHT(str, 3).
  • SQL Server: The function is SUBSTRING(string, start, length) (SQL Server does use the full word). It does not allow negative start positions (you’d get an error if you provide negative). SQL Server also starts indexing at 1.
  • Standard SQL: SUBSTRING is part of standard SQL with the FROM ... FOR ... syntax. PostgreSQL supports that syntax. Some databases like SQL Server don’t support the FROM ... FOR ... notation and only the function syntax.

So, PostgreSQL is flexible by providing both syntaxes and an alias. The presence of SUBSTR in PostgreSQL is simply for convenience/compatibility (for those coming from Oracle or MySQL, for example).

Edge Cases and Tips of SUBSTRING

  • If you want only the first N characters of a text, you can also use the LEFT(string, N) function in PostgreSQL (it’s essentially a wrapper for SUBSTR(string, 1, N)). Similarly RIGHT(string, N) gives the last N characters.
  • For performance, substrings on large texts are generally fine, but remember that if you’re selecting a substring of a large text column for many rows, it still has to scan through that text. However, this is usually not an issue unless dealing with huge TEXT values.
  • If you find yourself doing a lot of substring operations in WHERE clauses (e.g., WHERE SUBSTRING(column, ...) = 'XYZ'), note that this will not use an index on the original column (because of the function call). In such cases, consider if an index on the expression is appropriate, or redesign the data if possible (e.g., store the part you need to query as a separate column).

Summary

In PostgreSQL, use SUBSTRING (or the alias SUBSTR) to extract parts of a string. The usage is straightforward: provide the string, a 1-based start position, and an optional length. The function is standard and similar across databases, with minor differences in how negative or out-of-range positions are handled.

As shown here, utilizingSUBSTRING in PostgreSQL becomes easier with a visual database client like DbVisualizer. That tool is a fully-featured database client that supports multiple DBMS technologies, offers advanced query optimization capabilities, and can generate ERD-type schemas with a few clicks. Download it for free today!

Dbvis download link img
About the author
TheTable
TheTable

The Table by DbVisualizer is where we gather together to learn about and simplify the complexity of working with database technologies.

The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

Check If A Table Exists in SQL: Multiple Approaches

author Antonello Zanini tags MySQL POSTGRESQL SQL SQL SERVER 6 min 2025-05-14
title

A Complete Guide to NOT EXISTS in SQL

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2025-05-12
title

SQL DROP TABLE IF EXISTS Statement: Complete Guide

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 6 min 2025-05-05
title

CREATE DATABASE in PostgreSQL: A Complete Guide

author Antonello Zanini tags POSTGRESQL 6 min 2025-04-30
title

A Beginner's Guide to Vector Search Using pgvector

author Lukas Vileikis tags POSTGRESQL Vectors 3 min 2025-04-24
title

TRUNCATE vs DELETE: SQL Comparison of the Two Statements

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 9 min 2025-04-23
title

How to Extract the Year from a Date in SQL

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 5 min 2025-04-21
title

How To List Tables In Postgres: Complete Guide

author Leslie S. Gyamfi tags POSTGRESQL 6 min 2025-04-17
title

A Guide to the SQL Standard Deviation Functions

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 6 min 2025-04-15
title

SQL EXISTS: Syntax and Use Cases with Examples

author Leslie S. Gyamfi tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 6 min 2025-04-14

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.