i created employees as superclass with 4 subclass, added value to employees, with my primary key also able to enter a subclass, is this right? - sql-insert

superclass
CREATE TABLE EMPLOYEE (
EMP_ID CHAR(2),
CONSTRAINT PK_EMP PRIMARY KEY (EMP_ID),
FNAME CHAR(15),
LNAME CHAR(15),
ADDRESS VARCHAR(255)
);
ALTER TABLE EMPLOYEE
ADD EMP_TYPE CHAR(3) NOT NULL;
ALTER TABLE EMPLOYEE
ADD CONSTRAINT CHECK_EMP_TYPE
CHECK (EMP_TYPE IN ('AGN', 'CLK', 'DRV', 'MGR'));
```subclass```
CREATE TABLE AGENT (
EMP_ID CHAR(2) PRIMARY KEY,
COMMISSION INT,
FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE(EMP_ID));
INSERT INTO EMPLOYEE
VALUES ('E1', 'JOHN', 'DOE', '2 ORACLE STREET, NEWCASTLE, NE25YU', 'MGR');
INSERT INTO EMPLOYEE
(EMP_ID, FNAME, LNAME, ADDRESS, EMP_TYPE)
VALUES ('E2', 'MARY', 'JAMES', '4 BILL STREET, NEWCASTLE, NE44TR', 'CLK');
INSERT INTO EMPLOYEE
INSERT INTO AGENT
2 VALUES ('E1', '500');
I was expecting an error message when I insert into the 'AGENT' subclass with 'E1' since i already have it in the superclass 'EMPLOYEE' table

Related

MariaDB Check value of an attribute w/ another table attribute

I want to assure at inserting a manager that department manager start date [DEPARTMENT.mgr_start_date] is coming after his birthdate [EMPLOYEE.bdate],
how can I do that?
CREATE TABLE IF NOT EXISTS EMPLOYEE
(
ssn INT(16) unsigned NOT NULL,
fname VARCHAR(16),
lname VARCHAR(16),
bdate DATE,
address VARCHAR(32),
gender enum('m','f'),
salary decimal(16,2),
Dno VARCHAR(8),
PRIMARY KEY (ssn)
);
CREATE TABLE IF NOT EXISTS DEPARTMENT
(
mgr_ssn INT(16) unsigned,
Dname VARCHAR(32),
mgr_start_date DATE,
Dnumber VARCHAR(8),
PRIMARY KEY (Dnumber),
FOREIGN KEY (mgr_ssn) REFERENCES EMPLOYEE(ssn)
);
You would have to do this with a trigger.
CHECK constraints can reference only columns in the table where the constraint is defined.
The full SQL standard includes a type of constraint called an ASSERTION, which allows multi-table constraints, but MariaDB does not implement this feature of SQL (very few brands of SQL databases do implement it).
CREATE TRIGGER t BEFORE INSERT ON DEPARTMENT
FOR EACH ROW BEGIN
IF NEW.mgr_start_date < (SELECT bdate FROM EMPLOYEE WHERE ssn = NEW.mgr_ssn) THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'manager is way too young';
END IF;
END
Test:
insert into EMPLOYEE set ssn=123, bdate='2021-01-01';
insert into DEPARTMENT set mgr_ssn=123, dnumber='1', mgr_start_date='2010-01-01';
ERROR 1644 (45000): manager is way too young

I need to create tables with "one to zero or to one" relationships in sqlite. This is what I have so far, is it right?

So I have this so far, I have to bind these two tables (one-to-zero or to-one relationship)
DROP TABLE if exists Person;
CREATE TABLE Person(
ID int NOT NULL,
Name varchar (40),
PRIMARY KEY(ID));
DROP TABLE if exists Pass;
CREATE TABLE Pass(
ID int REFERENCES Person,
Owner int,
PRIMARY KEY(ID),
FOREIGN KEY(Owner) REFERENCES Person(ID));
I'm going to use a different child table definition, because the
Pass table in your question doesn't make any sense; it doesn't
contain any information of its own.
CREATE TABLE Person (
ID INTEGER PRIMARY KEY,
Name VARCHAR(40) NOT NULL,
Dept INT REFERENCES Department(DeptID);
);
CREATE TABLE Department (
DeptID INTEGER PRIMARY KEY,
Name VARCHAR(120) NOT NULL
);
The Dept column of the Person table has a 1 : 0 or 1 relationship
to the Department table, because each row in the Person table
(1) can contain either zero or one (0 or 1) references to a row in
the Department table (the Dept column can be NULL).
Meaning that a person can be assigned to a department or not, but if
they are, they can only be assigned to 1 department.

How to connect tables

Im stuck with my code. I want everything from my serviceticket table to be shown with CUSTID. I get an error "ambiguous column name: CUSTID"
Can anyone help me? I have tried everything
create table customers(CUSTID INTEGER PRIMARY KEY AUTOINCREMENT,
FIRSTNAME TEXT(50),
LASTNAME TEXT (50),
STREET TEXT(50),
CITY TEXT(50),
ZIP INT(4),
PHONENUMBER INT(8),
EMAIL VARCHAR(50)
);
create table serviceticket(SERVICETICKETID int(2) NOT NULL PRIMARY KEY,
TICKETNUMBER INT,
CUSTID int,
DATE_RECIEVED text,
EXPECTED_DELIEVERYDATe TEXT,
COMMENTS TEXT,
DATE_RETURNED TEXT
);
insert into customers (FIRSTNAME, LASTNAME, STREET, CITY, ZIP, PHONENUMBER, EMAIL)
values ('Jørgen', 'Marven', 'Dræmmestad 22', 'Gjøvik', 6026,12837262, 'jørge#gmail.com');
insert into serviceticket(SERVICETICKETID, TICKETNUMBER,CUSTID, DATE_RECIEVED, EXPECTED_DELIEVERYDATE, COMMENTS, DATE_RETURNED)
values (56, 133, NULL, NULL, '12/4/19', '22/4/19', 'Wants authenic parts', '22/4/19');
select SERVICETICKETID, TICKETNUMBER, CUSTID, DATE_RECIEVED, EXPECTED_DELIEVERYDATE, COMMENTS, DATE_RETURNED
from serviceticket, customers
where serviceticket.CUSTID = customers.CUSTID;
You wrote select SERVICETICKETID, TICKETNUMBER, CUSTID, ... without specifying whether the CUSTID is from serviceticket or customers. Write
select SERVICETICKETID, TICKETNUMBER, customers.CUSTID, ...
and you should use the join syntax that is newer than the where syntax for joining tables. You can also use table aliases to make the query more readable
select
S.SERVICETICKETID, S.TICKETNUMBER, C.CUSTID, S.DATE_RECIEVED, S.EXPECTED_DELIEVERYDATE,
S.COMMENTS, S.DATE_RETURNED
from
serviceticket S
INNER JOIN customers C
ON S.CUSTID = C.CUSTID

Foreign key problems in sqlite3

I get an error "unknown column "CustID" in foreign key definition"
and "no such table: serviceticket"
Can anyone help me?
drop table if exists customer;
drop table if exists serviceticket;
PRAGMA foreign_keys = ON;
create table customer (CustID char(6) not null primary key UNIQUE,
CustNAME TEXT,
STREET TEXT,
CITY TEXT,
ZIP INT(5),
EMAIL VARCHAR,
PHONENUMBER INT(10)
);
create table serviceticket (TicketID char(4) not null primary key,
TicketNO char(5),
WatchID char(6),
DateRecieved char(6),
ExpectedDelivery char(6),
COMMENTS text,
DateReturned char(6),
FOREIGN KEY (CustID) REFERENCES customer (CustID)
);
insert into customer (CustID, CustNAME, STREET, CITY, ZIP, PHONENUMBER, EMAIL)
values (170362, 'James', 'Vvegen', New York, 12345, 8170710520, 'brt92#outlook.com');
insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
values (6745, 87463, 098636, 124319, 362836, 683743, 'Nothing to say', 583728);
The code below will work.
This has three changes instead of using FOREIGN KEY (CustID) REFERENCES customer (CustID), which requires the column CustID in the serviceticket table to have been defined; CustID REFERENCES customer (CustID), this defines the CustID column and sets the Foreign Key constraint.
The second change replaces 098636 which will result in a Foreign Key constraint conflict, with 170362 which is a value that exists in the CustID column of the Customer table.
e.g. :-
This works (after the table has been correctly defined) :-
insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
values (6745, 87463, '170362', 124319, 362836, 683743, 'Nothing to say', 583728)
> Affected rows: 1
> Time: 0.082s
This will (as per the message) fail
insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
values (6745, 87463, 098636, 124319, 362836, 683743, 'Nothing to say', 583728)
> FOREIGN KEY constraint failed
> Time: 0s
The third change is swapping the order in which the tables are dropped.
The working code
drop table if exists serviceticket; -- <<<<<<<<<< if not coding ON DELETE CASCADE the children have to be deleted first (so moved before dropping customer table)
drop table if exists customer;
PRAGMA foreign_keys = ON;
create table customer (CustID char(6) not null primary key UNIQUE,
CustNAME TEXT,
STREET TEXT,
CITY TEXT,
ZIP INT(5),
EMAIL VARCHAR,
PHONENUMBER INT(10)
);
create table serviceticket (TicketID char(4) not null primary key,
TicketNO char(5),
WatchID char(6),
DateRecieved char(6),
ExpectedDelivery char(6),
COMMENTS text,
DateReturned char(6),
CustID REFERENCES customer (CustID) -- <<<<<<<<<< defines the column and foreign key
);
insert into customer (CustID, CustNAME, STREET, CITY, ZIP, PHONENUMBER, EMAIL)
values (170362, 'James', 'Vvegen', 'New York', 12345, 8170710520, 'brt92#outlook.com');
insert into serviceticket (TicketID, WatchID, CustID, DateRecieved, DateReturned, ExpectedDelivery, COMMENTS, DateReturned)
values (6745, 87463,
'170362', -- <<<<<<<<<< MUST match a value in CustID column of the customer table (changed to work)
124319, 362836, 683743, 'Nothing to say', 583728);
Additional
you may wish to consider using (or variants thereof):-
CustID REFERENCES customer (CustID) ON DELETE CASCADE ON UPDATE CASCADE
4.3. ON DELETE and ON UPDATE Actions
You did not define CustID prior of the definition of the foreign key:
create table serviceticket (TicketID char(4) not null primary key,
TicketNO char(5),
WatchID char(6),
DateRecieved char(6),
ExpectedDelivery char(6),
COMMENTS text,
DateReturned char(6),
CustID char(6),
FOREIGN KEY (CustID) REFERENCES customer(CustID)
);

Whats the proper way to structure a SQLite DB with items and lists of items to create them [duplicate]

Can anyone explain how to implement one-to-one, one-to-many and many-to-many relationships while designing tables with some examples?
One-to-one: Use a foreign key to the referenced table:
student: student_id, first_name, last_name, address_id
address: address_id, address, city, zipcode, student_id # you can have a
# "link back" if you need
You must also put a unique constraint on the foreign key column (addess.student_id) to prevent multiple rows in the child table (address) from relating to the same row in the referenced table (student).
One-to-many: Use a foreign key on the many side of the relationship linking back to the "one" side:
teachers: teacher_id, first_name, last_name # the "one" side
classes: class_id, class_name, teacher_id # the "many" side
Many-to-many: Use a junction table (example):
student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id # the junction table
Example queries:
-- Getting all students for a class:
SELECT s.student_id, last_name
FROM student_classes sc
INNER JOIN students s ON s.student_id = sc.student_id
WHERE sc.class_id = X
-- Getting all classes for a student:
SELECT c.class_id, name
FROM student_classes sc
INNER JOIN classes c ON c.class_id = sc.class_id
WHERE sc.student_id = Y
Here are some real-world examples of the types of relationships:
One-to-one (1:1)
A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.
To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).
For example:
CREATE TABLE Gov(
GID number(6) PRIMARY KEY,
Name varchar2(25),
Address varchar2(30),
TermBegin date,
TermEnd date
);
CREATE TABLE State(
SID number(3) PRIMARY KEY,
StateName varchar2(15),
Population number(10),
SGID Number(4) REFERENCES Gov(GID),
CONSTRAINT GOV_SDID UNIQUE (SGID)
);
INSERT INTO gov(GID, Name, Address, TermBegin)
values(110, 'Bob', '123 Any St', '1-Jan-2009');
INSERT INTO STATE values(111, 'Virginia', 2000000, 110);
One-to-many (1:M)
A relationship is one-to-many if and only if one record from table A is
related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.
To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).
For example:
CREATE TABLE Vendor(
VendorNumber number(4) PRIMARY KEY,
Name varchar2(20),
Address varchar2(20),
City varchar2(15),
Street varchar2(2),
ZipCode varchar2(10),
Contact varchar2(16),
PhoneNumber varchar2(12),
Status varchar2(8),
StampDate date
);
CREATE TABLE Inventory(
Item varchar2(6) PRIMARY KEY,
Description varchar2(30),
CurrentQuantity number(4) NOT NULL,
VendorNumber number(2) REFERENCES Vendor(VendorNumber),
ReorderQuantity number(3) NOT NULL
);
Many-to-many (M:M)
A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.
To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.
CREATE TABLE Class(
ClassID varchar2(10) PRIMARY KEY,
Title varchar2(30),
Instructor varchar2(30),
Day varchar2(15),
Time varchar2(10)
);
CREATE TABLE Student(
StudentID varchar2(15) PRIMARY KEY,
Name varchar2(35),
Major varchar2(35),
ClassYear varchar2(10),
Status varchar2(10)
);
CREATE TABLE ClassStudentRelation(
StudentID varchar2(15) NOT NULL,
ClassID varchar2(14) NOT NULL,
FOREIGN KEY (StudentID) REFERENCES Student(StudentID),
FOREIGN KEY (ClassID) REFERENCES Class(ClassID),
UNIQUE (StudentID, ClassID)
);
One-to-many
The one-to-many table relationship looks as follows:
In a relational database system, a one-to-many table relationship links two tables based on a Foreign Key column in the child which references the Primary Key of the parent table row.
In the table diagram above, the post_id column in the post_comment table has a Foreign Key relationship with the post table id Primary Key column:
ALTER TABLE
post_comment
ADD CONSTRAINT
fk_post_comment_post_id
FOREIGN KEY (post_id) REFERENCES post
One-to-one
The one-to-one table relationship looks as follows:
In a relational database system, a one-to-one table relationship links two tables based on a Primary Key column in the child which is also a Foreign Key referencing the Primary Key of the parent table row.
Therefore, we can say that the child table shares the Primary Key with the parent table.
In the table diagram above, the id column in the post_details table has also a Foreign Key relationship with the post table id Primary Key column:
ALTER TABLE
post_details
ADD CONSTRAINT
fk_post_details_id
FOREIGN KEY (id) REFERENCES post
Many-to-many
The many-to-many table relationship looks as follows:
In a relational database system, a many-to-many table relationship links two parent tables via a child table which contains two Foreign Key columns referencing the Primary Key columns of the two parent tables.
In the table diagram above, the post_id column in the post_tag table has also a Foreign Key relationship with the post table id Primary Key column:
ALTER TABLE
post_tag
ADD CONSTRAINT
fk_post_tag_post_id
FOREIGN KEY (post_id) REFERENCES post
And, the tag_id column in the post_tag table has a Foreign Key relationship with the tag table id Primary Key column:
ALTER TABLE
post_tag
ADD CONSTRAINT
fk_post_tag_tag_id
FOREIGN KEY (tag_id) REFERENCES tag
One to one (1-1) relationship:
This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.
One to Many (1-M) relationship:
This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).
Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.
-- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
ID INT IDENTITY(1, 1) NOT NULL,
CallTime DATETIME NOT NULL DEFAULT GETDATE(),
CallerPhoneNumber CHAR(10) NOT NULL
)
-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
ID INT IDENTITY(1, 1) NOT NULL,
CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
Subject VARCHAR(250) NOT NULL,
Notes VARCHAR(8000) NOT NULL,
Completed BIT NOT NULL DEFAULT 0
)
-- This table will link a phone call with a ticket.
CREATE TABLE dbo.PhoneCalls_Tickets
(
PhoneCallID INT NOT NULL,
TicketID INT NOT NULL
)

Resources