How to get the OID of a Postgres table?

To get a table OID, cast to the object identifier type regclass (while connected to the same DB!). This finds the first table (or view etc.) with the given (unqualified) name along the search_path or raises an exception if not found: SELECT ‘mytbl’::regclass::oid; Schema-qualify the table name to remove the dependency on the search path: … Read more

to_char(number) function in postgres

You need to supply a format mask. In PostgreSQL there is no default: select to_char(1234, ‘FM9999′); If you don’t know how many digits there are, just estimate the maximum: select to_char(1234, ‘FM999999999999999999′); If the number has less digits, this won’t have any side effects. If you don’t need any formatting (like decimal point, thousands separator) … Read more

PostgreSQL 9.1: How to concatenate rows in array without duplicates, JOIN another table

Instead of using window functions and partitioning, use a query-level GROUP BY and aggregate with a DISTINCT clause: SELECT rnp.grp_id, array_to_string(array_agg(distinct rnp.cabinets),’,’) AS cabinets, array_to_string(array_agg(distinct ips.address),’,’) AS addresses FROM rnp JOIN ips ON rnp.grp_id=ips.grp_id GROUP BY rnp.grp_id, ips.grp_id; Result: grp_id | cabinets | addresses ——–+————————-+———– 11 | cabs1,cabs2,cabs3,cabs4 | CA,NY 22 | c1,c2 | DC,LA … Read more

Postgres analogue to CROSS APPLY in SQL Server

In Postgres 9.3 or later use a LATERAL join: SELECT v.col_a, v.col_b, f.* — no parentheses, f is a table alias FROM v_citizenversions v LEFT JOIN LATERAL f_citizen_rec_modified(v.col1, v.col2) f ON true WHERE f.col_c = _col_c; Why LEFT JOIN LATERAL … ON true? Record returned from function has columns concatenated For older versions, there is … Read more

tech