PostgreSQL UNIQUE constraint and REFERENCES - sql

Let's say I have a table tree and a table special_tree
CREATE TABLE tree VALUES (name VARCHAR(32) UNIQUE NOT NULL PRIMARY KEY,
type VARCHAR(32) NOT NULL);
CREATE TABLE special_tree VALUES (name NOT NULL REFERENCES tree(name),
treat_date DATE,
id INT NOT NULL PRIMARY KEY);
So I have a table containing a list of trees with unique names BUT I want to say that a tree can have multiple 'treat_date' (for various reasons).
Since tree(name) is unique I can't add 2 same name in special_tree.
Is the only solution is to remove unique from tree and then add everywhere i handle the tree table an IF statement to check if name isn't already there? (IF EXISTS (SELECT name FROM tree where tree.name = ...))

If you consider the column name of the table tree it doesn't mean that all referenced columns also should have unique values. Take a look at this example

the best solution for this is (for MySQL):
CREATE TABLE tree VALUES (
id_t int(11) NOT NULL auto_increment,
name VARCHAR(32) NOT NULL,
type VARCHAR(32) NOT NULL,
CONSTRAINT tree_pk PRIMARY KEY (id_t));
CREATE TABLE special_tree VALUES (
id_st int(11) NOT NULL auto_increment,
id_t NOT NULL REFERENCES tree(id_t),
treat_date DATE,
CONSTRAINT special_tree_pk PRIMARY KEY (id_st));
for PostgreSQL:
CREATE TABLE tree VALUES (
id_t serial primary key,
name VARCHAR(32) NOT NULL,
type VARCHAR(32) NOT NULL);
CREATE TABLE special_tree VALUES (
id_st serial primary key,
id_t NOT NULL REFERENCES tree(id_t),
treat_date DATE);

Related

Error: there is no unique constraint in the referenced table "table_name" that matches the specified keys

CREATE TABLE IF NOT EXISTS ingredients
(
i_id SERIAL PRIMARY KEY,
i_name VARCHAR(100) NOT NULL
);
CREATE TABLE IF NOT EXISTS dishes
(
d_id SERIAL PRIMARY KEY,
d_name VARCHAR(100) NOT NULL
);
CREATE TABLE IF NOT EXISTS dishes_ingredients
(
di_id SERIAL PRIMARY KEY,
di_d_id INTEGER NOT NULL REFERENCES dishes(d_id),
di_i_id INTEGER NOT NULL REFERENCES ingredients(i_id),
di_i_weight DECIMAL NOT NULL
);
I get the error:
"there is no unique constraint in the referenced table
"dishes_ingredients" that matches the specified keys".
I have searched for this problem and notice that my two foreign keys in table "dishes_ingredients" are referencing two serial primary keys from tables "ingredients" and "dishes", and thus, they are by definition unique. What I am doing wrong?
This is the create statement for the table that references the table "dishes_ingredients":
CREATE TABLE IF NOT EXISTS ratings (
r_id SERIAL PRIMARY KEY,
r_c_id INTEGER REFERENCES customers(c_id),
r_d_id INTEGER REFERENCES dishes_ingredients(di_d_id),
r_value INTEGER NOT NULL
);

Add a reference to a postgrest table

I want to alter the artist_label to be label_id BIGINT NOT NULL REFERENCES label(id) like how it is in the album_label table.
CREATE TABLE label (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
parent_label_id BIGINT REFERENCES label(id)
);
CREATE TABLE album_label (
id BIGSERIAL PRIMARY KEY,
album_id TEXT NOT NULL UNIQUE,
label_id BIGINT NOT NULL REFERENCES label(id)
);
CREATE INDEX album_label_idx ON album_label(label_id);
CREATE INDEX album_uid_idx ON album_label(id)
CREATE TABLE artist_label (
artist_id VARCHAR(60) NOT NULL,
label_id BIGINT NOT NULL,
PRIMARY KEY (artist_id, label_id)
);
CREATE INDEX artist_label_idx ON artist_label(label_id);
If you haven't created the tables yet, you could modify the creation script and add that clause.
If you're asking how to modify the table after its creation, you can use an alter table statement:
ALTER TABLE artist_label
ADD CONSTRAINT artist_label_fk FOREIGN KEY (label_id) REFERENCES label(id)
SQLFiddle Example

Design sql tables with list of foreign keys

I want to create an application for rotating pairs in a team every day. I need to store this in the database. Requirments are:
A team should be assigned to one ore more members.
Each team can have multiple tabs and different members allocate in them.(If team consist of 4 members for the particular tab only 3 should be part of it)
Each tab will have a pair of members or list of pairs per day stored.
I have ended up designing something like the example below:
create table if not exists team (
id serial not null primary key,
name text not null
);
create table if not exists member (
id serial not null primary key,
team_id integer references team(id),
nickname text
);
create table if not exists team_tab (
id bigserial not null primary key,
team_id integer references team(id) on delete cascade,
name text not null,
member_ids integer[],
);
create table if not exists team_tab_pairs (
id bigserial not null primary key,
team_tab_id integer not null references team_tab(id) on delete cascade,
tab_date date not null,
pair_ids integer[][],
);
I need an advice and suggestions how could I achieve this without having a list of references ids stored in the 2 tables below.
You need an extra table to design an M:N relationship. This is the case, for example, between "team tab" and "member". In addition to both main entities:
create table member (
id serial not null primary key,
team_id integer references team(id),
nickname text
);
create table team_tab (
id bigserial not null primary key,
team_id integer references team(id) on delete cascade,
name text not null
);
...you'll need to create a table to represent the M:N relationship, as in:
create table team_tab_member (
team_tab_id bigint not null,
member_id int not null,
primary key (team_tab_id, member_id) -- optional depending on the model
);

Can we update a record that is defined as a foreign key of a unique record define in a different table?

I am new to PostgreSQL and how i can update the records while they are related with a foreign key definition.
I am getting an error and that would be great if you can guide me with any hints
Let's say we have two different tables like below :
CREATE TABLE IF NOT EXISTS student
(
id_num VARCHAR(40) NOT NULL REFERENCES registered(student_id),
first_name VARCHAR(32) NOT NULL,
last_name VARCHAR(32) NOT NULL,
birthdate DATE NOT NULL,
PRIMARY KEY(id_num)
);
CREATE TABLE IF NOT EXISTS registered
(
student_id VARCHAR(40) NOT NULL UNIQUE,
paid_tuition BOOL NOT NULL,
PRIMARY KEY(paid_tuition)
);
Based on my understating i need to fill the registered table and then try to insert values to the student table that their id match the student_id value in registered table.
But when I try it I get the following error?
Any idea or recommendation?
Message:"update or delete on table "registered" violates foreign key
constraint "student_id_num_id_fkey" on table "student"",
Detail:"Key (id_num)=(idNum-1) is still referenced from table
"student".", Hint:"", Position:0, InternalPosition:0,
InternalQuery:"", Where:"", SchemaName:"", TableName:"student",
ColumnName:"", DataTypeName:"",
ConstraintName:"student_id_num_id_fkey", File:"ri_triggers.c",
Line:2490, Routine:"ri_ReportViolation"}
seems like you are linking tables in opposite direction , to me it makes more sense that "registered" table has been linked to student table by fk studentid .
also in your "student" table definition you are saying that column "id" is primary key while no "id" column has been declared.
so here is what I mean:
CREATE TABLE IF NOT EXISTS student
(
id_num VARCHAR(40) NOT NULL REFERENCES registered(student_id),
first_name VARCHAR(32) NOT NULL,
last_name VARCHAR(32) NOT NULL,
birthdate DATE NOT NULL,
PRIMARY KEY(id_num)
);
CREATE TABLE IF NOT EXISTS registered
(
student_id VARCHAR(40) NOT NULL REFERENCES student(id_num)
paid_tuition BOOL NOT NULL,
PRIMARY KEY(id_num)
);

SQL Server : create error how to write database name with the table name

CREATE DATABASE agom COLLATE Arabic_CI_AS
CREATE TABLE Branches
(
ID INT PRIMARY KEY NOT NULL IDENTITY,
NAME VARCHAR(255) NOT NULL
)
CREATE TABLE agom.Brands
(
ID INT PRIMARY KEY NOT NULL IDENTITY,
NAME VARCHAR(255) NOT NULL
)
CREATE TABLE agom.Work_Order
(
NUMBER INT NOT NULL,
BRANCHID INT NOT NULL,
BRANDID INT NOT NULL,
WDATE DATE NOT NULL,
REPAIRSTATUS VARCHAR(255),
REPAIRCOST VARCHAR(255),
REMARK VARCHAR(500),
PRIMARY KEY (NUMBER,BRANCHID,BRANDID)
)
CREATE TABLE agom.Profiles
(
ID INT PRIMARY KEY NOT NULL IDENTITY,
USERNAME VARCHAR(25) NOT NULL,
PASS VARCHAR(25) NOT NULL
)
ALTER TABLE agom.Work_Order
ADD CONSTRAINT branchfk
FOREIGN KEY (BRANCHID) REFERENCES Branches(ID)
ALTER TABLE agom.Work_Order
ADD CONSTRAINT brandfk
FOREIGN KEY (BRANDID) REFERENCES Brands(ID)
I get an error that cannot create table
I try to write database name with the table name db.tablename but it's not working
I need to create the database then create the tables and its constraints but I don't know where is the error.I am a sql noob
It's never Database.Table.
It's either Table, or Schema.Table, or Database.Schema.Table, or Server.Database.Schema.Table.
You probably just want to insert USE agom right after create database, and then only refer to tables by name.
Alternatively, you can refer to your tables as agom.dbo.Work_Order, dbo being the default database schema.
See Using Identifiers As Object Names for general reference.