From: | Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com> |
---|---|
To: | Peter Devoy <peter(at)3xe(dot)co(dot)uk>, "Psql_General (E-mail)" <pgsql-general(at)postgresql(dot)org> |
Subject: | Re: Enforcing uniqueness on [real estate/postal] addresses |
Date: | 2020-05-11 18:32:46 |
Message-ID: | c9349c8f-9cad-9b2e-9380-f78748b4090b@aklaver.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On 5/11/20 9:55 AM, Peter Devoy wrote:
> Hi list
>
> I need to store addresses for properties (as in real estate) so in my
> naivety I created a unique constraint like this:
>
> ALTER TABLE properties
> ADD CONSTRAINT is_unique_address
> UNIQUE (
> description, --e.g. Land north of Foo Cottage
> address_identifier_general,
> street,
> postcode
> );
>
> Of course, if any of the fields are NULL (which they often are) I end
> up with duplicates.
>
> One solution may be to add NOT NULL constraints and use empty strings
> instead of NULL values but, until asking around today, I thought this was
> generally considered bad practice.
>
> Please can anyone recommend a way of approaching this? Perhaps empty strings
> are pragmatic in this situation?
How about?:
create table properties (description varchar, address_identifier_general
varchar, street varchar, postcode varchar);
CREATE UNIQUE INDEX is_unique_address ON properties
((coalesce(description, '')),
(coalesce(address_identifier_general, '')),
(coalesce(street, '')),
(coalesce(postcode, ''))
);
insert into properties (description, street, postcode) values ('test',
'anywhere', '1234');
INSERT 0 1
insert into properties (description, street, postcode) values ('test',
'anywhere', '1234');
ERROR: duplicate key value violates unique constraint "is_unique_address"
DETAIL: Key (COALESCE(description, ''::character varying),
COALESCE(address_identifier_general, ''::character varying),
COALESCE(street, ''::character varying), COALESCE(postcode,
''::character varying))=(test, , anywhere, 1234) already exists.
>
> Kind regards
>
>
> Peter
>
>
--
Adrian Klaver
adrian(dot)klaver(at)aklaver(dot)com
From | Date | Subject | |
---|---|---|---|
Next Message | David G. Johnston | 2020-05-11 18:33:11 | Re: Enforcing uniqueness on [real estate/postal] addresses |
Previous Message | Matthias Apitz | 2020-05-11 18:18:10 | Re: PostgreSQL client hangs sometimes on 'EXEC SQL PREPARE sid_sisisinst FROM :select_anw;' |