Passing parameters for a constraint function - sql

I have the following table that joins driver and truck tables in order to assign trucks to drivers. I need to constraint entries that belong to the same driver on the same day, and DO NOT include the same truck code.
CREATE TABLE Assignments(
ID_CxC CHAR(3) NOT NULL PRIMARY KEY,
truck_code char(3) NOT NULL REFERENCES Trucks(truck_code),
driver_code char(5) NOT NULL REFERENCES Drivers(driver_code),
[date] DATE NOT NULL
);
INSERT Assignments
VALUES(1,1,1,'06-11-2021');
INSERT Assignments
VALUES(2,2,2,'06-11-2021');
INSERT Assignments
VALUES(3,3,3,'06-11-2021');
INSERT Assignments
VALUES(4,4,4,'06-11-2021');
INSERT Assignments
VALUES(5,5,5,'06-11-2021');
INSERT Assignments
VALUES(6,6,6,'06-11-2021');
INSERT Assignments
VALUES(7,1,1,'06-11-2021');
INSERT Assignments
VALUES(8,2,2,'06-11-2021');
INSERT Assignments
VALUES(9,3,3,'06-11-2021');
INSERT Assignments
VALUES(10,4,4,'06-11-2021');
It was suggested to create a boolean function to pass along dateval, truckval and driverval, and returns the following.
Not Exists (Select id_CxC From Assignments
Where Date = Dateval and Driver=Driverval
And Truck<>Truckval)
I have tried creating a function returning a bit datatype, but I honestly lack knowledge on user created functions, how would I go about passing the parameters for the function?
Is there an easier approach to the whole situation?

You clearly have two different entities -- but they are related. You have something like an "assignment" where a driver has a truck for one or more days. Then you have something like a "trip" where a driver uses the truck (what you are currently calling an "assignment").
So, I would model this as:
CREATE TABLE assignments (
ID_CxC CHAR(3) PRIMARY KEY,
truck_code char(3) NOT NULL REFERENCES Trucks(truck_code),
driver_code char(5) NOT NULL REFERENCES Drivers(driver_code),
date DATE NOT NULL,
UNIQUE (driver_code, date)
);
Note that there is only one row per driver and per date. Voila! Only one truck.
CREATE TABLE trips (
ID_trip INT IDENTITY(1, 1) PRIMARY KEY,
AssignmentId CHAR(3) NOT NULL REFERENCES Assignments(ID_CxC)
);
You can then add as many trips for a driver that you like, but for a given driver, they all have the same truck.

Related

How do I create a IF statement creating a table in Postgres?

I'm creating a table and I need a check constraint to validate the posibles values given a string value. I'm creating this table:
CREATE TABLE cat_accident (
acc_type VARCHAR(30) NOT NULL CHECK(acc_type = 'Home accident' OR acc_type = 'Work accident'),
acc_descrip VARCHAR(30) NOT NULL
);
So basically I want to validate if acc_type is equal to Home accident, then acc_descrip can be or 'Intoxication' OR 'burns' OR 'Kitchen wound', OR if acc_type is equal to Work Accident, then acc_descrip can be OR 'freezing' OR 'electrocution'.
How do I write that constraint?
Use a CHECK constraint with a CASE expression:
CREATE TABLE cat_accident (
acc_type VARCHAR(30) NOT NULL,
acc_descrip VARCHAR(30) NOT NULL
CHECK(
CASE acc_type
WHEN 'Home accident' THEN acc_descrip IN ('Intoxication', 'burns', 'Kitchen wound')
WHEN 'Work accident' THEN acc_descrip IN ('freezing', 'electrocution')
END
)
);
See the demo.
I'd suggest implementing this with a lookup table:
CREATE TABLE l_accident_description(
description_id VARCHAR(5) PRIMARY KEY,
description_full VARCHAR(30) NOT NULL UNIQUE,
location VARCHAR(30)
);
INSERT INTO l_accident_description
(description_id,description_full,location)
VALUES
('INTOX','Intoxication','Home Accident'),
('BURNS','Burns','Home Accident'),
('K_WND','Kitchen wound','Home Accident'),
('FREEZ','Freezing','Work Accident'),
('ELECT','Electrocution','Work Accident');
That way you can encode the relationship you want to encode into cat_accident, but if the details ever change, it's only a matter of inserting/deleting/updating rows in your lookup table. This implementation has the added benefit that you're not storing as much data repetitively in your table (just a VARCHAR(5) code rather than a VARCHAR(30) string). The table construction then becomes (with added primary key):
CREATE TABLE cat_accident (
cat_accident_id PRIMARY KEY,
acc_descrip VARCHAR(5) NOT NULL REFERENCES l_accident_description(description_id)
);
Any time you wanted to know whether the accident Home/Work, this could be accomplished with a query joining the lookup table. Joining lookup tables is more in the spirit of good database construction, rather than hard-coding checks to tables that may easily change or grow more complex as the database grows.
In fact, the ideal solution might be to create two lookup tables here, with l_accident_description in turn referencing a location lookup, but for simplicity's sake I've shown how it might be accomplished with one.

Need a constraint to conditionally avoid certain uniques

I created and filled the following table:
CREATE TABLE Assignments(
ID_CxC CHAR(3) NOT NULL PRIMARY KEY,
truck_code char(3) NOT NULL REFERENCES Trucks(truck_code),
driver_code char(5) NOT NULL REFERENCES Drivers(driver_code),
[date] DATE NOT NULL
);
INSERT Assignments
VALUES(1,1,1,'06-11-2021');
INSERT Assignments
VALUES(2,2,2,'06-11-2021');
INSERT Assignments
VALUES(3,3,3,'06-11-2021');
INSERT Assignments
VALUES(4,4,4,'06-11-2021');
INSERT Assignments
VALUES(5,5,5,'06-11-2021');
INSERT Assignments
VALUES(6,6,6,'06-11-2021');
INSERT Assignments
VALUES(7,1,1,'06-11-2021');
INSERT Assignments
VALUES(8,2,2,'06-11-2021');
INSERT Assignments
VALUES(9,3,3,'06-11-2021');
INSERT Assignments
VALUES(10,4,4,'06-11-2021');
I need to create a constraint that will only allow a driver to have more than one truck assigned on a single day if it is the same truck as previously assigned that same day.
I was attempting to write a CHECK constraint where in case UNIQUE(driver_code,date) is broken, the statement would only allow an insert or update if it verifies that UNIQUE(driver_code,truck_code,date) is also false.
Write a boolean function that passes in Dateval, Truckval, & Driverval and returns the value of
Not Exists (Select id_CxC From Assignments
Where Date = Dateval and Driver=Driverval
And Truck<>Truckval)
Set up a table check constraint that calls this function, prefaced with the schema name.

How do I check the value of a foreign key on insert?

I'm teaching myself SQL using Sqlite3, well suited for my forever-game project (Don't we all have one?) and have the following tables:
CREATE TABLE equipment_types (
row_id INTEGER PRIMARY KEY,
type TEXT NOT NULL UNIQUE);
INSERT INTO equipment_types (type) VALUES ('gear'), ('weapon');
CREATE TABLE equipment_names (
row_id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE);
INSERT INTO equipment_names (name) VALUES ('club'), ('band aids');
CREATE TABLE equipment (
row_id INTEGER PRIMARY KEY,
name INTEGER NOT NULL UNIQUE REFERENCES equipment_names,
type INTEGER NOT NULL REFERENCES equipment_types);
INSERT INTO equipment (name, type) VALUES (1, 2), (2, 1);
So now we have a 'club' that is a 'weapon', and 'band aids' that are 'gear'. I now want to make a weapons table; it will have an equipment_id that references the equipment table and weapon properties like damage and range, etc. I want to constrain it to equipment that is a 'weapon' type.
But for the life of me I can't figure it out. CHECK, apparently, only allows expressions, not subqueries, and I've been trying to craft a TRIGGER that might do the job, but in short, I can't quite figure out the query and syntax, or how to check the result that as I understand it will be in the form of a table, or null.
Also, are there good online resources for learning SQL more advanced than W3School? Add them as a comment, please.
Just write a query that looks up the type belonging to the new record:
CREATE TRIGGER only_weapons
BEFORE INSERT ON weapons
FOR EACH ROW
WHEN (SELECT et.type
FROM euqipment_types AS et
JOIN equipment AS e ON e.type = et.equipment_type_id
WHERE e.row_id = NEW.equipment_id
) != 'weapon'
BEGIN
SELECT RAISE(FAIL, "not a weapon");
END;
The foreign key references should be to the primary key and to the same time. I would phrase this as:
CREATE TABLE equipment_types (
equipment_type_id INTEGER PRIMARY KEY,
type TEXT NOT NULL UNIQUE
);
INSERT INTO equipment_types (type) VALUES ('gear'), ('weapon');
CREATE TABLE equipment_names (
equipment_name_id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE
);
INSERT INTO equipment_names (name) VALUES ('club'), ('band aids');
CREATE TABLE equipment (
equipment_id INTEGER PRIMARY KEY,
equipment_name_id INTEGER NOT NULL UNIQUE REFERENCES equipment_names(equipment_name_id),
equipement_type_id INTEGER NOT NULL REFERENCES equipment_types(equipement_type_id)
);
I would not use the name row_id for the primary key. That is the built-inn default, so the name is not very good. In SQLite, an integer primary key is automatically auto-incremented (see here).

Check that a value is lower than a value in another table postgresql

CREATE TABLE Time(
Tipo VARCHAR(15) PRIMARY KEY,
DataInizio DATE,
DataFine DATE NOT NULL);
INSERT INTO Time VALUES('PreIscrizione', '2017-02-01', '2017-04-30');
INSERT INTO Time VALUES('Candidatura', '2017-05-01', '2017-07-30');
CREATE TABLE PreIscrizione(
Studente VARCHAR(16) REFERENCES Persona ON DELETE CASCADE ON UPDATE CASCADE PRIMARY KEY,
DataPreIscrizione DATE CHECK(DataPreIscrizione<(SELECT DataFine FROM Time WHERE Tipo = 'PreIscrizione')));
The table PreIscrizione allows to sign up a student, but it has to be done before a date indicated in the table Time. Obviously what i wrote above doesn't work, but it explains my idea. Which is the right way to solve this?

How can I insert into tables with relations?

I have only done databases without relations, but now I need to do something more serious and correct.
Here is my database design:
Kunde = Customer
Vare = Product
Ordre = Order (Read: I want to make an order)
VareGruppe = ehm..type? (Read: Car, chair, closet etc.)
VareOrdre = Product_Orders
Here is my SQL (SQLite) schema:
CREATE TABLE Post (
Postnr INTEGER NOT NULL PRIMARY KEY,
Bynavn VARCHAR(50) NOT NULL
);
CREATE TABLE Kunde (
CPR INTEGER NOT NULL PRIMARY KEY,
Navn VARCHAR(50) NOT NULL,
Tlf INTEGER NOT NULL,
Adresse VARCHAR(50) NOT NULL,
Postnr INTEGER NOT NULL
CONSTRAINT fk_postnr_post REFERENCES Post(Postnr)
);
CREATE TABLE Varegruppe (
VGnr INTEGER PRIMARY KEY,
Typenavn VARCHAR(50) NOT NULL
);
CREATE TABLE Vare (
Vnr INTEGER PRIMARY KEY,
Navn VARCHAR(50) NOT NULL,
Pris DEC NOT NULL,
Beholdning INTEGER NOT NULL,
VGnr INTEGER NOT NULL
CONSTRAINT fk_varegruppevgnr_vgnr REFERENCES Varegruppe(VGnr)
);
CREATE TABLE Ordre (
Onr INTEGER PRIMARY KEY,
CPR INTEGER NOT NULL
CONSTRAINT fk_kundecpr_cpr REFERENCES Kunde(CPR),
Dato DATETIME NOT NULL,
SamletPris DEC NOT NULL
);
CREATE TABLE VareOrdre (
VareOrdreID INTEGER PRIMARY KEY,
Onr INTEGER NOT NULL
CONSTRAINT fk_ordrenr_onr REFERENCES Ordre(Onr),
Vnr INTEGER NOT NULL
CONSTRAINT fk_varevnr_vnr REFERENCES Vare(Vnr),
Antal INTEGER NOT NULL
);
It should work correctly.
But I am confused about Product_Orders.
How do I create an order? For example, 2 products using SQL INSERT INTO?
I can get nothing to work.
So far:
Only when I manually insert products and data into Product_Orders and then add that data to Orders = which makes it complete. Or the other way around (create an order in with 1 SQL, then manually inserting products into Product_orders - 1 SQL for each entry)
You should first create an order and then insert products in the table Product_Orders. This is necessary because you need an actual order with an id to associate it with the table Product_Orders.
You always should create a record in the foreign-key table before being able to create one in your current table. That way you should create a "Post", customer, type, product, order and product_order.
Try this ...
first you have to insert a customer
insert into kunde values(1, 'navn', 1, 'adresse', 1)
then you insert a type
insert into VareGruppe values(1, 'Type1')
then you insert a product
insert into vare values(1, 'product1', '10.0', 1, 1)
then you add an order
insert into ordre values(1, 1, '20090101', '10.0')
then you insert a register to the product_orders table
insert into VareOrdre values (1, 1, 1, 1)
I think this is it. :-)
As the primary keys are autoincrement, don't add them to the insert and specify the columns like this
insert into vare(Nav, Pris, Beholdning, VGnr) values('product1', '10.0', 1, 1)
Use Select ##identity to see the onr value
I think you already have the hang of what needs to happen. But what I think you are getting at is how to ensure data integrity.
This is where Transactions become important.
http://www.sqlteam.com/article/introduction-to-transactions
Is it the SalesPrice (I'm guessing that's what SamletPris means) that's causing the issue? I can see that being a problem here. One common design solution is to have 2 tables: Order and OrderLine. The Order is a header table - it will have the foreign key relationship to the Customer table, and any other 'top level' data. The OrderLine table has FK relationships to the Order table and to the Product table, along with quantity, unit price, etc. that are unique to an order's line item. Now, to get the sales price for an order, you sum the (unit price * quantity) of the OrderLine table for that order. Storing the SalesPrice for a whole order is likely to cause big issues down the line.
A note just in case this is MySQL: If you're using MyISAM, the MySQL server ignores the foreign keys completely. You have to set the engine to InnoDB if you want any kind of integrity actually enforced on the database end instead of just in your logic. This isn't your question but it is something to be aware of.
fbinder got the question right :)