In the Udemy PostgreSQL Bootcamp : Go From Beginner to Advanced, 60+hours course, there was a lesson where we wrote a function to output some SQL to enable dynamic pivot tables:
pass the table_name, vertical_header_column, horizontal_header_column, value_column, and data_type and any table can be “pivoted”. Pretty nifty.
But… it was hideously difficult to transcribe the code from video source.
And, the horizontal headers were year values, so the instructor prepended an underscore (_) to the column names since databases do not (normally) like a column named 2020.
I posted comments on the lesson showing that:
- it’s possible
- how to do it in the lesson code
The underscore prepended to field names is not necessary
One can create a table where column names start with / are completely numeric characters:
\echo NOTE: field names CAN start with numbers, like I tried to do above:
DROP TABLE IF EXISTS crosstabs.column_name_numeric;
CREATE TABLE crosstabs.column_name_numeric (
"123" integer
);
\x on
\d crosstabs.column_name_numeric
Table "crosstabs.column_name_numeric"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+---------
123 | integer | | |
This way, with a lot of work at trying to figure out the nested quotes in the dynsql1
statement, we can get the following headers that are purely numeric:
location | 2012 | 2013 | 2014 | 2015 | 2016 | 2017
-----------+------+------+------+------+------+------
Dubai | 112 | 116 | 111 | 80 | 110 | 102
France | 114 | 111 | 113 | 85 | 120 | 110
Germany | 153 | 120 | 136 | 128 | 138 | 113
London | 116 | 138 | 137 | 101 | 117 | 110
Malaysia | 53 | 77 | 78 | 50 | 52 | 43
Qatar | 86 | 116 | 111 | 83 | 102 | 89
Singapore | 124 | 132 | 142 | 111 | 106 | 110
Sydney | 98 | 120 | 110 | 93 | 122 | 115
Tokyo | 47 | 63 | 68 | 53 | 54 | 43
(9 rows)
So, yes, it is possible to have numeric column names in PostgreSQL.