Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

95
Views
Date part in WHERE clause of a function

I want to select persons from a table where the date is within a given month.
This is what I have so far, but it's not working:

CREATE OR REPLACE FUNCTION u7()
RETURNS character varying AS
$BODY$
    DECLARE
        data varchar=`data`;
        mes varchar=`2016-11-21`;
        incidencia varchar=`expulsions`;
        valor varchar;
    BEGIN
        EXECUTE `SELECT `
        ||quote_ident(data)
        ||`FROM `
        ||quote_ident(incidencia)
        ||` WHERE data IN(select date_part(`month`, TIMESTAMP $1))`
        INTO valor USING mes;
        return valor;
    END;
$BODY$
LANGUAGE plpgsql;

select * FROM u7();
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Clean syntax for what you are trying to do could look like this:

CREATE OR REPLACE FUNCTION u7()
  RETURNS TABLE (valor text) AS
$func$
DECLARE
   data       text := 'data';    -- the first 3 would typically be function parameters
   incidencia text := 'expulsions';
   mes        timestamp = '2016-11-21';

   mes0       timestamp := date_trunc('month', mes);
   mes1       timestamp := (mes0 + interval '1 month');
BEGIN
   RETURN QUERY EXECUTE format(
     'SELECT %I
      FROM   %I
      WHERE  datetime_column_name >= $1
      AND    datetime_column_name <  $2'
    , data, incidencia)
   USING mes0, mes1;
END
$func$  LANGUAGE plpgsql;

SELECT * FROM u7();

Obviously, data cannot be a text column and a timestamp or date column at the same time. I use datetime_column_name for the timestamp column - assuming it's data type timestamp.

Aside from various syntax errors, do not use the construct with date_part(). This way you would have to process every row of the table and could not use an index on datetime_column_name - which my proposed alternative can.

See related answers for explanation:

  • EXECUTE...INTO...USING statement in PL/pgSQL can't execute into a record?
  • Table name as a PostgreSQL function parameter
  • How do I match an entire day to a datetime field?
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!