Constraint on row value based on values in other rows
Is it possible to have a table with four columns: CREATE TABLE accrual ( add_date date NOT NULL, user_id integer NOT NULL, rate integer NOT NULL, amount numeric(7,3) ); and then constrain it so that if...
View Articlepg_stat_activity shows lots of easy queries running for minutes
After application server start its connection pool fills quickly and application can’t work properly. I went through pg_stat_activity and noticed lots of queries running for minutes: But postgres’s...
View ArticleVery different query plans with and without LIMIT in PostgreSQL.
I have the following query which I am using to create vector tiles for a web map. I’m pulling together just the geometries within the selected tile using a CTE, then joining it to get additional...
View Articleinsert/update from web server or database
I have a data-model on the front-end that I want to insert/update in the database which of the following approaches (or neither!) is considered best practice: # in webserver some_model = {json}...
View ArticleForeign key with additional constraints?
There is a table called Item(id, name, cost) and Orders(id, bill_id, item_id, units), which is created to track orders placed, where same bill_id means it belongs to a single order. How to impose an...
View ArticleDynamic Column Label in Postgres 9.5
I am using postgres 9.5 and have built the following function: CREATE or REPLACE FUNCTION func_getratio_laglag(_numeratorLAG text, _n1 int, _denominatorLAG text, _n2 int, _table text) RETURNS TABLE...
View ArticleReuse subquery as in another result
In a typical social-network-like application I have the following query that gathers news from a set of followed channels. The main query gets the news, while the subquery gets the followed channels:...
View ArticleConverting standard_conforming_strings from off to on when importing Postgres...
I’ve got a Postgres 8.1 instance which has standard_conforming_strings set to off (== handles slashes as escape characters). Recent Postgres versions have this setting on by default (for good reasons)....
View ArticleMake a (copy of a) postgis database available to customer?
Our application uses a PostgreSQL database (with the PostGIS spatial extension). Now one of our customers has requested direct access to the database; because, as they claim, it’s their data. We’d...
View Articlebest way to avoid redundant aggregate functions and/or group by columns
Suppose I have two tables: Foo: id baz Bar: id foo_id boom So a Foo has many Bars. I frequently find myself in situations where I need to compute an aggregate across the Bars for a given set of Foos...
View Article