Convert escaped Unicode character back to actual character in PostgreSQL

One old trick is using parser for this purpose: postgres=# select e’Telefon\u00ED kontakty’; ?column? ——————- Telefoní kontakty (1 row) CREATE OR REPLACE FUNCTION public.unescape(text) RETURNS text LANGUAGE plpgsql AS $function$ DECLARE result text; BEGIN EXECUTE format(‘SELECT e”%s”’, $1) INTO result; RETURN result; END; $function$ It works, but it is SQL injection vulnerable – so you … Read more

Join a count query on generate_series() and retrieve Null values as ‘0’

Untangled, simplified and fixed, it might look like this: SELECT to_char(s.tag,’yyyy-mm’) AS monat , count(t.id) AS eintraege FROM ( SELECT generate_series(min(date_from)::date , max(date_from)::date , interval ‘1 day’ )::date AS tag FROM mytable t ) s LEFT JOIN mytable t ON t.date_from::date = s.tag AND t.version = 1 GROUP BY 1 ORDER BY 1; db<>fiddle here … Read more

now() default values are all showing same timestamp

That is expected and documented behaviour: From the manual: Since these functions return the start time of the current transaction, their values do not change during the transaction. This is considered a feature: the intent is to allow a single transaction to have a consistent notion of the “current” time, so that multiple modifications within … Read more

How to create a new database with the hstore extension already installed?

Long story short: Install hstore in the template1 database: psql -d template1 -c ‘create extension hstore;’ Step-by-step explanation: As stated by the PostgreSQL documentation: CREATE EXTENSION loads a new extension into the current database. Installing an extension is database-specific. The following returns you the current database name: $ psql -c ‘select current_database()’ current_database —————— username … Read more

PostgreSQL next value of the sequences?

RETURNING That’s possible with a single round-trip to the database: INSERT INTO tbl(filename) VALUES (‘my_filename’) RETURNING tbl_id; tbl_id would typically be a serial or IDENTITY (Postgres 10 or later) column. More in the manual. Explicitly fetch value If filename needs to include tbl_id (redundantly), you can still use a single query. Use lastval() or the … Read more