I have created a Staff table. It has a self reference key - sql

create table STAFF
(
StaffID TINYINT IDENTITY NOT NULL,
StaffName varchar(20) NOT NULL,
Phone varchar(10) NOT NULL,
Gender char(01),
DoB date NOT NULL,
Mentor TINYINT,
Payment_ID TINYINT NOT NULL,
constraint staff_pk primary key (StaffID),
constraint staff_fk
foreign key (Payment_ID) references PAYMENT(Payment_ID),
constraint mentor_fk
foreign key (Mentor) references staff(StaffID)
);
Table was created successfully. But when I'm going to insert values like this:
insert into STAFF
values ('Adeesha', '077282018', 'M', '1997-11-30', '', '5'),
('Kavitha', '0772556899', 'F', '1956-11-28', '', '4'),
('Patee Aiya', '0775669844', 'M', '1954-01-04', '', '3'),
('Chanuka', '0772562984', 'M', '1997-02-24', '', '2'),
('Umesha', '0723328284', 'F', '1997-11-26', '', '3');
I get the following error:
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "mentor_fk".
The conflict occurred in database "F_T", table "dbo.STAFF", column 'StaffID'.

An empty string ('') is not the same as NULL. You should use NULL:
insert into STAFF(StaffName, Phone, Gender, DoB, Mentor, Payment_ID)
values ('Adeesha', '077282018', 'M', '1997-11-30', NULL, 5),
('Kavitha', '0772556899', 'F', '1956-11-28', NULL, 4),
('Patee Aiya', '0775669844', 'M', '1954-01-04', NULL, 3),
('Chanuka', '0772562984', 'M', '1997-02-24', NULL, 2),
('Umesha', '0723328284', 'F', '1997-11-26', NULL, 3);
Notes:
When using insert, list all the columns being inserted into the table. This is a best-practice.
Do not insert into the identity column. It is generated automatically.
Use NULL to mean NULL rather than an empty string. They are not the same.
If a value is a number, do not enclose it in single quotes.

Related

I am receiving 'FOREIGN KEY constraint failed' errors but cannot find the source

I have these four tables that represent a hardware store:
PRAGMA foreign_keys = 1;
DROP TABLE IF EXISTS transactions;
DROP TABLE IF EXISTS customers;
DROP TABLE IF EXISTS tools;
DROP TABLE IF EXISTS departments;
CREATE TABLE departments (
name PRIMARY KEY NOT NULL
);
CREATE TABLE tools (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tool_name TEXT NOT NULL UNIQUE,
tool_price DECIMAL(5, 2),
tool_department VARCHAR(250),
FOREIGN KEY (tool_department) REFERENCES departments(name) ON DELETE CASCADE
);
CREATE TABLE customers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT NOT NULL UNIQUE,
last_name TEXT NOT NULL UNIQUE,
phone_number INTEGER UNIQUE NOT NULL
);
CREATE TABLE transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
customer_id INTEGER,
customer_first_name TEXT NOT NULL,
customer_last_name TEXT NOT NULL,
customer_phone_number INTEGER NOT NULL,
tool_purchased TEXT NOT NULL,
item_quantity INTEGER NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE,
FOREIGN KEY (tool_purchased) REFERENCES tools(tool_name) ON DELETE CASCADE,
FOREIGN KEY (customer_first_name) REFERENCES customers(first_name) ON DELETE CASCADE,
FOREIGN KEY (customer_last_name) REFERENCES customers(last_name) ON DELETE CASCADE,
FOREIGN KEY (customer_phone_number) REFERENCES customers(phone_number) ON DELETE CASCADE
);
I am trying to insert this data into my tables:
INSERT INTO tools(tool_name, tool_price, tool_department)
VALUES
('Snow shovel', 16.50, 'Home & Garden'),
('Work light', 29.99, 'Electrical'),
('Wheelbarrow', 89.99, 'Home & Garden'),
('Pipe Wrench', 18.99, 'Plumbing'),
('Pipe Cutter', 36.36, 'Plumbing'),
('Rake', 15.45, 'Home & Garden');
INSERT INTO customers(first_name, last_name, phone_number)
VALUES
('John', 'Smith', 1111111111),
('Jane', 'Doe', 2222222222);
INSERT INTO transactions(customer_id, customer_first_name, customer_last_name, customer_phone_number, tool_purchased, item_quantity)
VALUES
(1, 'John', 'Smith', 1111111111, 'Work light', 1),
(1, 'John', 'Smith', 1111111111, 'Pipe Cutter', 2),
(2, 'Jane', 'Doe', 2222222222, 'Snow shovel', 3),
(2, 'Jane', 'Doe', 2222222222, 'Work light', 1),
(2, 'Jane', 'Doe', 2222222222, 'Pipe Wrench', 1),
(2, 'Jane', 'Doe', 2222222222, 'Pipe Cutter', 1),
(1, 'John', 'Smith', 1111111111, 'Wheelbarrow', 3);
However, I am getting these errors back:
Error: near line 1: FOREIGN KEY constraint failed
Error: near line 15: FOREIGN KEY constraint failed
You haven't defined the type of column name in table departments! Must be VARCHAR(250) like in table tools (FK).
CREATE TABLE departments (
name VARCHAR(250) PRIMARY KEY NOT NULL
);
Correct departments table and insert department in it in order to reference tools to this dept. You cannot reference a tool to department that does not exist yet. Also read docs about column types TEXT and VARCHAR.

adding multiple foreign keys to existing tables

I'm relatively new to SQL. I was wondering how I would go about adding data to my foreign keys. I have gotten errors with everything I've tried and google hasn't been much help... also, please ignore the nonsense data I've added.
Thank you!
Here's what I'm starting with:
CREATE TABLE GAME
(
GAME_ID INT NOT NULL AUTO_INCREMENT,
GAME_NAME VARCHAR(20) NOT NULL,
PLATFORM_ID INT NOT NULL,
PUBLISHER_ID INT NOT NULL,
DEV_ID INT NOT NULL,
GAME_GENRE VARCHAR(20),
PRIMARY KEY(GAME_ID)
);
CREATE TABLE DEVELOPER
(
DEV_ID INT NOT NULL AUTO_INCREMENT,
DEV_NAME VARCHAR(20) NOT NULL,
DEV_CIY VARCHAR(20),
DEV_COUNTRY VARCHAR(20),
DEV_CEO VARCHAR(20),
DEV_GAMES INT,
PRIMARY KEY(DEV_ID)
);
CREATE TABLE PUBLISHER
(
PUBLISHER_ID INT NOT NULL AUTO_INCREMENT,
PUBLISHER_NAME VARCHAR(20) NOT NULL,
DEV_ID INT NOT NULL,
PUBLISHER_CEO VARCHAR(20),
PUBLISHER_GAMES INT,
PUBLISHER_EMPLOYEES INT,
PRIMARY KEY(PUBLISHER_ID)
);
CREATE TABLE EMPLOYEE
(
EMPLOYEE_ID INT NOT NULL AUTO_INCREMENT,
EMPLOYEE_NAME VARCHAR(20) NOT NULL,
EMPLOYEE_ROLE VARCHAR(20) NOT NULL,
DEV_ID INT NOT NULL,
GAME_ID INT NOT NULL,
EMPLOYEE_NUM CHAR(10),
PRIMARY KEY(EMPLOYEE_ID)
);
CREATE TABLE GAMECREDITS
(
GAMECREDITS_ID INT NOT NULL AUTO_INCREMENT,
GAME_ID INT NOT NULL,
PUBLISHER_ID INT NOT NULL,
DEV_ID INT NOT NULL,
GAMECREDITS_YEAR INT,
PLATFORM_ID INT NOT NULL,
PRIMARY KEY(GAMECREDITS_ID)
);
CREATE TABLE PLATFORM
(
PLATFORM_ID INT NOT NULL AUTO_INCREMENT,
PLATFORM_PC BOOLEAN,
GAME_ID INT NOT NULL,
PLATFORM_PRICE NUMERIC,
PLATFORM_XBOOX BOOLEAN,
PLATFORM_SWOOTCH BOOLEAN,
PRIMARY KEY(PLATFORM_ID)
);
ALTER TABLE GAME
ADD FOREIGN KEY (PLATFORM_ID) REFERENCES PLATFORM(PLATFORM_ID),
ADD FOREIGN KEY (PUBLISHER_ID) REFERENCES PUBLISHER(PUBLISHER_ID),
ADD FOREIGN KEY (DEV_ID) REFERENCES DEVELOPER(DEV_ID);
ALTER TABLE PUBLISHER
ADD FOREIGN KEY (DEV_ID) REFERENCES DEVELOPER(DEV_ID);
ALTER TABLE EMPLOYEE
ADD FOREIGN KEY (DEV_ID) REFERENCES DEVELOPER(DEV_ID),
ADD FOREIGN KEY (GAME_ID) REFERENCES GAME(GAME_ID);
ALTER TABLE GAMECREDITS
ADD FOREIGN KEY (GAME_ID) REFERENCES GAME(GAME_ID),
ADD FOREIGN KEY (PUBLISHER_ID) REFERENCES PUBLISHER(PUBLISHER_ID),
ADD FOREIGN KEY (DEV_ID) REFERENCES DEVELOPER(DEV_ID),
ADD FOREIGN KEY (PLATFORM_ID) REFERENCES PLATFORM(PLATFORM_ID);
ALTER TABLE PLATFORM
ADD FOREIGN KEY (GAME_ID) REFERENCES GAME(GAME_ID);
INSERT INTO GAME (GAME_ID, GAME_NAME, GAME_GENRE)
VALUES
(001, 'GTA Sons Andres', 'Sand-Box'),
(002, 'Not Destiny', 'FPS'),
(003, "Red Alive Redemption", 'TPS'),
(004, 'Animal Passing', 'Simulation'),
(005, 'Knights Creed', 'Action'),
(006, 'Simpsins hit and run', 'Action');
INSERT INTO DEVELOPER
(DEV_ID, DEV_NAME, DEV_CITY, DEV_COUNTRY, DEV_CEO, DEV_GAMES)
VALUES
(010, 'Kawcho Games', 'Texas', 'usa', 'Joe Houston', 6),
(020, 'NotStar Games', 'Vancouver', 'canada' 'Sam Haser', 7),
(030, 'Boungie', 'New York', 'usa' 'Pete Larson', 3),
(040, 'Pinnaple Games', 'Halifax', 'canada', 'Sam Haser', 6),
(050, 'Noontendo', 'Toronto', 'canada', 'Bowser Doug', 10),
(060, 'Oobiesoft', 'Washington', 'usa', 'Larry Seinfield', 5);
INSERT INTO PUBLISHER
(PUBLISHER_ID, PUBLISHER_NAME, PUBLISHER_CEO, PUBLISHER_GAMES, PUBLISHER_EMPLOYEES)
VALUES
(111, 'Kawcho Publishing', 'Cassie Haley', 44, 20),
(222, 'Walmort Publishers', 134, 'Perry Plat', 45, 23),
(333, 'Kents Publishing', 156, 'Linda Frend', 23, 15),
(444, 'Coffee House', 145, 'Susy Paige', 45, 15),
(555, 'Off the ground publishing', 189, 'Kerry Doug', 60, 25),
(666, 'yourWay', 1, 'beff, jezos', 46, 25);
INSERT INTO EMPLOYEE
(EMPLOYEE_ID, EMPLOYEE_NAME, EMPLOYEE_ROLE)
VALUES
(100, 'Fiacre Julen', 'Ui design'),
(200, 'Sebastian Aneta', 'Animator'),
(300, 'Xavia Guy', 'Developer'),
(400, 'Oakley Jillie', 'Character Design'),
(500, 'Keaton Lula', 'Marketing'),
(600, 'Liv Randell', 'Developer');
INSERT INTO GAMECREDITS
(GAMECREDITS_ID, GAMECREDITS_YEAR)
VALUES
(101, 2012),
(102, 2020),
(103, 1999),
(104, 2015),
(105, 2017),
(106, 2019);
INSERT INTO PLATFORM
(PLATFORM_ID, PLATFORM_PC, PLATFORM_PRICE, PLATFORM_XBOOX, PLATFORM_SWOOTCH);
VALUES
(123, FALSE, 49.99, TRUE, FALSE),
(145, TRUE, 25.00, FALSE, FALSE),
(167, TRUE 26.99, FALSE, FALSE),
(189, FALSE, 12.49, FALSE, TRUE),
(134, FALSE, 69.99, FALSE, TRUE),
(156, FALSE, 36.00, TRUE, FALSE);
I appreciate any help I can get as this is relating to a final assignment of mine. The only solutions I've found through google and my teacher would take up like 60 update queries to fill in my tables.
Give me any advice you can :)

What is the proper way to set up multiple references to one table?

Using Postgres and setting up my schema in an SQL file for an app I am building. I have tables: users, posts, templates and a junction table users_posts_templates.
Users is 1:N with Posts
Users is also 1:N with Templates
users_posts_templates is meant to act as a junction so that a Post owned by a User can have N templates from any and all Users, my schema is set up as such:
CREATE TABLE users (
username VARCHAR(30) UNIQUE PRIMARY KEY,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
password TEXT NOT NULL,
email TEXT NOT NULL
CHECK (position('#' IN email) > 1),
address TEXT NOT NULL,
is_admin BOOLEAN NOT NULL DEFAULT FALSE
);
-- CREATE TYPE category AS ENUM ('environment', 'health care', 'defense');
-- CREATE TYPE states AS ENUM ('USA', 'AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FM', 'FL', 'GA', 'GU', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MH', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'MP', 'OH', 'OK', 'OR', 'PW', 'PA', 'PR', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VI', 'VA', 'WA', 'WV', 'WI', 'WY');
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
link TEXT,
body TEXT NOT NULL,
username VARCHAR(30) NOT NULL
FOREIGN KEY REFERENCES users(username) ON DELETE CASCADE,
tag category NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
location states NOT NULL
)
CREATE TABLE templates (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
body TEXT NOT NULL,
)
CREATE TABLE users_posts_templates (
post_id INTEGER NOT NULL
FOREIGN KEY REFERENCES posts(id) ON DELETE CASCADE,
username VARCHAR(30) NOT NULL
FOREIGN KEY REFERENCES users(username) ON DELETE CASCADE,
template_id INTEGER NOT NULL
FOREIGN KEY REFERENCES templates(id) ON DELETE CASCADE,
PRIMARY KEY (username, post_id, template_id)
)
I get the error when I build ERROR: relation "users" already exists
How do I set up my relationships so that the Posts table and junction table can both reference Users or is there a better approach I should consider?
Which version of PostgreSQL you are using? I tested on the Postgre 13 and Postgre 14 this script, no error, all tables and foreign keys were created.
CREATE TABLE users (
username VARCHAR(30) UNIQUE PRIMARY KEY,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
password TEXT NOT NULL,
email TEXT NOT NULL
CHECK (position('#' IN email) > 1),
address TEXT NOT NULL,
is_admin BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
link TEXT,
body TEXT NOT NULL,
username VARCHAR(30) NOT null
REFERENCES users(username) ON DELETE CASCADE,
tag text NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE templates (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
body TEXT NOT NULL
);
CREATE TABLE users_posts_templates (
post_id INTEGER NOT NULL
REFERENCES posts(id) ON DELETE CASCADE,
username VARCHAR(30) NOT NULL
REFERENCES users(username) ON DELETE CASCADE,
template_id INTEGER NOT NULL
REFERENCES templates(id) ON DELETE CASCADE,
PRIMARY KEY (username, post_id, template_id)
);
I do not know your business logic, so maybe I am thinking incorrectly. I think the username field in the users_posts_templates table is unnecessary. Because if we need it, we can get it from the posts table using users_posts_templates.post_id

Insert Into, Conflit with Foreign Key

create table Interventions
(
InterventionID BIGINT IDENTITY (1,1) PRIMARY KEY NOT NULL,
InterventionCustomerID BIGINT FOREIGN KEY REFERENCES Customer(CustomerID) NOT NULL,
InterventionMalfunctionDescription NVARCHAR(MAX) NOT NULL,
CustomerID BIGINT FOREIGN KEY REFERENCES Customer(CustomerID),
EmployeeID INT FOREIGN KEY REFERENCES Employees(EmployeeID),
TypeOfEquipementID INT FOREIGN KEY REFERENCES TypeOfEquipements(TypeOfEquipementID),
StatusID INT FOREIGN KEY REFERENCES TypeOfStatus(StatusID),
SerialNumber VARCHAR(255) FOREIGN KEY REFERENCES SerialNumbers(SerialNumber),
GroupID INT FOREIGN KEY REFERENCES TypeOfGroup(GroupID) NOT NULL,
InterventionCreateDate DATETIME NOT NULL,
InterventionStartDate DATETIME,
InterventionFinnishDate DATETIME,
InterventionArchiveDate DATETIME
);
create table Customer
(
CustomerID BIGINT IDENTITY(1,1) PRIMARY KEY NOT NULL,
OrganizationName VARCHAR(255) NOT NULL,
Telephone VARCHAR(255),
MobileTelephone VARCHAR(255) NOT NULL,
CustomerAdressLine1 VARCHAR(255) NOT NULL,
CustomerAdressLine2 VARCHAR(255),
PostalCode VARCHAR(255) NOT NULL,
FederalTaxID VARCHAR(255) UNIQUE NOT NULL,
EmailAddress VARCHAR(255) UNIQUE NOT NULL,
SageCustomerID BIGINT UNIQUE
);
INSERT INTO Interventions(InterventionCustomerID, InterventionMalfunctionDescription, CustomerID, EmployeeID, TypeOfEquipementID, StatusID, SerialNumber, GroupID, InterventionCreateDate, InterventionStartDate, InterventionFinnishDate, InterventionArchiveDate) VALUES
('1', 'abc', '4', '4', '1', '1', 'SerialNumber1', '1', '2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04'),
('2', 'abc', '5', '5', '2', '2', 'SerialNumber2', '2', '2019-02-01', '2019-02-02', '2019-02-03', '2019-02-03'),
('3', 'abc', '6', '6', '3', '3', 'SerialNumber3', '3', '2019-03-01', '2019-03-02', '2019-03-03', '2019-03-04');
Select * from Customer;
Erro:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Intervent__Inter__6C190EBB". The conflict occurred in database "ADSGLOBAL", table "dbo.Customer", column 'CustomerID'.
You have a constraint on InterventionCustomerID that says it references Customer(CustomerID).
Your insert statement says you're trying to insert the values 1, 2, 3 in to that column.
Your SELECT * FROM customer shows that customers 1, 2, 3 don't exist in that table.
You can't insert records for customers 1, 2, 3 until you've created them in the Customer table.

SQL Server check constraint on part of composite primary key

Trying to learn SQL. Can't seem to find an answer to this or if I did I don't know enough SQL to recognize it as such. Can you create a table with a composite primary key and a check constraint on one of the key columns?
To be specific this fails with:
The INSERT statement conflicted with the CHECK constraint "CH_AddressType". The conflict occurred in database "tempdb", table "dbo.#t
If I comment out the check constraint in the table create and uncomment the alter table the insert works.
Do the two ways of creating the table... create the same table? What am I missing?
create table #t
(
entityNo int not null,
addressType char(1) not null,
valid char(1) not null,
address1 varchar(256) not null,
address2 varchar(256) not null,
city varchar(128) not null,
stateCode char(2) not null,
zipCode char(5) not null,
dtCreate datetime not null,
dtUpdate datetime not null
constraint PK_Address_Entity
primary key (entityNo, addressType),
constraint CH_AddressValid
check (valid in ('Y', 'N')),
constraint CH_AddressType
check (valid in ('H', 'V'))
)
go
--alter table #t
-- add constraint CH_Address_Type check ((addressType) in ('H', 'V'))
--go
insert into #t (entityNo, addressType, valid, address1, address2, city, stateCode, zipCode, dtCreate, dtUpdate)
values (100, 'H', 'Y', '100 Some Street', '' , 'Someville', 'PA', '19335', '2016-10-08', '2016-10-08')
select * from #t
go
drop table #t
go
constraint CH_AddressType check (valid in ('H', 'V'))
should be
constraint CH_AddressType check (addressType in ('H', 'V'))