H2 database CREATE TABLE with constraint - sql

I have two SQL statements:
CREATE TABLE legs(legid INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
playerid1 INT NOT NULL REFERENCES players(playerid),
playerid2 INT NOT NULL REFERENCES players(playerid),
added TIMESTAMP AS CURRENT_TIMESTAMP NOT NULL);
ALTER TABLE legs ADD CONSTRAINT distinct_players CHECK(playerid1 <> playerid2);
I am 99% sure I should be able to condense them into one, i.e:
CREATE TABLE table(...
playerid2 INT NOT NULL REFERENCES players(playerid) CHECK(playerid1 <> playerid2),
...);
However, I am consistently getting a syntax error. AFAIK, this is where the constraint should be.

CREATE TABLE legs(legid INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
playerid1 INT NOT NULL REFERENCES players(playerid),
playerid2 INT NOT NULL REFERENCES players(playerid),
added TIMESTAMP AS CURRENT_TIMESTAMP NOT NULL,
CHECK (playerid1 <> playerid2));

Related

Referenced table not found in the data dictionary mariadb

so I have written this Mariadb code as the solution for an assignment and am running it on HeidiSQL. It should work in theory however I am getting the error message SQL Error (1005): Can't create table bestellung.arbeitetin (errno: 150 "Foreign key constraint is incorrectly formed"). Upon using show warning, the program elaborates that "referenced table bestellung.arbeitetin not found in the data dictionary". I am wondering, is there something wrong with the code?
Datum date not NULL,
Abholtermin DATE,
Kostenstelle int not NULL,
Abteilung char(5) not NULL,
Mitarbeiter int not NULL,
Telefon int not NULL,
primary key (Bestellnummer)
);
create table enthaelt (
FK_Bestellnummer int not NULL,
FK_Artikelnummer char(10) not NULL,
Menge int not NULL,
unique key (FK_Bestellnummer, FK_Artikelnummer)
);
alter table enthaelt ADD
constraint FK_ArtikelNr
foreign key (FK_Artikelnummer)
references Artikel (Artikelnummer);
alter table enthaelt ADD
constraint FK_BestellNr
foreign key (FK_Bestellnummer)
references Bestellung (Bestellnummer);
create table arbeitetin
(
FK_PersNr int not NULL,
FK_ProjektNr int not NULL,
unique key(FK_PersNr, FK_ProjektNr)
);
alter table arbeitetin ADD
constraint FK_ARBEITETIN_MITARBEITER1
FOREIGN KEY (FK_PersNr)
REFERENCES Mitarbeiter (PersNr);
alter table arbeitetin ADD
constraint FK_ARBEITETIN_PROJEKT
foreign key (FK_ProjektNr)
references Projekt (ProjektNr);
alter table Mitarbeiter ADD
constraint FK_MITARBEITER_ABTEILUNG
foreign key (FK_Abkuerzung)
references Abteilung (Abkuerzung); ```

Creating SQL database. with multiple primary and foreign keys

I'm currently working through an assignment that is asking me to create a SQL database using SQL Server Express. This is what it's asking for:
CREATE DATABASE USING SQL
And this is the code I have tried running;
CREATE DATABASE db_Library
Go
USE db_Library
CREATE TABLE tbl_library_branch
(
library_branch_branch_id INT PRIMARY KEY NOT NULL IDENTITY (1,1),
library_branch_branch_name VARCHAR(50) NOT NULL,
library_branch_address VARCHAR(50) NOT NULL
);
CREATE TABLE tbl_publisher
(
library_publisher_publisher_name VARCHAR(50) PRIMARY KEY NOT NULL,
library_publisher_address VARCHAR(50) NOT NULL,
library_publisher_phone INT NOT NULL
);
CREATE TABLE tbl_books
(
library_books_book_id INT PRIMARY KEY NOT NULL IDENTITY (1,1),
library_books_title VARCHAR(50) NOT NULL,
library_books_publisher_name VARCHAR(50) NOT NULL CONSTRAINT fk_library_books_publisher_name FOREIGN KEY REFERENCES tbl_publisher(library_publisher_publisher_name) ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TABLE tbl_book_authors
(
library_book_authors_book_id INT NOT NULL CONSTRAINT fk_library_book_authors_book_id FOREIGN KEY REFERENCES tbl_books(library_books_book_id) ON UPDATE CASCADE ON DELETE CASCADE,
library_book_authors_author_name VARCHAR(50) NOT NULL
);
CREATE TABLE tbl_book_copies
(
library_book_copies_book_id INT NOT NULL CONSTRAINT fk_library_book_copies_book_id FOREIGN KEY REFERENCES tbl_books(library_books_title),
library_book_copies_branch_id INT NOT NULL,
library_book_copies_number_of_copies INT NOT NULL
);
CREATE TABLE tbl_book_loans
(
library_book_loans_book_id INT NOT NULL,
library_book_loans_branch_id INT NOT NULL,
library_book_loans_card_no INT NOT NULL,
library_book_loans_date_out INT NOT NULL,
library_book_loans_date_due INT NOT NULL
);
CREATE TABLE tbl_borrower
(
library_borrower_card_no INT PRIMARY KEY NOT NULL IDENTITY (1,1),
library_borrower_name VARCHAR(50) NOT NULL,
library_borrower_address VARCHAR(50) NOT NULL,
library_borrower_phone VARCHAR(50) NOT NULL
);
Using the library "Books" as an example it looks like I need to have BoodID as a primary key and Title as a primary key, but you can't have more than one primary key per table..
Then I have to take BookID from the Book_Copies table and the Book_Loans table connect to the primary key of Title in Books?
I'm beyond stuck at this point and would appreciate any resources you think could help.
There is no need to be so verbose. I think you want something more like this (for two tables):
CREATE TABLE tbl_publisher (
publisher_id int IDENTITY(1, 1) PRIMARY KEY,
publisher_name VARCHAR(50) NOT NULL UNIQUE,
address VARCHAR(50) NOT NULL,
phone INT NOT NULL
);
CREATE TABLE books (
book_id INT IDENTITY (1,1) PRIMARY KEY,
title VARCHAR(50) NOT NULL UNIQUE,
publisher_id INT NOT NULL CONSTRAINT fk_books_publisher__id FOREIGN KEY REFERENCES tbl_publisher(publisher_id) ON UPDATE CASCADE ON DELETE CASCADE
);
Notes:
Stick with synthetic primary keys for all the tables. That is, identity columns.
Other columns can be declared to be unique. That is fine.
I type quite fast. And yet I would quickly wary of typing library_book_ over and over. Such repetition just makes it harder to write and read queries.

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 Srver foreign key error

I have this assignment for beginning sql server to add foreign keys to these tables. The last ALTER TABLE command always throws an error
There are no primary or candidate keys in the referenced table 'TCases' that match the referencing column list...
and I really can't figure out why it's giving this error. Any insight is appreciated.
CREATE TABLE TCourtRooms
( intCourtRoomID INTEGER NOT NULL
,strCourtRoomNumber VARCHAR(50) NOT NULL
,strJudgeLastName VARCHAR(50) NOT NULL
,strJudgeFirstName VARCHAR(50) NOT NULL
,CONSTRAINT TCourtDockets_PK PRIMARY KEY (intCourtRoomID)
)
CREATE TABLE TCases
( intCourtRoomID INTEGER NOT NULL
,intCaseIndex INTEGER NOT NULL
,strCaseNumber VARCHAR(50) NOT NULL
,strDescription VARCHAR(50) NOT NULL
,CONSTRAINT TCases_PK PRIMARY KEY (intCourtRoomID, intCaseIndex)
)
CREATE TABLE TPersons
( intCourtRoomID INTEGER NOT NULL
,intCaseIndex INTEGER NOT NULL
,intPersonIndex INTEGER NOT NULL
,strLastName VARCHAR(50) NOT NULL
,strFirstName VARCHAR(50) NOT NULL
,strPersonRole VARCHAR(50) NOT NULL --Options are plaintiff or defendant
,CONSTRAINT TPlaintiffs_PK PRIMARY KEY (intCourtRoomID, intCaseIndex, intPersonIndex)
)
CREATE TABLE TLawyers
( intLawyerID INTEGER NOT NULL
,intCaseIndex INTEGER NOT NULL
,intPersonIndex INTEGER NOT NULL
,strLastName VARCHAR(50) NOT NULL
,strFirstName VARCHAR(50) NOT NULL
,strLawyerRole VARCHAR(50) NOT NULL --plaintiff or defendant
,CONSTRAINT TLawyers_PK PRIMARY KEY (intLawyerID, intCaseIndex, intPersonIndex)
,CONSTRAINT TLawyers_intLawyerID_strLawyerRole_UN UNIQUE (intLawyerID, strLawyerRole)
)
Problem 3.2 Identify and create foreign keys
-- Child Parent Column(s)
-- ----- ------ ---------
-- TCases TCourtRooms intCourtRoomID
-- TPersons TCases intCourtRoomID, intCaseIndex
-- TLawyers TCourtRooms
ALTER TABLE TCases
ADD CONSTRAINT TCases_TCourtRooms_FK
FOREIGN KEY (intCourtRoomID) REFERENCES TCourtRooms (intCourtRoomID)
ALTER TABLE TPersons
ADD CONSTRAINT TPersons_TCases_FK
FOREIGN KEY (intCourtRoomID, intCaseIndex) REFERENCES TCases (intCourtRoomID, intCaseIndex)
ALTER TABLE TLawyers
ADD CONSTRAINT TLawyers_TCases_FK
FOREIGN KEY (intCaseIndex) REFERENCES TCases (intCaseIndex)</code>
This is the primary key for TCases:
CONSTRAINT TCases_PK PRIMARY KEY (intCourtRoomID, intCaseIndex)
It is a composite primary key, with two parts. You need to include both keys in the declaration:
ALTER TABLE TLawyers
ADD CONSTRAINT TLawyers_TCases_FK
FOREIGN KEY (intCaseIndex) REFERENCES TCases (intCourtRoomId, intCaseIndex)
But, alas, you cannot because the field TLawyers.intCourtRoomId does not exist. I'm not sure what you should do:
Add the field to TLawyers.
Fix the primary key definition to reference only one column.
Do something else.
But that is your problem.

SQL SMS - Error - There is already an object named "genre" in the database

I'm trying to create a hypothetical videostore database and this error message comes up everytime I execute this query:
DROP DATABASE videostore
CREATE DATABASE videostore
CREATE TABLE genre
(
genre_id INT NOT NULL PRIMARY KEY IDENTITY,
genre_name VARCHAR(15) NOT NULL
);
CREATE TABLE classification
(
rating VARCHAR(2) NOT NULL CONSTRAINT classification_pk PRIMARY KEY,
description VARCHAR(100) NOT NULL,
minimum_age INT NULL,
);
CREATE TABLE format
(
format_id INT NOT NULL CONSTRAINT format_pk PRIMARY KEY IDENTITY,
format_name VARCHAR(8) NOT NULL,
purchase_cost FLOAT NOT NULL
);
CREATE TABLE rental_cost
(
rental_cost_id INT NOT NULL CONSTRAINT rental_cost_pk PRIMARY KEY IDENTITY,
rental_name VARCHAR(15) NOT NULL,
rental_cost FLOAT NOT NULL,
rental_days TINYINT NOT NULL
);
CREATE TABLE customer
(
customer_id INT NOT NULL CONSTRAINT customer_pk PRIMARY KEY IDENTITY,
first_name VARCHAR(20) NOT NULL,
surname VARCHAR(20) NOT NULL,
dob DATETIME NOT NULL,
home_address VARCHAR(50) NOT NULL,
contact_number VARCHAR(10) NOT NULL,
referrer_id INT NULL FOREIGN KEY REFERENCES customer(customer_id),
);
CREATE TABLE movie
(
movie_id INT NOT NULL CONSTRAINT movie_pk PRIMARY KEY IDENTITY,
movie_name VARCHAR(40) NOT NULL,
year SMALLINT NOT NULL,
duration SMALLINT NULL,
descrip VARCHAR(120) NULL,
classification VARCHAR(2) NOT NULL FOREIGN KEY REFERENCES classification(rating),
rental_cost_id INT NOT NULL FOREIGN KEY REFERENCES rental_cost(rental_cost_id),
);
CREATE TABLE copy
(
copy_id INT NOT NULL CONSTRAINT copy_pk PRIMARY KEY IDENTITY,
movie_id INT NOT NULL FOREIGN KEY REFERENCES movie(movie_id),
format_id INT NOT NULL FOREIGN KEY REFERENCES format(format_id),
);
CREATE TABLE rental
(
rental_id INT NOT NULL CONSTRAINT rental_pk PRIMARY KEY IDENTITY,
copy_id INT NOT NULL FOREIGN KEY REFERENCES copy(copy_id),
customer_id INT NOT NULL FOREIGN KEY REFERENCES customer(customer_id),
rental_date DATETIME NOT NULL,
return_date DATETIME NULL
);
CREATE TABLE genre_movie
(
genre_id INT NOT NULL FOREIGN KEY REFERENCES genre(genre_id),
movie_id INT NOT NULL FOREIGN KEY REFERENCES movie(movie_id),
CONSTRAINT genre_movie_pk PRIMARY KEY (genre_id, movie_id)
);
(Sorry it's not in the correct format for reading a script with ease, I just really couldn't work out how to do that.)
Basically when I execute the SQL script it tells me that the object 'genre' already exists, but I can't see it anywhere else in my code.
And the table shouldn't already exist because I drop the database each time the script is executed right?
Sidenote - if there's a better way to make it so the database is dropped only if it exists please help me with that also.
Appreciate it.
I think you need to add USE videostore after the CREATE DATABASE videostore. Otherwise you are creating tables in whatever database you are currently in.
I think you are executing this in the context of the master database. If you check it you will probably see all your tables are actually in master.
Change the first part to this:
DROP DATABASE videostore
CREATE DATABASE videostore
USE videostore
CREATE TABLE genre
It's generally best to execute sql statements when required - try:
DROP DATABASE videostore
GO
CREATE DATABASE videostore
GO
USE videostore
CREATE TABLE genre
(
genre_id INT NOT NULL PRIMARY KEY IDENTITY,
genre_name VARCHAR(15) NOT NULL
);
GO
etc.