column deleted, now want to add constraint back - sql

I deleted a column in a table, using ALTER TABLE. I didn't realize that there was a constraint attached to it. Now the constraint also got deleted. How do I add the constraint back? I don't know the exact wording of that constraint. Also, the table was empty, so in that moment I thought the column was never going to be populated and removed it.
Here is the table CREATE query in pgadmin3:
CREATE TABLE employee_grade
(
id uuid NOT NULL DEFAULT uuid_generate_v4(),
graded_to uuid,
grade character varying(10),
graded_by uuid,
grade_date timestamp with time zone,
grade_month timestamp with time zone,
CONSTRAINT employee_grade_pkey PRIMARY KEY (id),
CONSTRAINT employee_grade_by_fk FOREIGN KEY (graded_by)
REFERENCES employee (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT employee_grade_to_fk FOREIGN KEY (graded_to)
REFERENCES employee (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
I don't know what the constraint was, but I do know that it involved the graded_by and graded_to foreign keys, and the grade_month column. It was also unique.
It probably meant that in that month, graded_by graded graded_to, and there should not be two gradings in the same month for the same two employees.
Also, if it helps, the corresponding Java entity does not have a corresponding gradeMonth column.

Turns out the answer indeed was a simple UNIQUE constraint:
CONSTRAINT grade_month_uniq UNIQUE (graded_to, graded_by, grade_month)
I used this and it works fine for the intended purpose.
Thanks #NickBarnes.

Related

Postgers: No unique or exclusion constraint matching ON CONFLICT specification when using a primary key and a UNIQUE column

Here is the schema
CREATE TABLE instagram_posts (
post_id serial PRIMARY KEY,
user_id int REFERENCES instagram_users ON DELETE RESTRICT,
link TEXT UNIQUE,
caption TEXT,
num_likes int,
num_comments int,
exsits BOOLEAN NOT NULL DEFAULT TRUE);
And I would try to call the command:
INSERT INTO instagram_posts (link,num_likes,user_id) VALUES (%s,%s,(SELECT user_id from instagram_users WHERE user_account=%s)) ON CONFLICT (post_id, link) DO UPDATE SET num_likes=EXCLUDED.num_likes,user_id=EXCLUDED.user_id;
Which gives me an Error: there is no unique or exclusion constraint matching the ON CONFLICT specification
The query works if I only include post_id as a constraint or only include the link as a constraint (ie ON CONFLICT (post_id) or ON CONFLICT(link)) but not both. I cannot think of a reason why that is. Does anyone know why?
For exactly the reason it tells you — you don't have a unique constraint on (post_id, link) to power the ON CONFLICT clause. You could create such a constraint, but that seems rather pointless when the two keys making up the composite key are already individually unique. Probably ON CONFLICT (link) is exactly what you want, but it's not completely clear what you're trying to accomplish.

The usability of Unique Constraint

I would like to ask in which cases its proper to use UNIQUE keyword in SQL. I know that if I declare a column as a primary key has uniqueness on its own but what happens with other attributes like country? Is it proper to use a unique constraint there?
The unique keyword in sql is used whenever you want each and every row entry of that column to be different from each other. A primary key column is automatically unique but there are some cases in which you may want more columns to be unique.
For example if you have a product_id as primary key it will ensure that no other row will have a product with product_id as that row. And in addition to that, you want that no two rows should have the same product_imei, then you can make the product_imei unique.
You can make a composite primary key like Primary Key(column1,column2) but that will mean that the combination you get from product_id and product_imei will be unique.
For example
(DLK-22,356938035643809) and (DLK-22, 11111111111111) both can exist in a table if (product_id,product_imei) is the primary key.
So you can use a unique constraint on as much columns as you like and its need depends on the scenario of the problem you are facing. You can use the unique constraint with the country if that helps you, there is no problem in doing so
The UNIQUE constraint ensures that all values in a column are different. Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint.
As any other constraint the UNIQUE constraint enforces some level of data quality. If you add this constraint to a column, then all values on that column will be different.
For example, on a table where EMPLOYEE_PK is already unique (because it's the PK) you may want to enforce the CARD_NUMBER column is also unique; that's the number displayed on the employee card. In your model the card number may be different from the PK, and you may also need to make sure it's unique.
Another extra benefit of a UNIQUE constraint is that other tables can link foreign keys to it. Since a UNIQUE column effectively acts as a "table key", any other table can establish a foreign key pointing to it. I've met many people who [wrongly] think that foreign keys can only point to primary keys.

Why can't I add this foreign key?

I'll post only the main part. I have two tables, each one has to have the PK of the other as a FK.
CREATE TABLE apartment
(
cod_apartment INT NOT NULL PRIMARY KEY,
cod_offer INT NOT NULL
);
CREATE TABLE offer
(
cod_offer INT NOT NULL PRIMARY KEY,
cod_apartment INT NOT NULL
);
First I inserted the values on both tables and it was working, I could even search using "select * from...". But then I tried to add the foreign key:
This worked.
ALTER TABLE offer
ADD FOREIGN KEY (cod_apartment ) REFERENCES apartment;
And this not.
ALTER TABLE apartment
ADD FOREIGN KEY (cod_offer) REFERENCES offer;
This is the error message:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__apartment__cod_offer__6383C8BA". The conflict occurred in database "kleber_apartment", table "dbo.offer", column 'cod_offer'.
The problem is, every time I try to execute, the FK name changes. And this FK actually doesn't exist. I already dropped both tables and tried to insert the values again, but the same happens.
What could be?
That means you're trying to add a foreign key when existing data doesn't obey that constraint. So you have a record in your apartment table where the cod_offer column does not match any value in the cod_apartment table.
Adding a foreign key not only constrains future data, but it requires that any existing data must also follow the rule.
And regarding the 6383C8BA, whenever you add a constraint without giving it a name, SQL Server picks one for you. Personally, I'd recommend something like:
alter table dbo.apartment
add constraint FK_apartment__cod_offer
foreign key (cod_offer) references dbo.offer (cod_offer);
This lets you define names the way you want, and is a little more clear about what you're actually building.

Oracle SQL Foreign Key constraint that ignores null or historic values

I am trying to add a constrain to a database table that I want to modify. I want to add a constraint on a column so it references a primary key of another tables. Easy enough, I just have to add a foreign key constraint. The problem is that the column already has some values that are null or something that is not part of the table I will be referencing.
My question is how do I add a constraint that references a primary key but can also accept null values (the primary key always has a value) and how to ignore the existing values so far. Is it possible? If the second part is not, I am thinking I could always write a script that updates all the nonsense values (they have a format of sort if that I can reg ex) to null so they only thing I have to figure out is how to add a foreign key constraind that also accepts null values
Firstly, there's nothing stopping you from adding a referential constraint on a column that has NULLs - foreign key constraints are only enforced for non-NULL values.
Secondly, if there are existing values that do not exist in the parent table, and you can't fix them, you do have the option in Oracle to make the constraint only validated for newly inserted or updated rows, using the NOVALIDATE option, e.g.
ALTER TABLE x ADD CONSTRAINT fk FOREIGN KEY (id) REFERENCES parent (id) NOVALIDATE;
The only downside to using the NOVALIDATE option is that the query optimizer will not rely on the FK constraint, and will execute queries with the assumption that there may be rows that do not have a matching parent row.
It would be a good idea if you are able to fix the missing values, afterwards to alter the constraint to VALIDATE.
Primary keys can not contain NULL values in all databases (proof)
To add a foreign key you should do something like:
ALTER TABLE table1
ADD CONSTRAINT fk_table1_2
FOREIGN KEY (column1)
REFERENCES table2(column2);

Adding Constraint with multiple foreign keys

I have a SQL database opened with visual studio, and I need to add some constraints to a table already created. I need a foreign key, which already has a foreign key from a third table. To explain better ,
Table ANIMALI needs a foreign key from table GABBIA, which has already a foreign key from table STANZA. This was the code I came up with:
ALTER TABLE ANIMALE ADD CONSTRAINT REF_ANIMA_GABBI_FK FOREIGN KEY (n_stanza, n_gabbia) REFERENCES GABBIA(n_stanza, n_gabbia);
This gives me an error, n_stanza is a column id not valid. I think it's about the fact that the ID for the class GABBIA is taken from joining n_gabbia and n_stanza, the latter being a key in class STANZA.
Can anyone help me out?
In order for your ALTER TABLE statement to work as written, both tables (not classes) "ANIMALE" and "GABBIA" must include the columns "n_stanza" and "n_gabbia".
In addition, in the table "GABBIA", there must be either a primary key constraint or a unique constraint on the pair of columns "n_stanza" and "n_gabbia". That is, you need something like either primary key (n_stanza, n_gabbia) or unique (n_stanza, n_gabbia) in the table "GABBIA".