I try to Write the SQL code to create the table named ‘EMP_1’. This table is a subset of the EMPLOYEE table, and the structure of the table is summarized as shown below.
This is the information:
Attribute Name Data Type Remarks
EMP_NUM CHAR(3) PK
EMP_LNAME VARCHAR(15) Not Null
EMP_FNAME VARCHAR(15) Not Null
EMP_INITIAL CHAR(1)
EMP_HIREDATE DATE
JOB_CODE CHAR(3) FK (from JOB table)
My code:
CREATE TABLE EMP_1
(
EMP_NUM CHAR(3) PRIMARY KEY,
EMP_LNAME VARCHAR(15) Not Null,
EMP_FNAME VARCHAR(15) Not Null,
EMP_INITIAL CHAR(1) ,
EMP_HIREDATE DATETIME,
JOB_CODE CHAR(3) FOREIGN KEY (JOB_CODE) REFERENCES JOB(JOB_CODE)
);
I keep getting CONSTRAINT error
I think you might be missing a comma before the constraint. This worked when I tried it:
CREATE TABLE EMP_1
(
EMP_NUM CHAR(3) PRIMARY KEY,
EMP_LNAME VARCHAR(15) Not Null,
EMP_FNAME VARCHAR(15) Not Null,
EMP_INITIAL CHAR(1),
EMP_HIREDATE DATETIME,
JOB_CODE CHAR(3),
CONSTRAINT FK_JOBS FOREIGN KEY (JOB_CODE) REFERENCES JOB(JOB_CODE)
);
Make sure your PRIMARY KEY and FOREIGN KEY have the same DATA TYPE.
I've not scrpited a FK for a while, but my recollection is that you can EITHER use:
JOB_CODE CHAR(3) FOREIGN KEY REFERENCES JOB(JOB_CODE)
which will create an FK named JOB_CODE,
OR:
split the line so you create the field and add the constraint separately as per JPW's response.
Your original code tries to combine the 2 approaches which will throw the error you describe.
Related
When create table have error "Incorrect syntax near ','."
I cant see this error in code. Please point out this error.
CREATE TABLE books(
id INT NOT NULL IDENTITY PRIMARY KEY,
author VARCHAR(150) NOT null,
date DATETIME NOT null,
city VARCHAR(50) NOT null,
publishing VARCHAR(50) NOT null,
udc INT NOT null,
quantity INT NOT null,
inventory_numbers INT NOT NULL PRIMARY KEY)
CREATE TABLE systematic_catalog(
id INT NOT NULL IDENTITY PRIMARY KEY,
udc_id INT FOREIGN KEY REFERENCES books(udc),
knowledge_area VARCHAR)
CREATE TABLE issued_books(
date_issued DATETIME,
inventory_numbers_id INT FOREIGN KEY REFERENCES books(inventory_numbers))
CREATE TABLE readers(
id INT NOT NULL IDENTITY PRIMARY KEY,
last_name VARCHAR CONSTRAINT,
first_name VARCHAR CONSTRAINT,
middle_name VARCHAR,
phone_number INT(11),
address VARCHAR,
ticket_number INT CONSTRAINT,
date_registration DATETIME,
date_reregistratiom DATETIME,
issued_books_id FOREIGN KEY REFERENCES issued_books(inventory_numbers_id))
You cannot add multiple primary keys to the table, either composite ey (combination of two fields) or Unique constraint can be added instead.
CREATE TABLE books(
id INT NOT NULL IDENTITY PRIMARY KEY,
author VARCHAR(150) NOT null,
date DATETIME NOT null,
city VARCHAR(50) NOT null,
publishing VARCHAR(50) NOT null,
udc INT NOT null,
quantity INT NOT null,
inventory_numbers INT NOT NULL PRIMARY KEY)
this is an error, you cannot ass multiple primary keys. Instead you can add Unique constraint
Correction would be,
CREATE TABLE books(
id INT NOT NULL IDENTITY PRIMARY KEY,
author VARCHAR(150) NOT null,
date DATETIME NOT null,
city VARCHAR(50) NOT null,
publishing VARCHAR(50) NOT null,
udc INT NOT null Unique, --this is used to create the second table
quantity INT NOT null,
inventory_numbers INT NOT NULL Unique )
CREATE TABLE systematic_catalog(
id INT NOT NULL IDENTITY PRIMARY KEY,
udc_id INT FOREIGN KEY REFERENCES books(udc), --Referenced column needs to be unique
knowledge_area VARCHAR)
CREATE TABLE issued_books(
date_issued DATETIME,
inventory_numbers_id INT FOREIGN KEY REFERENCES books(inventory_numbers))
CREATE TABLE readers(
id INT NOT NULL IDENTITY PRIMARY KEY,
last_name VARCHAR (255),
first_name VARCHAR (255),
middle_name VARCHAR(255),
phone_number INT,
[address] VARCHAR(255),
ticket_number INT ,
date_registration DATETIME,
date_reregistratiom DATETIME)
You cannot use a foreign key of another table as a foreign key for some other table. You need to read more on table, Primary key constraints and foreign key referencing.
This cannot be done. you are trying to refer to the foreign key of issued_books table as a foreign key in readers table, which is wrong.
issued_books_id INT FOREIGN KEY REFERENCES issued_books(inventory_numbers_id))
I hope this explanation will give you a better understanding of errors. There were synatx errors as well as wrong use of the SQL table creation steps. I have added the corrected code for you. Feel free to contact any time.
I have a problem with adding foreign keys with alter table command. I don't know how to make it so it works.
I need to add ISIK_ID and STAADION_ID to ISIK_STAADIONIL table as foreign key.
Here is my code:
CREATE TABLE ISIK(
ISIK_ID INT NOT NULL,
EESNIMI VARCHAR(25) NOT NULL,
PEREKONNANIMI VARCHAR(25) NOT NULL,
ISIKUKOOD VARCHAR(20),
KODAKONDSUS VARCHAR(30),
SUGU CHAR(1) NOT NULL,
HARIDUSTASE CHAR(1) NOT NULL,
TELEFONI_NR VARCHAR(20),
SYNNIPAEV DATE,
CONSTRAINT ISIK_ID_PK PRIMARY KEY (ISIK_ID)
);
CREATE TABLE ISIK_STAADIONIL(
ISIK_STAADIONIL_ID INT NOT NULL,
CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_STAADIONIL_ID),
ALATES TIMESTAMP,
KUNI TIMESTAMP
);
CREATE TABLE STAADION(
STAADION_ID INT NOT NULL,
NIMETUS VARCHAR(20),
KIRJELDUS VARCHAR(100),
ASUKOHT VARCHAR(50),
SUURUS VARCHAR(20),
MAHUTAVUS INT,
EHITATUD VARCHAR(20),
EHITAJA VARCHAR(20),
CONSTRAINT STAADION_ID_PK PRIMARY KEY (STAADION_ID)
);
ALTER TABLE ISIK_STAADIONIL
ADD CONSTRAINT ISIK_ID_FK
FOREIGN KEY(ISIK_ID)
REFERENCES ISIK(ID);
You need to add the columns first (to the table) before you can create FK constraints using them.
CREATE TABLE ISIK_STAADIONIL(
ISIK_STAADIONIL_ID INT NOT NULL,
CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_STAADIONIL_ID),
ALATES TIMESTAMP,
KUNI TIMESTAMP,
ISIK_ID INT,
STAADION_ID INT
);
And then your ALTER statement should work fine.
UPDATE
Changing the table-design slightly would make more sense, as per following. The logic is that ISIK_ID and STAADION_ID would together be sufficient to determine uniqueness in the ISIK_STAADIONIL table, so a separate ID is redundant:
CREATE TABLE ISIK_STAADIONIL(
ISIK_ID INT NOT NULL,
STAADION_ID INT NOT NULL,
CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_ID, STAADION_ID),
ALATES TIMESTAMP,
KUNI TIMESTAMP
);
CREATE table Book
(
book_title varchar (100) not null ,
book_genre char(60) not null,
Date_of_publish date not null,
user_code char(7) not null ,
book_id char (7) primary key not null ,
constraint writer__id_fk foreign key (writer_id),
constraint publisher__id_fk foreign key (publisher_id)
);
I'm getting
[ORA-00905: missing keyword]
in publisher table
CREATE table publisher
(
publisher_id char (7) primary key not null,
publisher_name char(20) not null,
publisher_number char(10) not null,
publisher_email varchar2(60) not null,
publisher_address varchar2(60) not null,
);
I'm getting
[ORA-00904: : invalid identifier]
The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is created:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
Refer this link for more details
https://www.w3schools.com/sql/sql_foreignkey.asp
Hope this helps.
Welcome to the wonderful world of SQL! :-)
General remark:
Please tell us what kind of DBMS you're using. MySQL? SQL Server? Oracle? SQlite? Different systems use different kinds of syntaxes.
First statement:
The problem seems to be in the FOREIGN KEY-portion.
Usually, you'll state something like:
CONSTRAINT [constraint_name] FOREIGN KEY([column_in_this_table]) REFERENCES OTHER_TABLE([column_in_other_table])
edit (added):
The [column_in_this_table] has to exist in your DDL (CREATE TABLE-statement), like so:
CREATE TABLE Book ( book_title ... etc., publisher_id INT, CONSTRAINT FK_publ_id FOREIGN KEY(publisher_id) REFERENCES publisher(publisher_id));
Here, you'll have a 'original' column called 'publisher_id', in the 'publisher'-table. You refer to it from within the 'Book'-table, by first having a 'publisher_id' column in the 'Book'-table (which should have the same DDL as the original column by the way). Next, you'll add a FOREIGN KEY to the 'Book'-table, that is imposed on the Book(publisher_id) column. Note, that you could also name the column in your 'Book'-table differently -- like, say, 'Spongebob' or 'Patrick'. But for future use, you'd like naming conventions that tell what you might expect to find in a column. So you'd name columns for what they contain.
Second statement:
The problem is with the last portion of your statement, where there's a comma after the NOT NULL portion for column publisher_address.
(Part of) your statement:
publisher_address varchar2(60) not null, );
Try replacing that with:
publisher_address VARCHAR2(60) NOT NULL);
edit (note to self):
VARCHAR2 turns out to be a valid datatype in Oracle databases (see:
Oracle documentation)
For your first table, the Foreign Keys do not reference any table. For your second table, I would imagine that comma after your last column isn't helping anything.
So this is the answer.
CREATE table Book
(
book_title varchar (100) not null ,
book_genre char(60) not null,
Date_of_publish date not null,
user_code char(7) not null ,
publisher_id char (7) not null,
writer_id char(7) not null,
book_id char (7) primary key not null ,
CONSTRAINT book_writer_id_fk FOREIGN KEY(writer_id) REFERENCES writer(writer_id),
CONSTRAINT book_publisher_id_fk FOREIGN KEY(publisher_id) REFERENCES publisher(publisher_id)
);
CREATE table publisher
(
publisher_id char (7) primary key not null,
publisher_name char(20) not null,
publisher_number char(10) not null,
publisher_email varchar2(60) not null,
publisher_address varchar2(60) not null
);
I'm having some problem with the table called HoursandEarnings and I kept getting an error saying,
"There are no primary or candidate keys in the referenced table
'PayRoll' that match the referencing column list in the foreign key
'fk_EmployeeNumber'"
create table Address
(
PostalCode nvarchar(6) not null,
Address nvarchar(50) not null,
City nvarchar(30) not null,
Province nvarchar(30) not null,
constraint pk_postalcode primary key(PostalCode)
)
create table Payperiod
(
StartDate DateTime not null,
EndDate DateTime not null,
constraint pk_StartDate primary key(StartDate)
)
create table PayRoll
(
EmployeeNumber nvarchar(30) not null,
StartDate DateTime not null
constraint fk_StartDate references Payperiod(StartDate),
PostalCode nvarchar(6) not null
constraint fk_PostalCode references Address(PostalCode),
Department nvarchar(50) not null,
TotalEarningsCurrent decimal(5,2) not null,
TotalEarningsYearToDate decimal(5,2) not null,
Netpay decimal(5,2) not null,
EmployeeName nvarchar(30) not null,
constraint pk_PayRoll primary key(EmployeeNumber,StartDate)
)
create table HoursandEarnings
(
EmployeeNumber nvarchar(30) not null
constraint fk_EmployeeNumber references PayRoll(EmployeeNumber),
StartDate DateTime not null
constraint fk_StartDate references Payperiod(StartDate),
HoursAndEarningsDescription nvarchar(50) not null,
HoursandEarningsCurrent decimal(5,2) not null,
HoursandEarningsYearToDate decimal(5,2) not null,
constraint pk_HoursandEarnings primary
key clustered(EmployeeNumber,StartDate,HoursAndEarningsDescription)
)
create table EmployerPaidBenefits
(
EmployeeNumber nvarchar(30) not null
constraint fk_EmployerPaidBenefits_EmployeeNumber references PayRoll(EmployeeNumber),
StartDate DateTime not null
constraint fk_EmployerPaidBenefits_StartDate references Payperiod(StartDate),
EmployerpaidBenefitsDescription nvarchar(50) not null,
EmployerPaidBenefitsCurrent decimal(5,2) not null,
EmployerPaidBenefitsYearToDate decimal(5,2) not null
constraint pk_EmployerPaidBenefits
primary key(EmployeeNumber,StartDate,EmployerpaidBenefitsDescription)
)
create table Taxesanddeductions
(
EmployeeNumber nvarchar(30) not null,
constraint fk_Taxesanddeductions_EmployeeNumber references PayRoll(EmployeeNumber),
StartDate DateTime not null
constraint fk_Taxesanddeductions_StartDate references Payperiod(StartDate),
TaxesandDeductionsDescription nvarchar(50) not null,
TaxesandDeductionsCurrent decimal(5,2) not null,
EmployerPaidBenefitsYeartoDate decimal(5,2) not null,
constraint pk_Taxesanddeductions
primary key(EmployeeNumber,StartDate,TaxesandDeductionsDescription)
)
Because you have a composite key (EmployeeNumber,StartDate) on table PayRoll, you will need to reference both keys in the foreign key in the other tables which reference it.
If EmployeeNumber is unique in table Payroll, then you can make just EmployeeNumber the primary key on Payroll, and then your foreign keys on the other 3 tables to Payroll will be valid as-is.(Not the case)
Not related, but I believe you may run into problems making PostalCode a primary key on Address - this will mean that only one address with the same PostalCode may be added to the table. I would suggest a surrogate key instead.
Edit
Example of both columns in the foreign key:
constraint fk_HE_EmployeeNumber
foreign key(EmployeeNumber, StartDate)
references PayRoll(EmployeeNumber, StartDate)
Note also that primary and foreign key constraint names must be unique within the database (not just in the table) - you'll need to rename the duplicate keys like fk_StartDate.
SqlFiddle here
You may also find at some point that the encumberance and additional storage requirements of composite / compound keys may make implementation of simple surrogate keys (like int identity() or Guids) a simpler approach.
I have the following SQL code
CREATE TABLE EMPLOYEES
(
empID NUMBER NOT NULL,
ssn CHAR(10) NOT NULL,
fname VARCHAR(20) NOT NULL,
minit VARCHAR(15),
lname VARCHAR(30) NOT NULL,
gender CHAR(2),
email VARCHAR(40),
street VARCHAR(40),
postalCode NUMBER,
city VARCHAR(20),
country VARCHAR(20),
job VARCHAR(20),
salary NUMBER(*,2),
birthdate DATE,
specialization VARCHAR(30),
username VARCHAR(25),
password VARCHAR(25),
levelOfClearance VARCHAR(20),
PRIMARY KEY (empID),
UNIQUE (ssn)
);
CREATE TABLE PATIENTS
(
patientID NUMBER NOT NULL,
healthInsID NUMBER,
fname VARCHAR(20) NOT NULL,
minit VARCHAR(15),
lname VARCHAR(30) NOT NULL,
gender CHAR(1),
email VARCHAR(40),
street VARCHAR(40),
postalCode CHAR(4),
city VARCHAR(20),
country VARCHAR(20),
PRIMARY KEY (patientID),
FOREIGN KEY (healthInsID) REFERENCES HEALTH_INSURANCES (healthInsID)
ON DELETE SET NULL
);
CREATE TABLE APPOINTMENTS
(
appointmentID NUMBER NOT NULL,
empID NUMBER NOT NULL,
appointmentDate DATE,
cost NUMBER(*,2),
patientID NUMBER,
PRIMARY KEY (appointmentID),
FOREIGN KEY (empID) REFERENCES EMPLOYEES (empID)
ON DELETE SET NULL,
FOREIGN KEY (patientID) REFERENCES PATIENTS
ON DELETE SET NULL
);
CREATE TABLE SYMPTOMS
(
appointmentID NUMBER NOT NULL,
description VARCHAR(100),
PRIMARY KEY (appointmentID),
FOREIGN KEY (appointmentID) REFERENCES APPOINTMENTS (appointmentID)
ON DELETE SET NULL
);
The first 3 tables are created without a problem, but the last one give me the error "ORA-02270: no matching unique or primary key for this column-list". I have searched a lot but could not find any solution yet.
Not sure but I think the problem probably is with last line in your symptoms table
CREATE TABLE SYMPTOMS
(
appointmentID NUMBER NOT NULL, <-- it's NOT NULL
description VARCHAR(100),
PRIMARY KEY (appointmentID),
**FOREIGN KEY (appointmentID) REFERENCES APPOINTMENTS (appointmentID)
ON DELETE SET NULL** <-- here you are saying -- set to null on delete
);
You are trying to null the appointmentID which you have declared as non null. This doesn't looks correct. I tried creating the same table with on delete cascade and it worked fine.
(OR)
Try creating your SYMPTOMS table like below
CREATE TABLE SYMPTOMS
(
appointmentID number NOT NULL,
description VARCHAR(100),
FK_APT_APTID number null,
PRIMARY KEY (appointmentID),
FOREIGN KEY (FK_APT_APTID) REFERENCES APPOINTMENTS (appointmentID)
ON DELETE set null
);
See this sample fiddle
http://sqlfiddle.com/#!3/826dd
The problem is with the SYMPTOMS table, your PK can be set to null (which is not possible)
I suggest you'll do the following:
Add a symptom ID column as a PK (or set the combination of description and appointmentID as PK)
Set on delete cascade or don't set a delete policy: this will cause an error if you delete an appointment and will raise an exception that you'll need to handle in your code.
sql fiddle: http://sqlfiddle.com/#!4/67d4b
CREATE TABLE SYMPTOMS
(
SymptomID NUMBER NOT NULL,
appointmentID NUMBER NOT NULL,
description VARCHAR(100),
PRIMARY KEY (appointmentID),
FOREIGN KEY (appointmentID) REFERENCES APPOINTMENTS (appointmentID)
);