SELECT or INSERT a row in one command

Have you tried to union it? Edit – this requires Postgres 9.1: create table mytable (id serial primary key, other_key varchar not null unique); WITH new_row AS ( INSERT INTO mytable (other_key) SELECT ‘SOMETHING’ WHERE NOT EXISTS (SELECT * FROM mytable WHERE other_key = ‘SOMETHING’) RETURNING * ) SELECT * FROM new_row UNION SELECT * … Read more

Format specifier for integer variables in format() for EXECUTE?

This would be shorter, faster and safer: CREATE OR REPLACE FUNCTION get_parent_ltree(parent_id bigint, tbl_name regclass , OUT parent_ltree ltree) LANGUAGE plpgsql AS $func$ BEGIN EXECUTE format(‘SELECT l_tree FROM %s WHERE id = $1′, tbl_name) INTO parent_ltree USING parent_id; END $func$; Why? Most importantly, use the USING clause of EXECUTE for parameter values. Don’t convert them … Read more

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

PostgreSQL jsonb, `?` and JDBC

As a workaround to avoid the ? operator, you could create a new operator doing exactly the same. This is the code of the original operator: CREATE OPERATOR ?( PROCEDURE = jsonb_exists, LEFTARG = jsonb, RIGHTARG = text, RESTRICT = contsel, JOIN = contjoinsel); SELECT ‘{“a”:1, “b”:2}’::jsonb ? ‘b’; — true Use a different name, … Read more

Importing .csv with timestamp column (dd.mm.yyyy hh.mm.ss) using psql \copy

Have you tried setting the datestyle setting of the server? SET datestyle=”ISO,DMY”; You are using the psql meta-command \copy, which means the input file is local to the client. But it’s still the server who has to coerce the input to matching data-types. More generally, unlike the psql meta-command \copy which invokes COPY on the … Read more

Best way to install hstore on multiple schemas in a Postgres database?

It is not allowed to install extensions multiple times per database. Quoting the manual on CREATE EXTENSION: Remember that the extension itself is not considered to be within any schema: extensions have unqualified names that must be unique database-wide. But objects belonging to the extension can be within schemas. If you don’t want to include … Read more