Restriction Check in ProstgreSQL does not work

0

the next check restriction does not do its function,

CREATE TABLE products (

    product_no integer NOT NULL,
    name text NOT NULL,
    price numeric
    CONSTRAINT ck_nombre CHECK (name like '[A-Z][0-9][0-9]')
);

At the time of entering data, only let me enter as text in the name field the following '[AZ] [0-9] [0-9]' ,

Any ideas on how to make it work?

    
asked by Carlos L.F 31.07.2018 в 04:50
source

1 answer

0

Apparently what you are trying to do is a CHECK against a POSIX regular expression

The syntax would then be:

CREATE TABLE products (
    product_no integer NOT NULL,
    name text NOT NULL,
    price numeric
    CONSTRAINT ck_nombre CHECK (name ~ '[A-Z][0-9][0-9]')
);

Where ~ is the operator to say it matches and is case-sensitive.

Currently, when using LIKE , you are literally defining the text.

Note 1: Your regular expression says: "A capital letter followed by two numbers", but accept that the sequence is in any part of the text. Therefore the text: 'hola abuelita A25 te quiero mucho' meets the check.

If what you want is exactly that sequence, with nothing before or after, your check should be defined as

CONSTRAINT ck_nombre CHECK (name ~ '^[A-Z][0-9][0-9]$'::text)

Or, simpler:

CONSTRAINT ck_nombre CHECK (name ~ '^[A-Z]\d{2}$'::text)

Where the special characters ^ and $ respectively mean "start with ..." and "end with ...". (and \d means a numeric character).

    
answered by 31.07.2018 / 15:33
source