Database function SELECT with optional argument I need to perform a SELECT in postgres that filters records only when a certain argument value is not null. If the argument is null then the argument is ignored. I am experimenting with a function...
create or replace function my_func(argument INT)
returns table
        (
            field1   VARCHAR(50),
            field2 VARCHAR(2),
            field3 BIGINT
        )
language plpgsql
AS
$$
begin
select d.field1, d.field2, COUNT(*) as record_count
             from my_table d
             group by d.field1, d.field2;

if argument IS NOT NULL
    -- TODO: How to filter the first recordset here?
end;
$$

How do I perform a second, optional SELECT in a function please? Or perhaps there's a slick way to do an option where clause?
select d.field1, d.field2, COUNT(*) as record_count

WHERE d.fieldX = argument OR argument IS NULL

from my_table d
group by d.field1, d.field2;

Be aware that this may not always produce an efficient access plan. If you experience performance issues, you'll likely be better off executing one of the two query variants conditionally, something like
IF argument IS NULL THEN
   SELECT ... -- without conditions
ELSE 
   SELECT ... WHERE fieldX = argument
END IF