1

I would like to know if it's possible to create a not null constraint for either column name OR column surname. ex :

create table football_players (
    id VARCHAR(36) PRIMARY KEY,
    name VARCHAR(20),
    surname VARCHAR(20)
);

Sometimes we know the name or the surname but not both. I don't want a player without name in my database.

Mike
  • 23,542
  • 14
  • 76
  • 87
Robinson
  • 85
  • 1
  • 7

4 Answers4

2

The standard SQL method would be:

create table football_players (
    id VARCHAR(36) PRIMARY KEY,
    name VARCHAR(20),
    surname VARCHAR(20),
    constraint chk_name_surname check (name is not null or surname is not null)
);

This does not work in MySQL (the question was not originally tagged MySQL). Doing this in MySQL requires a trigger.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • You probably want to check for empty strings as well. For most people an empty string is not a "valid" name either. –  Nov 09 '15 at 15:07
  • Yes i tried that, but when i test it on mysql, i can enter null for name and surname. – Robinson Nov 09 '15 at 15:42
  • @Robinson: that's because MySQL still doesn't support check constraints. –  Nov 09 '15 at 17:15
  • `DELIMITER // CREATE TRIGGER trigger_players_name_not_null BEFORE INSERT ON players FOR EACH ROW BEGIN DECLARE dummy,baddata INT; SET baddata = 0; IF NEW.name is null and NEW.surname is null THEN SET baddata = 1; END IF; IF baddata = 1 THEN SELECT CONCAT('Cannot Insert This Because Age ',NEW.name, NEW.surname,' are Invalid') INTO dummy FROM information_schema.tables; END IF; END // DELIMITER ;` – Robinson Nov 09 '15 at 21:58
1

MySQL doesn't support check constraints, but you can do something similar with a trigger.

Community
  • 1
  • 1
Don Kirkby
  • 53,582
  • 27
  • 205
  • 286
0

If I understood correctly:

You can ask if any data from PHP to load is null. For instance:

If (!isset($name)) {
    //code sql
}
else if (!isset($lastname)){
    //code sql
}
else {
    //code sql
}

and altering the table:

alter table TABLENAME modify FIELD varchar(40) not null default ''

or you can select IS NOT NULL:

SELECT LastName,FirstName FROM tablename
WHERE LastName IS NOT NULL
0
DELIMITER //
CREATE TRIGGER trigger_players_name_not_null BEFORE INSERT ON players
   FOR EACH ROW BEGIN
   DECLARE dummy,baddata INT;
   SET baddata = 0;
      IF NEW.name is null and NEW.surname is null THEN SET baddata = 1;
      END IF;
      IF baddata = 1 THEN
         SELECT CONCAT('Cannot Insert This Because Age ',NEW.name, NEW.surname,' are Invalid')
         INTO dummy FROM information_schema.tables;
      END IF;
END
//
DELIMITER ;
Robinson
  • 85
  • 1
  • 7