Query which will delete other table reference as well as from main table - rdbms

I have a requirement of deleting records from the Postgres database tables.
We have a Customer table which is the main table, this table contains a primary key which is used in so many other tables as a FOREIGN KEY, I want to delete one of the customers as well as its reference used in other tables. Is there any way to delete the customer from main table as well as from other tables which contains foreign key.
Thanks in Advance.

In the other tables, you want a cascading delete foreign key reference. You can create one in the database using:
alter table othertable add constraint fk_othertable_customerid
foreign key (customerid) references customers(customerid)
on delete cascade;
Note: This assumes that customerid is the name of the column in both tables and that it is already defined in the other tables.
A cascading foreign key constraint does exactly what you specify. When a row is deleted in the reference table, then all related rows are deleted.
If you already have foreign key constraints on customerid, then drop the existing constraint and add the cascading version.

Related

How to alter a foreign key in postgresql

I created a table in PostgreSQL with a foreign key constraint.
I dropped the table to which the foreign key belongs. Now how to alter the table or how to defer the foreign key present in the table?
To clarify:
I have a table named test. It has a column called subjectName, which is a foreign key of subject Table. Now I dropped subject table. How to remove the FK constaint on table test
Assuming the following tables:
create table subject
(
name varchar(10) primary key
);
create table test
(
some_column integer,
subject_name varchar(10) not null references subject
);
there are two scenarios what could have happened when you dropped the table subject:
1. you didn't actually drop it:
drop table subject;
ERROR: cannot drop table subject because other objects depend on it
Detail: constraint test_subject_name_fkey on table test depends on table subject
Hint: Use DROP ... CASCADE to drop the dependent objects too.
2. you did drop it, then the foreign key is gone as well.
drop table subject cascade;
NOTICE: drop cascades to constraint test_subject_name_fkey on table test
which tells you that the foreign key constraint was automatically dropped.
Perhaps your question in not exactly what you mean. Are you wanting to remove the which was a foreign key from the table. As amply indicated if you dropped the parent table then the FK is also dropped. However the column itself is not dropped from the child table. To remove that you need to alter the table.
alter table test drop column subject_name;
See demo here

Create relationship for association table

Normally when creating constraint between two tables i used to use following script:
ALTER TABLE userVendor
ADD CONSTRAINT myrelation
FOREIGN KEY (DataSource, userId)
REFERENCES user(DataSource, userId)
so userVendor table references user table
Now let's say userVendor becomes association table between two tables. Therefore we have additionally third table called Vendor which has datasource and vendor id as composite key. All of them by the way having composite keys.
How to modify my script to say like (wrong script so far):
ALTER TABLE userVendor
ADD CONSTRAINT myrelation
FOREIGN KEY (DataSource, userId, vendorid)
REFERENCES user(DataSource, userId)
REFERENCES user(DataSource, vendorid)
You'll have to add two foreign key constraints, each referencing one table. It is no problem if a column appears in both constraints.
You will need two ADD CONSTRAINT clauses in your ALTER TABLE statement.

How would you create a unique index on a foreign table?

Database 1 has foreign tables a and b on database 2.
How can we create indexes on these foreign tables a and b. These foreign tables are wrappers over database2.c and database2.d tables respectively, which do have the necessary indexes in place.
How would you create indexes on foreign tables a and b? Is that even possible?
I get a cannot create index on foreign table a - when I try a simple Create Index command in postgres
You cannot create index on a foreign table, instead write a trigger on foreign table and create a local table in postgres such that whenever an insert, update or delete is happening in your foreign table it will be reflected in your local table and index it.
Joining with a foreign table can result to slow query's.
Since indexes are not a option with foreign table, consider making a materialized view on a foreign table . Materialized views do allow indexing
CREATE FOREIGN TABLE members_fdw(...)
CREATE MATERIALIZED VIEW members AS
select * from members_fdw
WITH DATA
CREATE UNIQUE INDEX "member_id" ON members USING btree ("id");

Altering table for adding foreign key constraint take very long time

I have one table manual_errors_archive. I need to add foreign key to this table keeping reference to values table, values table having 800,000 records and manual_errors_archive table does not have any records.
ALTER TABLE manual_errors_archive
ADD CONSTRAINT fk_manua_reference_value
FOREIGN KEY (value_id)
REFERENCES values;
Postgres version i am using 9.1
But this is running for more than 1 hr after that I canceled the process. Any idea how to optimize this process?

Problem adding foreign key in simple setup

I have two tables
Users
Users_Role
I decided to try to add a foreign key as to my understanding it will let me cascade the delete procedure when removing a user from Users (as well as enforce integrity).
So via Management Studio I right clicked my Users_Role table, Design, then went into Relationships. I added a new relationship between the two tables as such:
Foreign Key Base Table: Users_Role
Foreign Key Columns: UserID
Primary/Unique Key Base: Users
Primary/Unique Key columns: ID
When I then try to save, I get the following error:
'Users' table saved successfully
'Users_Role' table
- Unable to create relationship 'FK_Users_Role_Users'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Users_Role_Users". The conflict occurred in database "db", table "dbo.Users", column 'ID'.
I'm not sure what's going on. Adds the relationship to Users, but not Users_Role? The only thing special about Users_Role is that my primary key consists of two columns, UserID and Role (the only two columns in the table, if that matters). Otherwise, nothing special.
This error means that in your current database, you have entries in the "Users_Role" table which have a "UserID" value that is not present in the Users table as ID.
You first need to find those "rogue" rows and either update or delete them, before you can create the foreign key to enforce referential integrity and avoid such problems in the future.
You can find those by issuing this command:
SELECT * FROM Users_Role
WHERE UserID NOT IN
(SELECT DISTINCT ID FROM Users)