Primary key not null - sql

I am doing an Sql assignment in which I need to create a few tables. The assignment requires:
Make sure that you define NOT NULL constraints for the PK of each table
I don't get this. When we are defining a key as Primary Key, why should we write NOT NULL separately with it? Doesn't defining a key as PRIMARY KEY itself mean not null and unique?
Please explain!
Edit (copied from below):
CREATE TABLE Faculty(
FacNo char(11) not null,
FacFirstName varchar(30) not null,
FacLastName varchar(30) not null,
FacCity varchar(30) not null,
FacState char(2) not null,
FacZipCode char(10) not null,
FacRank char(4),
FacHireDate date,
FacSalary decimal(10,2),
FacSupervisor char(11),
FacDept char(6),
CONSTRAINT FacultyPK PRIMARY KEY (FacNo));
Is this correct? The FACNO column is not null plus it's also a primary key.

http://www.techonthenet.com/oracle/primary_keys.php
In Oracle, a primary key is a single field or combination of fields
that uniquely defines a record. None of the fields that are part of
the primary key can contain a null value. A table can have only one
primary key.
when you set PK for a table the column will be set to NOT NULL even if you specify it as nullable
-- Create table
create table t_test_pk(
col1 varchar2(5) null
);
SQL> desc t_test_pk
Name Type Nullable Default Comments
---- ----------- -------- ------- --------
COL1 VARCHAR2(5) Y
so... the column is nullable
then we set PK for the table:
SQL> alter table t_test_pk add constraint pk_1 primary key (COL1);
Table altered
and try to insert null into
SQL> insert into t_test_pk values (null);
insert into t_test_pk values (null)
ORA-01400: cannot insert NULL into ("T_TEST_PK"."COL1")
something was changed! check in SqlPlus - the column is not nullable - and get error... we cannot insert null into the column because it was used in PK
SQL> desc t_test_pk;
Name Type Nullable Default Comments
---- ----------- -------- ------- --------
COL1 VARCHAR2(5)
OK... try to set it to nullable
SQL> alter table t_test_pk modify col1 null;
alter table t_test_pk modify col1 null
ORA-01451: column to be modified to NULL cannot be modified to NULL

I imagine the reason your instructor asks for this is to make sure you write DDL that shows your intent clearly. Trusting auto conversion of null to not null does not help readability of DDL so I'd request all DDL to be written such that the create table statement shows the intended nullability of all columns.

Problem solved, with the following query
CREATE TABLE Faculty(
FacNo char(11) not null,
FacFirstName varchar(30) not null,
FacLastName varchar(30) not null,
FacCity varchar(30) not null,
FacState char(2) not null,
FacZipCode char(10) not null,
FacRank char(4),
FacHireDate date,
FacSalary decimal(10,2),
FacSupervisor char(11),
FacDept char(6),
CONSTRAINT FacultyPK PRIMARY KEY (FacNo) );

Related

beginner sql missing keyword and invalid identifier

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
);

Is there any needs of adding constraints for the DDL?

create table Country(
code char(3) PRIMARY KEY,
name varchar2(100) NOT NULL
);
create table Member(
firstname varchar(100) NOT NULL,
lastname varchar(100) NOT NULL,
title varchar(100) NOT NULL,
member_id INTEGER PRIMARY KEY,
Country_code char(3) NOT NULL REFERENCES Country(code)
ON DELETE CASCADE
ON UPDATE CASCADE
);
create table Athlete(
id integer NOT NULL REFERENCES Member(member_id)
ON DELETE NO ACTION
ON UPDATE CASCADE
);
create table Official(
id integer NOT NULL REFERENCES Member(member_id)
ON DELETE NO ACTION
ON UPDATE CASCADE
);
create table Staff(
id integer NOT NULL REFERENCES Member(member_id)
ON DELETE NO ACTION
ON UPDATE CASCADE
);
Create table Books(
when timestamp NOT NULL,
member_id integer NOT NULL REFERENCES Member(member_id),
start_time timestamp NOT NULL REFERENCES Journey(start_time),
start_date date NOT NULL REFERENCES Journey(start_date),
byStaff integer NOT NULL REFERENCES Staff(id)
);
create table Journey(
start_time timestamp PRIMARY KEY,
start_date date PRIMARY KEY,
member_id integer PRIMARY KEY REFERENCES Member(member_id),
nbooked integer NOT NULL,
departure varchar(100) NOT NULL REFERENCES Place(name),
arrival varchar(100) NOT NULL REFERENCES Place(name),
code varchar(100) NOT NULL REFERENCES Vehicle(code)
);
create table Vehicle(
code varchar(100) PRIMARY KEY,
capacity varchar(100) NOT NULL
);
create table Place(
name varchar(50) PRIMARY KEY,
address varchar(100) NOT NULL,
longitude float NOT NULL,
latitude float` NOT NULL
);
create table SportVenue(
name varchar(50) NOT NULL REFERENCES Place(name)
);
create table Accommodation(
name varchar(50) NOT NULL REFERENCES Place(name)
);
create table Event(
name varchar(100) PRIMARY KEY,
result_type varchar(100) NOT NULL,
time timestamp NOT NULL,
date date NOT NULL,
sport_name varchar(50) NOT NULL REFERENCES Sport(name),
);
For the DDL above, is there any needs of adding constraints for the DDL? If it needs to be modified, which constraints should be implemented? I am so confused on writing DDL... wef ewf ew fwe fewf wef oiwejf oiwej fioejwo ifjewo ifwjeoif jewoiew fiowefioje w
Thanks.
Constraints aka validation should be implemented from all sides of your application. Front-end, back-end, and your database. Otherwise, you would fail on the overall data integrity. So, the answer to your question is yes. Details depend on the nature of the data you will be working with.

SQL Error 02291 - Issues with foreign keys [duplicate]

This question already has answers here:
SQL Error: ORA-02291: integrity constraint
(4 answers)
Closed 7 years ago.
We are trying to insert data to our tables, however we have run into an error and can't see the problem. This is what we are getting -
INSERT INTO Item(Manifest_barcode,Trip_ID,Item_weight,Pickup_customer,Delivery_customer,Category) VALUES (159601450,73495,2156,166,184,'A')
Error report -
SQL Error: ORA-02291: integrity constraint (HR.SYS_C009055) violated - parent key not found
02291. 00000 - "integrity constraint (%s.%s) violated - parent key not found"
We have checked the order of the creation of the tables, and as far as we can tell everything is in the right place. All of the foreign keys seem to be correct as well.
This is how we are dropping/creating the tables -
DROP TABLE Item;
DROP TABLE Trip;
DROP TABLE Vehicle;
DROP TABLE Vehicle_Type;
DROP TABLE Employee;
DROP TABLE Customer;
DROP TABLE Category;
CREATE TABLE Category(
Category VARCHAR2(100) NOT NULL,
Description VARCHAR2(100) NOT NULL,
Requirements VARCHAR2(100),
PRIMARY KEY(Category)
);
CREATE TABLE Customer(
Reference INT NOT NULL,
Name VARCHAR2(100) NOT NULL,
Address VARCHAR2(100) NOT NULL,
Town VARCHAR2(100) NOT NULL,
Post_code VARCHAR2(8) NOT NULL,
Telephone INT NOT NULL,
Contact_first_name VARCHAR2(100) NOT NULL,
Contact_last_name VARCHAR2(100) NOT NULL,
Email VARCHAR2(100) NOT NULL,
PRIMARY KEY(Reference)
);
CREATE TABLE Employee(
Employee_no INT NOT NULL,
First_name VARCHAR2(100) NOT NULL,
Last_name VARCHAR2(100) NOT NULL,
NI_No VARCHAR2(100) NOT NULL,
Telephone VARCHAR2(100) NOT NULL,
Mobile VARCHAR2(100) NOT NULL,
Hazardous_goods VARCHAR2(100) NOT NULL,
PRIMARY KEY(Employee_no)
);
CREATE TABLE Vehicle_Type(
Vehicle_Type_ID VARCHAR2(100) NOT NULL,
Model VARCHAR2(100) NOT NULL,
Make VARCHAR2(100) NOT NULL,
PRIMARY KEY(Vehicle_Type_ID)
);
CREATE TABLE Vehicle(
Registration VARCHAR2(100) NOT NULL,
Vehicle_Type_ID VARCHAR2(100) NOT NULL,
GVW VARCHAR2(100) NOT NULL,
Vehicle_Year INT NOT NULL,
Body VARCHAR2(100),
PRIMARY KEY(Registration),
FOREIGN KEY(Vehicle_Type_ID) REFERENCES Vehicle_Type(Vehicle_Type_ID)
);
CREATE TABLE Trip(
Trip_ID INT NOT NULL,
Departure_date VARCHAR2(100) NOT NULL,
Return_date VARCHAR2(100) NOT NULL,
Employee_no INT NOT NULL,
Vehicle_registration VARCHAR2(100) NOT NULL,
PRIMARY KEY(Trip_ID),
FOREIGN KEY(Employee_no) REFERENCES Employee(Employee_no)
);
CREATE TABLE Item(
Manifest_barcode VARCHAR2(100) NOT NULL,
Trip_ID INT NOT NULL,
Item_weight INT NOT NULL,
Pickup_customer INT NOT NULL,
Delivery_customer INT NOT NULL,
Category VARCHAR2(100) NOT NULL,
PRIMARY KEY(Manifest_barcode),
FOREIGN KEY(Trip_ID) REFERENCES Trip(Trip_ID),
FOREIGN KEY(Category) REFERENCES Category(Category)
);
This is how the items are being inserted -
INSERT INTO Customer (Name,Reference,Address,Town,Post_code,Telephone,Contact_first_name,Contact_last_name,Email) VALUES
('Calash Ltd.',1,'88 Rinkomania Lane','Cardigan','SA55 8BA',11671595763,'Cameron','Dunnico','c.dunnico#calash.co.uk');
INSERT INTO Employee (Employee_no,First_name,Last_name,NI_No,Telephone,Mobile,Hazardous_goods) VALUES
(0045619,'Eamon','O''Looney','JJ 56 53 26 B','1656727840','76599770175','N');
INSERT INTO Vehicle_Type (Vehicle_Type_ID,Model,Make) VALUES
(1,'RIEVER','ALBION');
INSERT INTO Vehicle(Registration,Vehicle_Type_ID,GVW,Vehicle_Year,Body) VALUES
('4585 AW',1,20321,1963,'');
INSERT INTO Category (Category, Description, Requirements) VALUES
('A','Normal','');
INSERT INTO Trip(Trip_ID,Departure_date,Return_date,Employee_no,Vehicle_registration) VALUES
(72943,'40910','40914',0028539,'BR58BXE');
INSERT INTO Item(Manifest_barcode,Trip_ID,Item_weight,Pickup_customer,Delivery_customer,Category) VALUES
(541769754,73421,3629,44,145,'A');
Anyone have any suggestions?
Your full insert script has 13 inserts into the item table with trip_id 73495. Your error is being thrown from the first one:
INSERT INTO Item(Manifest_barcode,Trip_ID,Item_weight,Pickup_customer,Delivery_customer,Category)
VALUES (159601450,73495,2156,166,184,'A');
Your script does not have a matching insert for the trip table. You have IDs either side:
INSERT INTO Trip(Trip_ID,Departure_date,Return_date,Employee_no,Vehicle_registration)
VALUES (73494,'40994','40995',0077517,'PY11 OAA');
INSERT INTO Trip(Trip_ID,Departure_date,Return_date,Employee_no,Vehicle_registration)
VALUES (73496,'40994','41000',0083413,'PY58 UHF');
But there is not one for ID 73495.
Searching that script for 73495 only matches those 13 item inserts, and a later item which has a manifest_barcode of 617349505 which contains it. But that is all.
There is no matching trip, which is what the exception is telling you.
Hi please check the following
you have inserted this row in the employee table with employee_no=0045619
INSERT INTO Employee (Employee_no,First_name,Last_name,NI_No,Telephone,Mobile,Hazardous_goods) VALUES
(0045619,'Eamon','O''Looney','JJ 56 53 26 B','1656727840','76599770175','N');
trip is the table which was referencing the employee table
INSERT INTO Trip(Trip_ID,Departure_date,Return_date,Employee_no,Vehicle_registration) VALUES
(72943,'40910','40914',0028539,'BR58BXE');
in this insert statement you had inserted a row with employee_no=0028539, which was not matched with the employee_no(0045619) available in the employee table.
please correct the value and try to insert with the same employee number in the employee table
---------editied----------------
check the tripid in item(73421) is available in the trip table?

I cannot create a simple table

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.

Creating Table (Oracle)

I am creating two tables. The first table creates with no errors, but when I try to create the SUBHEAD table, I get an error: Line 2, Missing right parenthesis. I am not sure what is wrong with this line. Below is my SQL statements:
CREATE TABLE HEAD
(Code NUMERIC(4,0) NOT NULL PRIMARY KEY,
HeadName VARCHAR(50) NOT NULL UNIQUE,
HType VARCHAR(1) NOT NULL,
HDate DATE NOT NULL,
OpBal DECIMAL(11,2) NOT NULL
);
CREATE TABLE SUBHEAD
(HCode NUMERIC(4,0) NOT NULL FOREIGN KEY REFERENCES HEAD(Code),
SubCode NUMERIC(4,0) NOT NULL,
SubName VARCHAR(50) NOT NULL,
SDate DATE NOT NULL,
OpBal DECIMAL (11,2) NOT NULL,
CONSTRAINT pk_subheadID PRIMARY KEY (HCode, SubCode)
);
syntax: http://docs.oracle.com/cd/B28359_01/server.111/b28286/clauses002.htm#SQLRF52167
note that "in-line" constraint syntax is : "col col_type REFERENCES TAB(COL)" and not "FOREIGN KEY"
The data type for number is NUMBER not NUMERIC
So my memory did not fool me - you can have multiple in-line constraints (although the syntax graph doesn't show it):
SQL> create table tt1(a number primary key);
Table created.
SQL> create table tt2(a number references tt1(a) not null);
Table created.
CREATE TABLE SUBHEAD
(HCode NUMERIC(4,0) NOT NULL, FOREIGN KEY (Hcode) REFERENCES HEAD(Code),
SubCode NUMERIC(4,0) NOT NULL,
SubName VARCHAR(50) NOT NULL,
SDate DATE NOT NULL,
OpBal DECIMAL (11,2) NOT NULL,
CONSTRAINT pk_subheadID PRIMARY KEY (HCode, SubCode)
);
(note comma, and reference to the new table column)