Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you are willing to break your <code>INSERT</code> statements into one row of data per insert, then you could use <a href="http://www.postgresql.org/docs/9.1/static/rules-update.html" rel="nofollow">PostgreSQL rules</a>. The example that follows is a bit convoluted in that rules don't seem to let you redirect writes to a relation itself. That's usually done with triggers. But we're seeing if this is possible without triggers, so here goes:</p> <pre><code>--drop table table_data cascade; CREATE TABLE table_data ( month integer not null, task integer not null, "desc" text ); ALTER TABLE table_data add primary key (month, task); CREATE VIEW "table" as select month, task, "desc" from table_data; CREATE OR REPLACE RULE calculate_task AS ON INSERT TO "table" DO INSTEAD INSERT into table_data (month, task, "desc") VALUES ( NEW.month, (select coalesce(max(task),0) + 1 from table_data where month = NEW.month), NEW."desc"); BEGIN; INSERT INTO "table" ("month", "desc") VALUES (1, 'One thing'); INSERT INTO "table" ("month", "desc") VALUES (1, 'Another thing'); INSERT INTO "table" ("month", "desc") VALUES (1, 'Last task of the month'); INSERT INTO "table" ("month", "desc") VALUES (2, 'Last task of the month'); INSERT INTO "table" ("month", "desc") VALUES (2, 'Last task of the month'); INSERT INTO "table" ("month", "desc") VALUES (3, 'First of third month'); COMMIT; select * from "table"; </code></pre> <p><em>Notes</em></p> <ul> <li>If you need to support DELETE/UPDATE on "table", then you could add rules for each those actions as well.</li> <li>The <code>BEGIN</code> and <code>COMMIT</code> block above is used to show that even within the same transaction, this method will work as long as each row is broken into its own <code>INSERT</code>.</li> <li>You use a few <a href="http://www.postgresql.org/docs/9.1/static/sql-keywords-appendix.html" rel="nofollow">reserved words</a> like <code>table</code> and <code>desc</code>. Be sure to double-quote them as you've done and you won't have any problems.</li> </ul> <p><a href="http://sqlfiddle.com/#!12/98e10/2" rel="nofollow">Here</a> is the above code in sqlfiddle</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload