1

I have a table called Staff I am currently creating. I have columns:

  • staffNo
  • fName
  • lName
  • position
  • sex
  • DOB
  • salary
  • branchNo

Currently, the entry I have in the postgres command line is:

CREATE TABLE Staff(
         staffNo     TEXT CONSTRAINT firstkey PRIMARY KEY,
         fname       TEXT NOT NULL,
         lname       TEXT NOT NULL,
         position    TEXT NOT NULL,
         sex         CHAR(1) NOT NULL,
         DOB         DATE NOT NULL,
         salary      INT NOT NULL,
         FOREIGN KEY (branchNo) REFERENCES Branch(branchNo));

I would like to set it so that for position, only either Manager, Assistant, or Supervisor can be inserted into that column. For sex, I would like the same to be for M or F. Can anyone provide an example of how this can be done?

1 Answer 1

4

You can achieve this using the check constraint:

CREATE TABLE Staff(
     staffNo     TEXT CONSTRAINT firstkey PRIMARY KEY,
     fname       TEXT NOT NULL,
     lname       TEXT NOT NULL,
     position    TEXT NOT NULL,
     sex         CHAR(1) NOT NULL,
     DOB         DATE NOT NULL,
     salary      INT NOT NULL,
     FOREIGN KEY (branchNo) REFERENCES Branch(branchNo),
     CHECK((position = 'Manager' or position = 'Assistant' or position = 'Supervisor') 
     AND (sex = 'F' OR sex = 'M')));

But it is more flexible if you reference those constants from other table (Perhaps a position_table)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much, I am actually following these examples in a book to prepare for a job interview :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.