From a3927ee02e9c3eaa49b0dffcc1639055a7615b15 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 4 Aug 2023 12:57:03 -0500 Subject: [PATCH] Add Different Ways To Define An Interval as a PostgreSQL TIL --- README.md | 3 +- .../different-ways-to-define-an-interval.md | 51 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 postgres/different-ways-to-define-an-interval.md diff --git a/README.md b/README.md index d644ee5..6d1c0f8 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1327 TILs and counting..._ +_1328 TILs and counting..._ --- @@ -644,6 +644,7 @@ _1327 TILs and counting..._ - [Determine Types Of JSONB Records](postgres/determine-types-of-jsonb-records.md) - [Determining The Age Of Things](postgres/determining-the-age-of-things.md) - [Difference Between Explain And Explain Analyze](postgres/difference-between-explain-and-explain-analyze.md) +- [Different Ways To Define An Interval](postgres/different-ways-to-define-an-interval.md) - [Dump All Databases To A SQL File](postgres/dump-all-databases-to-a-sql-file.md) - [Dump And Restore A Database](postgres/dump-and-restore-a-database.md) - [Dump The SQL Needed To Recreate A Table](postgres/dump-the-sql-needed-recreate-a-table.md) diff --git a/postgres/different-ways-to-define-an-interval.md b/postgres/different-ways-to-define-an-interval.md new file mode 100644 index 0000000..3c614fc --- /dev/null +++ b/postgres/different-ways-to-define-an-interval.md @@ -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)