skip to Main Content

I’m new to stackoverflow, so in case of any error of formatting, or whatsoever, please let me know.

I’m a newbie in SQL so please bare with me.

I have two tables:

CREATE TABLE Users (
    idUser INT NOT NULL PRIMARY KEY,
    username VARCHAR(100) NOT NULL
)

CREATE TABLE Login(
    idLogin INT NOT NULL PRIMARY KEY,
    idUser INT NOT NULL,
    dateOfLogin DATETIME NOT NULL
)

I need to add a costraint such as Users.idUser = Login.idUser. How do I do it?

I’ve tried the following attempt:

Changing the create table to:

CREATE TABLE Login(
    idLogin INT NOT NULL PRIMARY KEY,
    idUser INT FOREIGN KEY REFERENCES Users(idUser),
    dateOfLogin DATETIME NOT NULL
)

But the teacher didn’t approve this solution, he wants the constraint to be added via a different Query.

2

Answers


  1. Use ALTER TABLE to add a constraint to an existing table:

    ALTER TABLE Login ADD CONSTRAINT FOREIGN KEY (idUser) REFERENCES Users (idUser);
    
    Login or Signup to reply.
  2. use ALTER TABLE instead

    ALTER TABLE Login
    ADD CONSTRAINT FK_LoginUsersOrder
    FOREIGN KEY (idUser ) REFERENCES Users(idUser); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search