Abubakar Mehmood
Abubakar Mehmood

Reputation: 1218

postgres - How to assign a result count to a variable and do a select query based on that

I am a from T-SQL and MS SQL Server background and struggling with PostgreSQL. I need to declare a variable, do a count query, save the result of the count in the variable; then based, on the count assign a date to another variable, and then do a select query with that assigned date to return its result set. The problem is when I declare a variable without a DO $$ block, like so:

DECLARE num_rows bigint; I get:

ERROR: syntax error at or near "bigint"

LINE 1: DECLARE num_rows bigint;

And if I try within the DO $$ block, I get the following error on the SELECT:

ERROR: query has no destination for result data

HINT: If you want to discard the results of a SELECT, use PERFORM instead.

CONTEXT: PL/pgSQL function inline_code_block line 35 at SQL statement SQL state: 42601

This is what I am trying:

DO $$
DECLARE num_rows bigint;
DECLARE end_date timestamp with time zone;
BEGIN
SELECT COUNT(my_table.id) 
INTO num_rows
FROM my_table
WHERE my_table.something = 1;

IF num_rows > 500 THEN
end_date = '2022-12-03';
END IF;

SELECT * FROM another_table WHERE some_date < end_date;

END $$;

Is there any way to accomplish this or similar in PostgreSQL? I cannot use functions because it is a legacy database and I cannot do DDL changes to it.

Upvotes: 0

Views: 1161

Answers (1)

mikasa
mikasa

Reputation: 180

1)in row end_date = '2022-12-03' you need a semicolon

2)in last select statement you must use execute

I think this will work:

DO $$
DECLARE 
  num_rows bigint;
  end_date timestamp with time zone;
BEGIN
SELECT COUNT(my_table.id) 
INTO num_rows
FROM my_table
WHERE my_table.something = 1;

IF num_rows > 500 THEN
end_date = '2022-12-03';
END IF;

execute 'SELECT * FROM another_table WHERE some_date <'|| end_date;

END $$;

You can also try to run something like this:

with mydate as(
    select case when (select count(*) from mytable where something = 1)>500 then '2022-12-03' end as end_date,
    (select count(*) from mytable where something = 1) as num_rows
    )
select * from another_table a,mydate b where a.some_date>end_date;

Upvotes: 1

Related Questions