-1

Consider I have two users with two different roles -- user1: role1, user2: role2

Many columns are same for both role types, for example consider data of birth. But for role1 saving data of birth is required(not null) whereas for role 2 it is optional(nullable). So is it better to maintain two different tables for two roles or keep same table and maintain logic in backend.

user4157124
  • 2,809
  • 13
  • 27
  • 42
arya.s
  • 111
  • 2
  • 11

1 Answers1

2

But for role1 saving data of birth is required(not null) whereas for role 2 it is optional(nullable).

Use table-level CHECK constraint:

CREATE TABLE user_role (
    user_name VARCHAR(255) NOT NULL,           -- common user info
    role_id INT NOT NULL,                      -- reference to role table 
    birth DATE,                                -- day of birth
    CHECK (role_id <> 1 OR birth IS NOT NULL)  -- if role=1 then check that birth date is set
);

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=a1ae67dd4dc31d446b65f41e54f59431

Akina
  • 39,301
  • 5
  • 14
  • 25