Hernandcb
Hernandcb

Reputation: 539

PostgreSQL: call EXTRACT function passing as argument one field of the query

I want to know if it is possible to use the extract function :

EXTRACT(field from timestamp)

Where the field is a value from the query?

Please see this (simplified) example:

SELECT c.name, EXTRACT(f.frecuency from NOW())
FROM contacts c 
INNER JOIN frecuencies f ON c.id = f.contact_id 

From the following tables:

contacts table: 
---------------------
| id   |   name     | 
---------------------
| 123  |   Test     | 
---------------------

 frecuencies table: 
---------------------------------
| id | contact_id | frecuency |
---------------------------------
| 1  |   123      |  DAY        |
--------------------------------- 

I made the query (in several ways) and got the message:

timestamp with time zone units "frecuency" not recognized

Therefore I want to know if exists some workaround for this.

Thank you in advance.

PD: If you think the question title or body need to be improved please go ahead, I would thank you a lot!

Upvotes: 1

Views: 190

Answers (1)

Laurenz Albe
Laurenz Albe

Reputation: 247790

Just use date_part which according to the documentation is the same as EXTRACT like in this example:

WITH units(u) AS (VALUES ('day'))
SELECT date_part(u, current_timestamp) FROM units;
┌───────────┐
│ date_part │
├───────────┤
│        18 │
└───────────┘
(1 row)

Upvotes: 1

Related Questions