mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Generate Series Of Numbers as a postgres til.
This commit is contained in:
@@ -57,6 +57,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
||||
- [Configure The Timezone](postgres/configure-the-timezone.md)
|
||||
- [Count Records By Type](postgres/count-records-by-type.md)
|
||||
- [Extracting Nested JSON Data](postgres/extracting-nested-json-data.md)
|
||||
- [Generate Series Of Numbers](postgres/generate-series-of-numbers.md)
|
||||
- [String Contains Another String](postgres/string-contains-another-string.md)
|
||||
- [Timestamp Functions](postgres/timestamp-functions.md)
|
||||
- [Toggling The Pager In PSQL](postgres/toggling-the-pager-in-psql.md)
|
||||
|
||||
46
postgres/generate-series-of-numbers.md
Normal file
46
postgres/generate-series-of-numbers.md
Normal file
@@ -0,0 +1,46 @@
|
||||
# Generate Series Of Numbers
|
||||
|
||||
Postgres has a `generate_series` function that can be used to, well,
|
||||
generate a series of something. The simplest way to use it is by giving it
|
||||
`start` and `stop` arguments
|
||||
|
||||
```sql
|
||||
> select generate_series(1,5);
|
||||
generate_series
|
||||
-----------------
|
||||
1
|
||||
2
|
||||
3
|
||||
4
|
||||
5
|
||||
```
|
||||
|
||||
The default step is 1, so if you want to count backwards, you need to
|
||||
specify a negative step
|
||||
|
||||
|
||||
```sql
|
||||
> select generate_series(5,1,-1);
|
||||
generate_series
|
||||
-----------------
|
||||
5
|
||||
4
|
||||
3
|
||||
2
|
||||
1
|
||||
```
|
||||
|
||||
You can use a larger step value to, for instance, get only multiples of 3
|
||||
|
||||
```sql
|
||||
> select generate_series(3,17,3);
|
||||
generate_series
|
||||
-----------------
|
||||
3
|
||||
6
|
||||
9
|
||||
12
|
||||
15
|
||||
```
|
||||
|
||||
Trying this out with timestamps is left as an exercise for the reader.
|
||||
Reference in New Issue
Block a user