Re: limit table to one row

From: Brandon Metcalf <brandon(at)geronimoalloys(dot)com>
To: Niklas Johansson <pgmailings(at)codecraft(dot)se>
Cc: Richard Broersma <richard(dot)broersma(at)gmail(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: limit table to one row
Date: 2009-06-05 16:13:12
Message-ID: Pine.LNX.4.58L.0906051111060.17533@cedar.geronimoalloys.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

p == pgmailings(at)codecraft(dot)se writes:

p> On 4 jun 2009, at 22.17, Richard Broersma wrote:

p> > On Thu, Jun 4, 2009 at 1:13 PM, Brandon Metcalf
p> > <brandon(at)geronimoalloys(dot)com> wrote:
p> >> Is there a way when creating a table to limit it to one row? That
p> >> is,
p> >> without using a stored procedure?
p> >
p> >
p> > Sure just add a check constraint along the lines of:
p> >
p> > CONSTRAINT Only_one_row
p> > CHECK( tableuniqueid = 1 ); --assuming you row has a unique id
p> > of 1

p> Another way, which I've used a couple of times, is to use the rule
p> system:

p> CREATE TABLE single_row (value text);
p> INSERT INTO single_row VALUES ('value');
p> CREATE RULE no_insert AS ON INSERT TO single_row DO INSTEAD NOTHING;
p> CREATE RULE no_delete AS ON DELETE TO single_row DO INSTEAD NOTHING;

p> This way, the table must have exactly one row. I believe the
p> constraint check would still allow the row to be deleted, which you
p> may or may not want.

p> If you want an error to be raised when inserting or deleting, you'd
p> have to call a function raising the error in the rule. A minor
p> drawback is that the table still isn't safe from TRUNCATE though.

Thanks for the info. The data in the table in question is easy to
recreate if it gets deleted. The main thing is to prevent more than
one row, so using CHECK( tableuniqueid = 1 ) works fine.

--
Brandon

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Brandon Metcalf 2009-06-05 16:27:44 maintaining referential integrity
Previous Message Tom Lane 2009-06-05 15:17:59 Re: How to know the indexes on a Table