0

I have a table USER

CREATE TABLE "USER"
  (
    USER_ID    INTEGER NOT NULL ,
    CREATED_BY INTEGER NOT NULL ,
  ) ;
ALTER TABLE "USER" ADD CONSTRAINT USER_PK PRIMARY KEY ( USER_ID ) ;

For this particular database, I need the CREATED_BY table to be a foreign key to USER_ID in the same table.

ALTER TABLE "USER" ADD CONSTRAINT USER_USER_FK FOREIGN KEY ( CREATED_BY ) REFERENCES "USER" ( USER_ID ) ;

Because of this constraint, my insert statement will always fail on the first user.

Is there a best practice for getting around this? Can I disable the constraint for the first user added and then re-enable the constraint?

jipot
  • 304
  • 3
  • 13
  • 34
  • 2
    Make it `NULL` instead of `NOT NULL`? – Siyual Aug 22 '16 at 18:14
  • 1
    is USER_ID really an auto increment? you could make it null instead as suggested by others then once inserted update CREATED_BY to the userID that was inserted and then make it not null again. If it is not auto incremented, just leave it as it is and repeat your USER_ID value for you CREATED_BY value in your insert statement – Matt Aug 22 '16 at 18:31

2 Answers2

1

You can modify your create table script, so that it accepts null values for created_by column. Then you can insert your first record(that has a user_id and a null for created_by). Logically someone in that User table has to be the root record(in other words admin or first-user whose record isn't created by someone else).

0
CREATE TABLE "USER"
  (
    USER_ID    INTEGER NOT NULL ,
    CREATED_BY INTEGER ,
  ) ;
ALTER TABLE "USER" ADD CONSTRAINT USER_PK PRIMARY KEY ( USER_ID ) ;

If table exists this line makes the column NOT NULL or non nullable.

ALTER TABLE USER MODIFY CREATED_BY INTEGER NOT NULL;

How to add not null constraint to existing column in MySQL5.1

Community
  • 1
  • 1
Matt
  • 13,833
  • 2
  • 16
  • 28