How to get a dynamic column name in a PostgreSQL SELECT statement

I have the following PostgreSQL table:

CREATE TABLE test (
  id INT,
  displaylabel VARCHAR(255)
);
INSERT INTO test (id, displaylabel) VALUES (1, 'Hello');
INSERT INTO INTO test (id, displaylabel) VALUES (2, 'World');

I want to write a SELECT statement that returns the number of rows in the table, with the column name being the current month and year. For example, if today is 2023-10-19, I want the result to be:

October 2023
2

I tried the following SELECT statements, but they don’t work:

SELECT 
    id AS format('%s %s', to_char(current_date, 'Month'), to_char(current_date, 'YYYY')) 
FROM test;

SELECT id AS (
  to_char(CURRENT_DATE, 'Month') || ' ' || to_char(CURRENT_DATE, 'YYYY')
)
FROM test;

I get the following error messages:

Query Error: error: syntax error at or near "("

I need to use only SELECT statements because my account is read-only, so I can’t use EXECUTE.

How can I write a SELECT statement that returns the desired result, with a dynamic column name?

Example output:

October 2023
2

DB fiddle : https://www.db-fiddle.com/f/9Hs1YtQxHfJMeKviNrj9Rb/0

  • 3

    Why are you doing this? This isn’t what SQL is meant for… Things like custom column-names, pivots/unpivots, et cetera should be performed by your presentation-layer, not in SQL.

    – 




  • 2

    Why do you want that to be the column name? You can select 'October 2023' as column_name, count(*) as count_ from test; – data goes into rows, vertially, not horizontally into columns. If you later wanted to do select "October 2023" from t1;, it should be select count_ from t1 where column_name="October 2023";.

    – 




Leave a Comment