I am writing a postgresql view that uses some complex logic to generate rows of data. It requires that I perform the same set of steps on two sets of data derived from results of querying two different tables. Is it possible to write a function that generalizes these steps?
For example:
CREATE TABLE foos (
id bigserial primary key,
name text not null
);
INSERT INTO foos (name) VALUES ('FOO_ONE');
INSERT INTO foos (name) VALUES ('FOO_TWO');
INSERT INTO foos (name) VALUES ('FOO_THREE');
INSERT INTO foos (name) VALUES ('FOO_FOUR');
CREATE TABLE bars (
id bigserial primary key,
name text not null
);
INSERT INTO bars (name) VALUES ('BAR_ONE');
INSERT INTO bars (name) VALUES ('BAR_TWO');
INSERT INTO bars (name) VALUES ('BAR_THREE');
INSERT INTO bars (name) VALUES ('BAR_FOUR');
Now I must compute:
WITH even_foos AS (SELECT * FROM foos WHERE id % 2 = 0)
SELECT id * 2 AS double_id, name FROM even_foos;
and
WITH odd_bars AS (SELECT * FROM foos WHERE id % 2 = 1)
SELECT id * 2 AS double_id, name FROM odd_bars;
Note how the id * 2
select is repeated in both queries. I would like to reuse this functionality so that I only have to implement this logic once. For example (made up syntax):
WITH even_foos AS (SELECT * FROM foos WHERE id % 2 = 0)
SELECT * FROM get_double_id_and_name(even_foos);
and
WITH odd_bars AS (SELECT * FROM foos WHERE id % 2 = 1)
SELECT * FROM get_double_id_and_name(odd_bars);
Is there an easy way to accomplish this?