Home > Database > Mysql Tutorial > How to Renormalize PostgreSQL Array Subscripts to Start from 1?

How to Renormalize PostgreSQL Array Subscripts to Start from 1?

Linda Hamilton
Release: 2025-01-09 12:03:56
Original
731 people have browsed it

How to Renormalize PostgreSQL Array Subscripts to Start from 1?

Adjusting PostgreSQL Array Indices to Start from 1

PostgreSQL's flexibility allows for arrays with indices that don't begin at the standard 1. For example, the following array's elements are indexed from 5 to 7:

SELECT '[5:7]={1,2,3}'::int[];
Copy after login

Accessing the first element requires using index 5:

SELECT ('[5:7]={1,2,3}'::int[])[5];
Copy after login

However, many users prefer arrays with indices starting at 1. Here's how to achieve this:

SELECT ('[5:7]={1,2,3}'::int[])[array_lower('[5:7]={1,2,3}'::int[], 1):array_upper('[5:7]={1,2,3}'::int[], 1)];
Copy after login

This extracts the array slice from the lowest to highest index, effectively resetting the indexing.

A more readable approach using a Common Table Expression (CTE):

WITH cte(a) AS (SELECT '[5:7]={1,2,3}'::int[])
SELECT a[array_lower(a, 1):array_upper(a, 1)]
FROM cte;
Copy after login

For PostgreSQL 9.6 and later, a simplified method exists: omitting the lower and upper bounds in the slice specification:

SELECT my_arr[:];
Copy after login

For our example, parentheses improve readability:

SELECT ( '[5:7]={1,2,3}'::int[] )[:];
Copy after login

This approach is efficient and works well even in Postgres versions prior to 9.6.

The above is the detailed content of How to Renormalize PostgreSQL Array Subscripts to Start from 1?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template