mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Different Ways To Define An Interval as a PostgreSQL TIL
This commit is contained in:
51
postgres/different-ways-to-define-an-interval.md
Normal file
51
postgres/different-ways-to-define-an-interval.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Different Ways To Define An Interval
|
||||
|
||||
There are several different ways in PostgreSQL to define an `interval` data
|
||||
type. An `interval` is useful because it can represent a discrete chunk of
|
||||
time. This is handy for doing date math.
|
||||
|
||||
Here are four different ways to define an `interval`:
|
||||
|
||||
1. Use the `interval` keyword with a string
|
||||
|
||||
```sql
|
||||
> select interval '3 days';
|
||||
interval
|
||||
----------
|
||||
3 days
|
||||
(1 row)
|
||||
```
|
||||
|
||||
2. Cast a string to the `interval` type
|
||||
|
||||
```sql
|
||||
> select '3 days'::interval;
|
||||
interval
|
||||
----------
|
||||
3 days
|
||||
(1 row)
|
||||
```
|
||||
|
||||
3. The `@` operator is a finicky syntax for declaring an interval
|
||||
|
||||
```sql
|
||||
> select @ 3 days;
|
||||
days
|
||||
------
|
||||
3
|
||||
(1 row)
|
||||
```
|
||||
|
||||
4. The [`make_interval`
|
||||
function](https://www.postgresql.org/docs/current/functions-datetime.html)
|
||||
can take various forms of arguments to construct an interval
|
||||
|
||||
```sql
|
||||
> select make_interval(days => 3);
|
||||
make_interval
|
||||
---------------
|
||||
3 days
|
||||
(1 row)
|
||||
```
|
||||
|
||||
[source](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-INTERVAL-INPUT)
|
||||
Reference in New Issue
Block a user