Re: check constraint on char field

From: "Scott Marlowe" <smarlowe(at)qwest(dot)net>
To: "Robert Fitzpatrick" <robert(at)webtent(dot)com>
Cc: "PostgreSQL" <pgsql-general(at)postgresql(dot)org>
Subject: Re: check constraint on char field
Date: 2004-06-09 18:38:23
Message-ID: 1086806303.23855.38.camel@localhost.localdomain
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wed, 2004-06-09 at 10:42, Robert Fitzpatrick wrote:
> I have a field in my pgsql 7.4.2 table that is char(6) type. This holds
> an ID that contains only numbers, but must be six characters in length.
> First two chars are the year followed by a sequential number. For
> instance, a number entered for the time this year would be '040001'. I
> was trying to setup a check constraint to make sure only number were
> used, this is what I have, but it is allowing alphanumerics:
>
> projectno >= '000000' AND projectno <= '999999'
>
> Or maybe just a trigger to create the number itself would be better?

You've chosen the wrong type. char(6) will ALWAYS be 6 characters long,
no matter how short a string you try to put it in. I.e. if you insert
'abc' it will become 'abc ' on insert. You also need to cast. Try
this:

smarlowe=> create table test (id varchar(6) check (id::text::int>0 and
id::text::int<1000000 and length(id)=6));
CREATE TABLE
smarlowe=> insert into test values ('6');
ERROR: new row for relation "test" violates check constraint "test_id"
smarlowe=> insert into test values ('601');
ERROR: new row for relation "test" violates check constraint "test_id"
smarlowe=> insert into test values ('abc123');
ERROR: invalid input syntax for integer: "abc123"
smarlowe=> insert into test values ('000123');
INSERT 17263 1

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Prabu Subroto 2004-06-09 19:09:00 Re: postgres on SuSE 9.1
Previous Message Duane Lee - EGOVX 2004-06-09 18:31:19 Re: [GENERAL] Help in finding the error