I have a query which contains mistakes. where are they? - sql

I want to create a table in SQlite but can't:
CREATE TABLE IF NOT EXISTS[Goods]
(GoodId INTEGER PRIMARY KEY AUTOINCREMENT,
GoodName varchar(100) not null,
CategoryId INTEGER FOREIGN KEY (CategoryId) REFERENCES Category (CategoryId),
ProducerId INTEGER FOREIGN KEY (ProducerId) REFERENCES Producer (ProducerId),
Price REAL not null,
GoodCount REAL not null)
here are additional tables but they are all right. I don't have problems with them:
CREATE TABLE IF NOT EXISTS[Category] (CategoryId INTEGER PRIMARY KEY
AUTOINCREMENT, CategoryName varchar(100) not null)
CREATE TABLE IF NOT EXISTS[Producer] (ProducerId INTEGER PRIMARY KEY
AUTOINCREMENT, ProducerName varchar(100) not null)

Inline foreign keys do not take the FOREIGN KEY keyword.
Consider:
CREATE TABLE IF NOT EXISTS[Goods] (
GoodId INTEGER PRIMARY KEY AUTOINCREMENT,
GoodName varchar(100) not null,
CategoryId INTEGER REFERENCES Category (CategoryId),
ProducerId INTEGER REFERENCES Producer (ProducerId),
Price REAL not null,
GoodCount REAL not null
)

Related

How to reference to primary key?

create database [PostaShpejte]
use PostaShpejte
create table Posta
(
ID_Posta int not null Primary Key,
Emri varchar(50)not null,
Qyteti varchar(15) not null,
)
create table Dergesa
(
ID_Dergesa int IDENTITY(1,1) not null Primary Key,
Emri_Dergeses varchar(30) not null,
Pershkrimi varchar(100),
Qmimi int not null,
Statusi varchar(30) not null,
CONSTRAINT CHK_Statusi CHECK (Statusi='E regjistruar' or Statusi='E nisur' or Statusi='Ne depo' or Statusi='E refuzuar' or Statusi='E derguar'),
)
create table Menaxhon
(
ID_Dergesa int not null references Dergesa (ID_Dergesa),
ID_Posta int not null references Posta(ID_Posta),
Primary Key(ID_Dergesa,ID_Posta),
)
--drop table TelBleresi
create table TelBleresi
(
ID_Tel_Bleresi int not null,
--ID_Bleresi int not null,
NumriTel int not null Unique,
Primary Key(ID_Tel_Bleresi),
)
--drop table Bleresi
create table Bleresi
(
ID_Bleresi int not null,
ID_Tel_Bleresi int not null,
Emri varchar(20) not null,
Mbiemri varchar(20) not null,
Shteti varchar(20) not null,
Qyteti varchar(20) not null,
Rruga varchar(50) not null,
ZIPKodi int not null,
FOREIGN KEY(ID_Tel_Bleresi) references TelBleresi(ID_Tel_Bleresi),
Primary Key (ID_Bleresi , ID_Tel_Bleresi),
)
create table Dergohet
(
ID_Dergesa int not null,
ID_Bleresi int not null,
Data_e_regj date not null,
Data_e_mbrritjes date not null,
----------------PROBLEM HERE---------------------------
FOREIGN KEY (ID_Dergesa) references Dergesa(ID_Dergesa),
FOREIGN KEY (ID_Bleresi) references **Bleresi**(ID_Bleresi),
*Error: There are no primary or candidate key to table Bleresi ....*
---------------------------------------------------------
PRIMARY KEY (ID_Dergesa,ID_Bleresi),
)
Bleresi has a compound primary key (ID_Bleresi, ID_Tel_Bleresi), so you need to reference all columns. That means adding ID_Tel_Bleresi to Dergohet.
create table Dergohet(
ID_Dergesa int not null,
ID_Bleresi int not null,
ID_Tel_Bleresi int not null, -- add this column
Data_e_regj date not null,
Data_e_mbrritjes date not null,
FOREIGN KEY (ID_Dergesa) references Dergesa(ID_Dergesa),
-- Reference the full compound key
FOREIGN KEY (ID_Bleresi, ID_Tel_Bleresi) references Bleresi(ID_Bleresi, ID_Tel_Bleresi),
PRIMARY KEY (ID_Dergesa,ID_Bleresi),
)
While they have some uses, compound primary keys are annoying as they create a proliferation of foreign key columns and complicate indexing. Some of yours seem unnecessary: Bleresi already has a ID_Bleresi, is that not unique?
In general, I'd recommend using simple big integer (2 billion creeps up on you surprisingly fast) auto incrementing primary keys. If you need to guarantee other uniquenesses, make a unique index.
The error say that ID_Bleresi is not the primary key on Bleresi table and for that can't be a foreign key. The primary key is:
Primary Key (ID_Bleresi , ID_Tel_Bleresi)
If ID_Bleresi is not a unique column, I recommend that in the table, you create a new unique column that is the primary key. In case it is, it would be best to set ID_Bleresi as the unique primary key

Table 'tableName' contains a constraint definition with column 'columnName' which is not in the table Java Derby

I am trying to run a SQL script to my database created on Java Derby:
CREATE TABLE USUARIO (
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY,
EMAIL VARCHAR(40) NOT NULL UNIQUE,
NOMBRES VARCHAR(20) NOT NULL,
APELLIDOS VARCHAR(20) NOT NULL,
CONTRASEÑA VARCHAR(20) NOT NULL,
CEDULA INTEGER,
TELEFONO INTEGER,
CONSTRAINT ID_USUARIO_PK PRIMARY KEY (ID) -- Primary Key
);
CREATE TABLE ORGANIZACION (
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY, -- Id autonumérico
NOMBRE VARCHAR(20) NOT NULL,
CONSTRAINT ID_ORGANIZACION_PK PRIMARY KEY (ID),
CONSTRAINT ID_DIRECCION_ORG_FK FOREIGN KEY (DIRECCION_ORG) REFERENCES DIRECCION_ORG (ID),
CONSTRAINT ID_TELEFONO_ORG_FK FOREIGN KEY (TELEFONO_ORG) REFERENCES TELEFONO_ORG (ID)
);
CREATE TABLE TELEFONO_ORG (
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY, -- Id autonumérico
TELEFONO INTEGER NOT NULL,
CONSTRAINT ID_TELEFONO_ORG_PK PRIMARY KEY (ID)
);
CREATE TABLE DIRECCION_ORG (
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY, -- Id autonumérico
DIRECCION VARCHAR(300) NOT NULL,
CONSTRAINT ID_DIRECCION_ORG_PK PRIMARY KEY (ID)
);
CREATE TABLE PRODUCTO (
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY,
RUTA_IMAGEN VARCHAR(400) NOT NULL,
NOMBRE VARCHAR(20) NOT NULL,
CANTIDAD INTEGER,
PRECIO INTEGER,
COSTO INTEGER,
CONSTRAINT ID_PRODUCTO_PK PRIMARY KEY (ID), -- Primary Key
CONSTRAINT ID_ORGANIZACION_FK FOREIGN KEY (ORGANIZACION) REFERENCES ORGANIZACION (ID)
);
But I am getting this error:
Table ORGANIZACION contains a constraint definition with column
DIRECCION_ORG which is not in the table.
What can be wrong here?
You are making constraints to foreign keys but haven't actually created the columns to contain those keys yet. Make those columns and make the constraints point to them (instead of just using the table's name again). Shown below with -- comments indicating where to add it.
CREATE TABLE USUARIO (
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY,
EMAIL VARCHAR(40) NOT NULL UNIQUE,
NOMBRES VARCHAR(20) NOT NULL,
APELLIDOS VARCHAR(20) NOT NULL,
CONTRASEÑA VARCHAR(20) NOT NULL,
CEDULA INTEGER,
TELEFONO INTEGER,
CONSTRAINT ID_USUARIO_PK PRIMARY KEY (ID) -- Primary Key
);
CREATE TABLE ORGANIZACION (
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY, -- Id autonumérico
NOMBRE VARCHAR(20) NOT NULL,
DIRECCION_ORG_ID INTEGER NOT NULL, -- ADD THIS and change constraint FK name
TELEFONO_ORG_ID INTEGER NOT NULL, -- ADD THIS and change constraint FK name
CONSTRAINT ID_ORGANIZACION_PK PRIMARY KEY (ID),
CONSTRAINT ID_DIRECCION_ORG_FK FOREIGN KEY (DIRECCION_ORG_ID) REFERENCES DIRECCION_ORG (ID),
CONSTRAINT ID_TELEFONO_ORG_FK FOREIGN KEY (TELEFONO_ORG_ID) REFERENCES TELEFONO_ORG (ID)
);
CREATE TABLE TELEFONO_ORG (
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY, -- Id autonumérico
TELEFONO INTEGER NOT NULL,
CONSTRAINT ID_TELEFONO_ORG_PK PRIMARY KEY (ID)
);
CREATE TABLE DIRECCION_ORG (
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY, -- Id autonumérico
DIRECCION VARCHAR(300) NOT NULL,
CONSTRAINT ID_DIRECCION_ORG_PK PRIMARY KEY (ID)
);
CREATE TABLE PRODUCTO (
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY,
RUTA_IMAGEN VARCHAR(400) NOT NULL,
NOMBRE VARCHAR(20) NOT NULL,
CANTIDAD INTEGER,
PRECIO INTEGER,
COSTO INTEGER,
ORGANIZACION_ID INTEGER NOT NULL, --ADD THIS and change constraint FK name
CONSTRAINT ID_PRODUCTO_PK PRIMARY KEY (ID), -- Primary Key
CONSTRAINT ID_ORGANIZACION_FK FOREIGN KEY (ORGANIZACION_ID) REFERENCES ORGANIZACION (ID)
);
Both the columns DIRECCION_ORG and TELEFONO_ORG are not defined in the table ORGANIZACION
The same problem occurs in the table PRODUCTO where the column ORGANIZACION is not defined
You have an error in your CONSTRAINT clause.
The format of the FOREIGN KEY constraint is:
CONSTRAINT {constraint name} FOREIGN KEY ([This_table_column],...) REFERENCES [Other_table] ([Other_table_column], ...).
Read this: https://db.apache.org/derby/docs/10.1/ref/rrefsqlj13590.html#rrefsqlj13590

Composite primary key for 1-to-many relationship?

Well, I was always doing it like this:
create table language (
id bigserial primary key,
code varchar(10) not null
);
create table entity (
id bigserial primary key
);
create table entity_description (
id bigserial primary key,
language_id bigint not null,
constraint fk__entity_description__language
foreign key language_id
references language(id),
entity_id bigint not null,
constraint fk__entity_description__entity
foreign key entity_id
references entity(id),
name varchar(20) not null
);
but I wonder.. why wouldn't I do it like this:
create table language (
id bigserial primary key,
code varchar(10) not null
);
create table entity (
id bigserial primary key
);
create table entity_description (
language_id bigint not null,
constraint fk__entity_description__language
foreign key language_id
references language(id),
entity_id bigint not null,
constraint fk__entity_description__entity
foreign key entity_id
references entity(id),
primary key (language_id, entity_id),
name varchar(20) not null
);
My questions are
Is there anything that speaks against the composite primary key in the second example?
Are there any benefits?
Are, in the second example, (language_id, entity_id), language_id and entity_id indexed separately for table entity_description? If I fetch for .. WHERE entity_description.id = x is this slower than fetching for .. WHERE (entity_description.language_id, entity_description.entity_id) = (x,y)?

SQL: create table with composite referencing primary key, and foreign key

So I have the following ER diagram:
So Subthing is a generalization. Stuff is either made out of Metal or Wood, it can't be just a Subthing. Here's the create code:
CREATE TABLE Thing (
ThingID INTEGER PRIMARY KEY NOT NULL
);
CREATE TABLE Subthing (
consists_of INTEGER REFERENCES Thing(ThingID),
SubthingID INTEGER NOT NULL,
PRIMARY KEY (SubthingID, consists_of)
);
CREATE TABLE Wood (
Wstuff VARCHAR(40) NOT NULL,
consists_of INTEGER NOT NULL,
SubthingID INTEGER NOT NULL,
FOREIGN KEY (SubthingID, consists_of) REFERENCES Subthing(SubthingID, consists_of),
PRIMARY KEY (SubthingID, consists_of)
);
CREATE TABLE Dust (
DustID INTEGER PRIMARY KEY NOT NULL
);
CREATE TABLE Metal (
Mstuff VARCHAR(40) NOT NULL,
consists_of INTEGER NOT NULL,
SubthingID INTEGER NOT NULL,
requires INTEGER NOT NULL REFERENCES Dust(DustID),
FOREIGN KEY (SubthingID, consists_of) REFERENCES Subthing(SubthingID, consists_of),
PRIMARY KEY (SubthingID, consists_of)
);
What I want is for Metal to, at the same time, have a primary key which references (SubthingID, consists_of) and a foreign key with requires, referencing DustID. I can't declare it as a foreign key after the fact since (SubthingID, consists_of) is already a foreign key.
How could you solve this, other than making requires into a table?
Never mind, I was too stupid.
CREATE TABLE Metal (
Mstuff VARCHAR(40) NOT NULL,
consists_of INTEGER NOT NULL,
SubthingID INTEGER NOT NULL,
requires INTEGER NOT NULL,
FOREIGN KEY (requires) REFERENCES Dust(DustID),
FOREIGN KEY (SubthingID, consists_of) REFERENCES Subthing(SubthingID, consists_of),
PRIMARY KEY (SubthingID, consists_of)
);
Works just fine.

Which of these is the right way to do foreign keys?

So, i'm trying sqlite3 and i have a question about Foreign Keys and Indices.
Which of these methods is the right one ?
CREATE TABLE artist(
artistid INTEGER PRIMARY KEY,
artistname TEXT
);
CREATE TABLE track(
trackid INTEGER,
trackname TEXT,
trackartist INTEGER REFERENCES artist
);
CREATE INDEX trackindex ON track(trackartist);
OR this one:
CREATE TABLE student(
SudentID INTEGER PRIMARY KEY,
First TEXT,
Last,
Contact Text,
Year INTEGER)
CREATE TABLE loan(
StudentID INTEGER,
ISBN INTEGER,
out INTEGER,
FOREIGN KEY(SudentID)
REFERENCES student(SudentID)
ON DELETE CASCADE
PRIMARY KEY(StudentID, ISBN)
)
CREATE INDEX StudentID_Index ON student(StudentID)
As long as it works, it's a style choice. IMHO coding the REFERENCES in-line on the column is better because it makes it more clear:
CREATE TABLE users (
id INTEGER PRIMARY KEY NOT NULL,
username TEXT NOT NULL,
pwhash TEXT NOT NULL,
email TEXT,
created INTEGER NOT NULL
);
CREATE TABLE posts (
id INTEGER PRIMARY KEY NOT NULL,
title TEXT NOT NULL,
description TEXT NOT NULL,
content TEXT NOT NULL,
id_user INTEGER NOT NULL REFERENCES users ON DELETE CASCADE
);
CREATE INDEX posts_id_user ON posts(id_user);
Also. no need to code the primary key column of the foreign table - referencing just the table is enough (the primary key is assumed).
See SQLFiddle.
I think i found a solution.
I'm doing this:
CREATE TABLE users(
id INTEGER PRIMARY KEY NOT NULL, /* No need for 'autoincrement' keyword */
username TEXT NOT NULL,
pwhash TEXT NOT NULL,
email TEXT,
created INTEGER NOT NULL
);
CREATE TABLE posts (
id INTEGER PRIMARY KEY NOT NULL,
title TEXT NOT NULL,
description TEXT NOT NULL,
content TEXT NOT NULL,
id_user INTEGER NOT NULL,
FOREIGN KEY (id_user)
REFERENCES users(id)
ON DELETE CASCADE
);
CREATE INDEX users_posts ON posts(id_user);