简体   繁体   中英

Adding constraints to an SQL Table with altering

I have a defined type:

CREATE TYPE salary AS (salary numeric);

and a table holding data:

CREATE TABLE employees (
lastname text,
firstname text,
salary salary, 
);

I want to use ALTER TABLE to add a constraint to the salary attribute:

ALTER TABLE employees ADD CONSTRAINT minimum_salary CHECK(salary > 1.47333);

this gives me the error ERROR: operator does not exist: salary > numeric . Why is this the case?

To start with: a type seems overkill to just store a scalar value. Why no just create a check constraint on the column?

create table employees (
    lastname text, 
    firstname text, 
    salary numeric check(salary > 1.473333)
);

Coming back to your original question: I don't think that it is possible to put a check constraint on a type column. One thing you could do, however, is to create a domain . Domains extend the standard types and do accept check constraints.

Consider this demo :

create domain salary numeric check(value > 1.47333);
create table employees (lastname text, firstname text, salary salary);
insert into employees values('foo', 'bar', 1);
-- ERROR:  value for domain salary violates check constraint "salary_check"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM