3

I have the following MySql syntax to create a table with constraint to check P_Id column have value greater than zero, but it still allows me to add values less than 0 like -1,-2, etc.

CREATE TABLE Persons(
    P_Id int NOT NULL ,
    LastName varchar( 255 ) NOT NULL ,
    FirstName varchar( 255 ) ,
    Address varchar( 255 ) ,
    City varchar( 255 ) ,
    CHECK (
        P_Id >0
    )
)

Is there anything that i am doing wrong in above structure to have value for P_Id > 0 ??

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
Kalpesh Jain
  • 409
  • 3
  • 10
  • 19

2 Answers2

2

Check constraints don't work in mysql. You have to make some trick to emulate them. Take a look at this article

http://forge.mysql.com/wiki/Triggers#Emulating_Check_Constraints

Nicola Cossu
  • 54,599
  • 15
  • 92
  • 98
1

You could add a derived

tinyint NOT NULL

column called

id_check

with (for example) the formula

(IF(id<1,NULL,1))

(many other variants feasible)

Be aware that column names are non-case-sensitive, so best lowercase them.

YesThatIsMyName
  • 1,585
  • 3
  • 23
  • 30
druid62
  • 109
  • 3
  • I now prefer it like this: `\`CHECK_id\` tinyint unsigned NOT NULL AS (IF(id>0,1,-1))`, because that leads to a clearer error message. – druid62 Jun 24 '19 at 11:44