mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Getting A Slice Of An Array as a postgres til.
This commit is contained in:
@@ -82,6 +82,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
|||||||
- [Extracting Nested JSON Data](postgres/extracting-nested-json-data.md)
|
- [Extracting Nested JSON Data](postgres/extracting-nested-json-data.md)
|
||||||
- [Fizzbuzz With Common Table Expressions](postgres/fizzbuzz-with-common-table-expressions.md)
|
- [Fizzbuzz With Common Table Expressions](postgres/fizzbuzz-with-common-table-expressions.md)
|
||||||
- [Generate Series Of Numbers](postgres/generate-series-of-numbers.md)
|
- [Generate Series Of Numbers](postgres/generate-series-of-numbers.md)
|
||||||
|
- [Getting A Slice Of An Array](postgres/getting-a-slice-of-an-array.md)
|
||||||
- [Integers In Postgres](postgres/integers-in-postgres.md)
|
- [Integers In Postgres](postgres/integers-in-postgres.md)
|
||||||
- [Intervals Of Time By Week](postgres/intervals-of-time-by-week.md)
|
- [Intervals Of Time By Week](postgres/intervals-of-time-by-week.md)
|
||||||
- [Limit Execution Time Of Statements](postgres/limit-execution-time-of-statements.md)
|
- [Limit Execution Time Of Statements](postgres/limit-execution-time-of-statements.md)
|
||||||
|
|||||||
25
postgres/getting-a-slice-of-an-array.md
Normal file
25
postgres/getting-a-slice-of-an-array.md
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
# Getting A Slice Of An Array
|
||||||
|
|
||||||
|
Postgres has a very natural syntax for grabbing a slice of an array. You
|
||||||
|
simply add brackets after the array declaring the lower and upper bounds
|
||||||
|
of the slice separated by a colon.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
> select (array[4,5,6,7,8,9])[2:4];
|
||||||
|
array
|
||||||
|
---------
|
||||||
|
{5,6,7}
|
||||||
|
```
|
||||||
|
|
||||||
|
Notice that the bounds are inclusive, the array index is `1`-based, and the
|
||||||
|
array declaration above needs to be wrapped in parentheses in order to not
|
||||||
|
trip up the array slice syntax.
|
||||||
|
|
||||||
|
You can also select rectangular slices from two dimensional arrays like so:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
> select (array[[1,2,3],[4,5,6],[7,8,9]])[2:3][1:2];
|
||||||
|
array
|
||||||
|
---------------
|
||||||
|
{{4,5},{7,8}}
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user