Create a database and add tables - sql

I am new to sql so I have a problem where I am asked to create a database for a city. The database I created with DB Browser.
The database code is below. When I try to use the database to add anything to it or even see if it is created successfully I get an error:
SQL logic error near "DATABASE".
I am not sure what is wrong with the code I wrote.
CREATE DATABASE City;
CREATE TABLE IF NOT EXISTS "OfficialEmployee" (
"EID" INTEGER NOT NULL,
"FirstName" TEXT NOT NULL,
"LastName" TEXT NOT NULL,
"BirthDate" TEXT NOT NULL,
"City" TEXT NOT NULL,
"StreetName" TEXT NOT NULL,
"Number" INTEGER NOT NULL,
"Door" INTEGER NOT NULL,
"StartWorkingDate" TEXT NOT NULL,
"Degree" TEXT NOT NULL,
"DID" TEXT NOT NULL,
PRIMARY KEY("EID"),
FOREIGN KEY("DID") REFERENCES "Department"("DID") On delete cascade on update cascade
);
CREATE TABLE IF NOT EXISTS "ConstructorEmployee" (
"EID" INTEGER NOT NULL,
"FirstName" TEXT NOT NULL,
"LastName" TEXT NOT NULL,
"BirthDate" TEXT NOT NULL,
"City" TEXT NOT NULL,
"StreetName" TEXT NOT NULL,
"Number" INTEGER NOT NULL,
"Door" INTEGER NOT NULL,
"CompanyName" TEXT NOT NULL,
"SalaryPerDay" INTEGER NOT NULL,
PRIMARY KEY("EID")
);
CREATE TABLE IF NOT EXISTS "Employee_Phones" (
"EID" INTEGER NOT NULL,
"CellPhoneNumber" INTEGER NOT NULL,
PRIMARY KEY("EID","CellPhoneNumber")
);
CREATE TABLE IF NOT EXISTS "Department" (
"DID" INTEGER NOT NULL,
"Name" TEXT NOT NULL,
"Description" TEXT NOT NULL,
"ManagerID" INTEGER,
PRIMARY KEY("DID"),
FOREIGN KEY("ManagerID") REFERENCES "OfficialEmployee"("EID") On Update cascade on delete no action
);
CREATE TABLE IF NOT EXISTS "Neighborhood" (
"NID" INTEGER NOT NULL,
"Name" TEXT NOT NULL,
PRIMARY KEY("NID")
);
CREATE TABLE IF NOT EXISTS "Apartment" (
"StreetName" TEXT NOT NULL,
"Number" INTEGER NOT NULL,
"Door" INTEGER NOT NULL,
"Type" TEXT NOT NULL,
"SizeSquareMeter" INTEGER NOT NULL,
"NID" INTEGER NOT NULL,
FOREIGN KEY("NID") REFERENCES "Neighborhood"("NID") on delete no action on update no action,
PRIMARY KEY("Door","StreetName","Number")
);
CREATE TABLE IF NOT EXISTS "Project" (
"PID" INTEGER NOT NULL,
"Name" TEXT NOT NULL,
"Description" TEXT NOT NULL,
"Budget" INTEGER NOT NULL,
"NID" INTEGER NOT NULL,
PRIMARY KEY("PID"),
FOREIGN KEY("NID") REFERENCES "Neighborhood"("NID") On Update no action on delete no action
);
CREATE TABLE IF NOT EXISTS "ProjectConstructorEmployee" (
"EID" INTEGER NOT NULL,
"PID" INTEGER NOT NULL,
"StartWorkingDate" TEXT NOT NULL,
"EndWorkingDate" TEXT,
"JobDescription" TEXT NOT NULL,
FOREIGN KEY("PID") REFERENCES "Project"("PID") On Update Cascade on Delete No Action,
FOREIGN KEY("EID") REFERENCES "ConstructorEmployee"("EID") On Update Cascade On Delete No Action
);
CREATE TABLE IF NOT EXISTS "Resident" (
"RID" INTEGER NOT NULL,
"FirstName" TEXT NOT NULL,
"LastName" TEXT NOT NULL,
"BirthDate" TEXT NOT NULL,
"StreetName" TEXT NOT NULL,
"Number" INTEGER NOT NULL,
"Door" INTEGER NOT NULL,
"CatalogID" INTEGER NOT NULL,
PRIMARY KEY("RID"),
FOREIGN KEY("Door") REFERENCES "Apartment"("Door") On update cascade on delete no action,
FOREIGN KEY("StreetName") REFERENCES "Apartment"("StreetName") On Update cascade on delete no action,
FOREIGN KEY("Number") REFERENCES "Apartment"("Number") On Update cascade on delete no action
);
CREATE TABLE IF NOT EXISTS "TrashCan" (
"CatalogID" INTEGER NOT NULL,
"CreationDate" TEXT NOT NULL,
"ExpirationDate" TEXT NOT NULL CHECK(ExpirationDate>CreationDate),
PRIMARY KEY("CatalogID")
);
CREATE TABLE IF NOT EXISTS "ParkingArea" (
"AID" INTEGER NOT NULL,
"Name" TEXT NOT NULL,
"PricePerHour" INTEGER NOT NULL,
"MaxPricePerDay" INTEGER NOT NULL,
"NID" INTEGER NOT NULL,
PRIMARY KEY("AID"),
FOREIGN KEY("NID") REFERENCES "Neighborhood"("NID") On Update cascade on delete cascade
);
CREATE TABLE IF NOT EXISTS "CarParking" (
"CID" INTEGER NOT NULL,
"StartTime" TEXT NOT NULL,
"EndTime" TEXT NOT NULL CHECK(StartTime<EndTime),
"Cost" INTEGER NOT NULL CHECK(MaxPricePerDay>Cost),
"AID" INTEGER NOT NULL,
"MaxPricePerDay" INTEGER NOT NULL,
PRIMARY KEY("CID","StartTime"),
FOREIGN KEY("CID") REFERENCES "Cars"("CID") On Update Cascade on delete cascade,
FOREIGN KEY("AID") REFERENCES "ParkingArea"("AID") On Delete set null on update cascade
);

I don't believe you can create a database from within a database in SQLite
Just do this, on the command line:
UNIX: $ touch my.db
Windows: c:> type nul > my.db
Then you can open the database using DB Browser

Related

Struggling to run a query against sqlite db

I am trying to run a migration script against a sqlite database. Below is the error I am getting when attempting the migration queries:
node:internal/process/promises:288
triggerUncaughtException(err, true /* fromPromise */);
^
[Error: SQLITE_ERROR: near "categoryId": syntax error] {
errno: 1,
code: 'SQLITE_ERROR'
}
sql query I am running to create tables
CREATE TABLE IF NOT EXISTS "Category" (
id INTEGER PRIMARY KEY NOT NULL,
name VARCHAR NOT NULL );
CREATE TABLE IF NOT EXISTS "Location"(
id INTEGER PRIMARY KEY NOT NULL,
name VARCHAR NOT NULL );
CREATE TABLE IF NOT EXISTS "Job" (
id INTEGER PRIMARY KEY NOT NULL,
createdAt datetime NOT NULL default current_time,
title VARCHAR NOT NULL,
description VARCHAR NOT NULL,
locationId INTEGER NOT NULL,
FOREIGN KEY(locationId) REFERENCES Location(id),
categoryId INTEGER NOT NULL,
FOREIGN KEY(categoryId) REFERENCES Category(id) );
You need to define all columns before defining the constraints, so swap the 2nd and 3rd last lines in your script:
CREATE TABLE IF NOT EXISTS "Job" (
id INTEGER PRIMARY KEY NOT NULL,
createdAt datetime NOT NULL default current_time,
title VARCHAR NOT NULL,
description VARCHAR NOT NULL,
locationId INTEGER NOT NULL,
categoryId INTEGER NOT NULL,
FOREIGN KEY(locationId) REFERENCES Location(id),
FOREIGN KEY(categoryId) REFERENCES Category(id) );

Index with sql execution

This is my DDL for create tables:
CREATE TABLE utenti
(
login text NOT NULL,
nome text NOT NULL,
cognome text NOT NULL,
password text NOT NULL,
admin boolean DEFAULT false,
CONSTRAINT login PRIMARY KEY (login)
);
CREATE TABLE appunti
(
nomeappunto text NOT NULL,
descrizione text NOT NULL,
CONSTRAINT nomeappunto PRIMARY KEY (nomeappunto)
);
CREATE TABLE lezioni
(
nomelezione text NOT NULL,
descrizione text NOT NULL,
nomeappunto text NOT NULL,
CONSTRAINT nomelezione PRIMARY KEY (nomelezione),
CONSTRAINT nomeappunto FOREIGN KEY (appunti)
REFERENCES nomeappunto(appunti) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
CREATE TABLE corsi
(
nomecorso text NOT NULL,
descrizione text NOT NULL,
nomelezione text NOT NULL,
CONSTRAINT nomecorso PRIMARY KEY (nomecorso),
CONSTRAINT nomelezione FOREIGN KEY (nomelezione)
REFERENCES nomelezione(lezioni) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
When I execute this sql file pgadmin returns:
ERROR: "nomeappunto" is an index
********** Error **********
ERROR: "nomeappunto" is an index
SQL state: 42809
The problem is your reference nomeappunto, but that isnt a table
CONSTRAINT nomeappunto FOREIGN KEY (appunti)
REFERENCES nomeappunto(appunti) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
The sintaxis is:
ADD CONSTRAINT constrain_name
FOREIGN KEY (local_field_name)
REFERENCES foreign_table_name (foreign_field_name)
ON UPDATE CASCADE ON DELETE CASCADE;
So you probably want;
SQL DEMO
CREATE TABLE lezioni
(
nomelezione text NOT NULL,
descrizione text NOT NULL,
nomeappunto text NOT NULL,
CONSTRAINT nomelezione_pk PRIMARY KEY (nomelezione),
CONSTRAINT nomeappunto_fk FOREIGN KEY (nomeappunto)
REFERENCES appunti(nomeappunto) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
CREATE TABLE corsi
(
nomecorso text NOT NULL,
descrizione text NOT NULL,
nomelezione text NOT NULL,
CONSTRAINT nomecorso_pk PRIMARY KEY (nomecorso),
CONSTRAINT nomelezione_fk FOREIGN KEY (nomelezione)
REFERENCES lezioni(nomelezione) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
Additional I suggest you create a different name for the constrains, like:
CONSTRAINT nomeappunto_pk PRIMARY KEY (nomeappunto)
CONSTRAINT nomeappunto_fk FOREIGN KEY (appunti)

Run sql command line, issue. Creating tables

I'm trying to create a table in run sql command line of oracle database 11 xe.
My problem is when I finish typing my code:
create table vigilantes(
idVigilantes integer(3) not null,
nombre varchar(100) not null,
paterno varchar(100) not null,
materno varchar(100) not null,
id_caseta integer(3) null,
id_turno integer(3) null,
edad integer(3) not null,
id_genero integer(1) not null,
idEmpresa integer(3) not null,
constraint pk_idVigilantes PRIMARY KEY (idVigilantes)
constraint fk_id_caseta FOREIGN KEY (id_caseta)
references Caseta(id_caseta)
constraint fk_id_turno FOREIGN KEY(id_turno)
references Turno(id_turno)
constraint fk_id_genero FOREIGN KEY(id_genero)
references Generos(id_genero)
constraint fk_idEmpresa FOREIGN KEY(idEmpresa)
references Empresa(idEmpresa)
);
I get "ORA-00907: missing right parenthesis" issue.
I read that this is often caused by not defining a value.
e.g:
create table vigilantes(
idVigilantes integer not null,
.......
But still no solution here.
Any help or clue will be a lot of help.
You are missing comma after constraints. Also, integer has no precision.
create table vigilantes (
idVigilantes integer not null,
nombre varchar(100) not null,
paterno varchar(100) not null,
materno varchar(100) not null,
id_caseta integer null,
id_turno integer null,
edad integer not null,
id_genero integer not null,
idEmpresa integer not null,
constraint pk_idVigilantes primary key (idVigilantes),
constraint fk_id_caseta foreign key (id_caseta) references Caseta(id_caseta),
constraint fk_id_turno foreign key (id_turno) references Turno(id_turno),
constraint fk_id_genero foreign key (id_genero) references Generos(id_genero),
constraint fk_idEmpresa foreign key (idEmpresa) references Empresa(idEmpresa)
);
If you must define precision, use number datatype:
create table vigilantes (
idVigilantes number(3, 0) not null,
nombre varchar(100) not null,
paterno varchar(100) not null,
materno varchar(100) not null,
id_caseta number(3, 0) null,
id_turno number(3, 0) null,
edad number(3, 0) not null,
id_genero number(1, 0) not null,
idEmpresa number(3, 0) not null,
constraint pk_idVigilantes primary key (idVigilantes),
constraint fk_id_caseta foreign key (id_caseta) references Caseta(id_caseta),
constraint fk_id_turno foreign key (id_turno) references Turno(id_turno),
constraint fk_id_genero foreign key (id_genero) references Generos(id_genero),
constraint fk_idEmpresa foreign key (idEmpresa) references Empresa(idEmpresa)
);

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

InterBase: How to create view with a multible tables?

I am using SQL statement to create a view, but all the time I have problems with syntax.
The four tables I have are:
CREATE TABLE "BOOK_ORDER"
(
"ID" INTEGER NOT NULL,
"Open_Date" DATE NOT NULL,
"Close_Date" DATE,
"Student_ID" INTEGER NOT NULL,
"Book_ID" INTEGER NOT NULL,
CONSTRAINT "PK_ORDER_ID" PRIMARY KEY ("ID")
);
ALTER TABLE "BOOK_ORDER" ADD CONSTRAINT "FK_ORDER_BOOK" FOREIGN KEY ("Book_ID") REFERENCES BOOK ("ID") ON UPDATE CASCADE ON DELETE CASCADE;
ALTER TABLE "BOOK_ORDER" ADD CONSTRAINT "FK_ORDER_STUDENT" FOREIGN KEY ("Student_ID") REFERENCES STUDENTS ("STUDENT_ID") ON UPDATE CASCADE ON DELETE CASCADE;
CREATE TABLE "STUDENTS"
(
"STUDENT_ID" INTEGER NOT NULL,
"STUDENT_NAME" VARCHAR(50) NOT NULL,
"TICKET" INTEGER NOT NULL,
"GROUP_ID" INTEGER NOT NULL,
CONSTRAINT "PK_StUDENTS" PRIMARY KEY ("STUDENT_ID")
);
ALTER TABLE "STUDENTS" ADD CONSTRAINT "FK_GROUP" FOREIGN KEY ("GROUP_ID") REFERENCES GROUPS ("GROUP_ID") ON UPDATE CASCADE ON DELETE CASCADE;
CREATE TABLE "GROUPS"
(
"GROUP_ID" INTEGER NOT NULL,
"TITLE" VARCHAR(50) NOT NULL,
"CURATOR" VARCHAR(50) NOT NULL,
"CURATOR_TEL" VARCHAR(20) NOT NULL,
"FAC_ID" INTEGER NOT NULL,
CONSTRAINT "PK_GROUP" PRIMARY KEY ("GROUP_ID")
);
CREATE TABLE "BOOK"
(
"ID" INTEGER NOT NULL,
"CODE" INTEGER NOT NULL,
"Name" VARCHAR(50) NOT NULL,
"Year" DATE NOT NULL,
"Publishing_Office" VARCHAR(50) NOT NULL,
"Language" INTEGER NOT NULL,
CONSTRAINT "PK_BOOK_ID" PRIMARY KEY ("ID")
);
I need to show info about order: OpenDate, CloseDate, Student, StudentGroup, Book.
You create a view with the syntax of CREATE VIEW view_name AS SELECT statement where statement is your regular SELECT statement.
Therefore, you would do this:
CREATE VIEW view_name AS
SELECT BOOK_ORDER.id, BOOK_ORDER.OpenDate, BOOK_ORDER.CloseDate, students.student_name, groups.title, book.name
FROM book_order, students, groups, book
WHERE book_order.student_id = students.student_id AND
book_order.book_id = book.id AND
students.group_id = groups.group_id
The where clause is performing a simple join by including values repeated across tables once. I cannot guarantee this will work, but it is a good start.
Also, to get data from the view, select from it like a regular table with the view as the table name.