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
Use
ALTER TABLE
to add a constraint to an existing table:use
ALTER TABLE
instead