POSTGRESQL- Make foreign key column point to another table - database

I'm using psql and I want to change one of the columns of my table.
At the moment this column is a foreign key of Table 2 but I would like to make it point to Table 3.
Is this possible or should I delete the column and add a new one?

There's no need to add & remove the column. You can remove/disable the constraint to one table and add it for the other table.
The command for doing the former is:
alter table Table1 drop constraint if exists name_of_constraint_on_Table_1_column
The command for doing the latter is:
alter table Table1
add constraint name_of_constraint_on_Table_1_column
foreign key (column) references Table3 (other_column) match full
You need to find the name of the foreign key constraint if you haven't named it explicitly. You can do so via the \d command:
\d Table1
You should read about alter table cause there's a lot of things you can do to change the table.

Related

How to alter type of a column who is references as Foreign key in other table?

I want to change the dataType of primary key from varchar to bigint.
I tried following command.
ALTER TABLE dbo.Company
ALTER COLUMN Id bigint
but it is not working as this column is referenced as the foreign key in other tables.
How can i change its type without loosing data of the table through Sql Query?
There are several steps to accomplish this. But the main thing, is that first you'll have to drop the key.
First drop the primary (change name_of_primary_key, with yours real):
ALTER TABLE dbo.Company DROP CONSTRAINT name_of_primary_key;
Change the data type (replace length with your desired):
alter table table alter column foreign_key_column bigint(length)
Then drop the foreign key from other tables (make this for every table, and replace the two arguments, with your real from the db):
ALTER TABLE table DROP FOREIGN KEY foreign_key_column;
Now, you change the data type of the foreign key column(replace length with your desired):
alter table table alter column foreign_key_column bigint(length);

Drop column with PK constraint in empty table in a script

Scenario
A table in SQL Server has two or more columns, but the original column with the primary key constraint is no longer needed. So now you want to write a script to drop the original column w/ a PK constraint and put the PK constraint on a different column.
In this example, the table is empty.
Problem
You can't drop the first column without first dropping the PK constraint.
And you can't drop the PK constraint in SQL Server without the exact name of it. (more info here)
....But you don't know the automatically generated name of the PK constraint.
NOTE: If the table is not empty, see this solution:
SQL Server 2008 Script to Drop PK Constraint that has a System Generated Name
(In most cases, this is the best solution.)
Question
The above solution will work, but what is another way to script dropping a column with a PK constraint when you don't know the constraint's name in an empty table?
Another strategy -- besides figuring out the system generated name of the PK constraint so you can drop it as described here -- is to drop the empty table and recreate it without the original column with the primary key constraint, instead putting it on the new column.
To drop the column with an unknown PK constraint name:
Generate a script to drop the table and re-create it from scratch
Remove the OriginalColumn column from the CREATE TABLE query
Put the PK constraint on the NewColumn column in the script
Run the script to drop and re-create it without the original column -- effectively dropping OriginalColumn and "moving" the PK constraint from OriginalColumn to NewColumn
???
Profit!

How do I set default value for a foreign key column in sql server?

I am adding a new column in an existing table with preloaded data. This column uses a primary key from another table and I want to default this to 5. I have tried the following code:
ALTER TABLE group
ADD group_type INT
GO
ALTER TABLE group
ADD CONSTRAINT FK_group_type DEFAULT 5 FOR group_type
GO
I was expecting on alter of the group table then all the values will be filled with 5 but instead its NULL. What am I doing wrong?
First of all, adding a DEFAULT constraint (in it's own SQL statement) to a column does not effect existing data in that column. It only effects new INSERTS to that table which do not provide a value for that column.
Second, you haven't created a FOREIGN KEY constraint here.
EDIT:
Here would be one way to create the FK correctly
ALTER TABLE group
ADD group_type_id INT
GO
ALTER TABLE group
ADD CONSTRAINT fk_groupType FOREIGN KEY (group_type_id)
REFERENCES group_type (group_type_id)
This worked for me, it set the foreign key constraint, default value, and updated existing table records all in a single ALTER TABLE statement. I'm using a SQL Azure database (via SQL Management Studio), so, YMMV.
ALTER TABLE Group
ADD GroupTypeId int NOT NULL
CONSTRAINT DK_GroupTypeId DEFAULT (5) WITH VALUES
CONSTRAINT FK_GroupTypeId FOREIGN KEY
REFERENCES [dbo].[GroupType] (GroupTypeId)
GO
It took a while to run, but a subsequent select, showed the rows had the correct default value for those columns.
Disclaimer: I edited the above query from my table / key names to yours without re-testing it, so you may want to double check it for any typos or other mismatches; The syntax should be the same though.
You can use:
alter table [group]
add group_type int constraint df_group_type default (5) with values
However, it doesn't seem a good idea to use constant as a default value for a column, which is supposed to be FK column.
It seems, that may be what actually you are trying to do is following:
alter table [group] add column group_type int
GO
update [group] set group_type = (select id from group_type where desc ='typeA')
GO
alter table [group] add constraint FK_group_grouptype foreign key (group_type) references group_type (id)
GO
Adding default constraint will affect existing rows if you add new not nullable column to table.
ALTER TABLE group
ADD group_type INT NOT NULL
CONSTRAINT DK_group_type DEFAULT 5
GO

Primary Key on existing data

I need to delete existing PK from table and create new in new column. Because column for new PK was added later (after table creation) - we have nulls for old rows. Should I use UPDATE statement or there is some option in "ADD CONSTRAINT" clause which automatically determine NULLs and generate GUIDs for them?
Thanks for help.
This is what you have to do.
UPDATE TABLE1
SET GUID = NEWID()
WHERE GUID IS NULL
Now to add a new contstraint, you will have tod elete the old one. This is how you can do it:
ALTER TABLE TABLE1
DROP CONSTRAINT PrimaryKeyName
ALTER TABLE TABLE1
ADD CONSTRAINT PrimaryKeyName PRIMARY KEY (GUID)

SQL Server Compact alter column size with constraint?

I am trying to modify the size of a column in a table, however that column is a primary key column and is used in other table ( which would need to have its size modified too)
I have a table called table1 with a column named column1 as primary key
I also have table2,table3 and table4 that has table2column1, table3column1 and table4column1 respectively.
table2column1,table3column1 and table4column1 are foreign keys ( reference column1 from table1) and they are also used as a composite primary key in their respective table.
I tried doing this to alter the size of the column
ALTER TABLE UtilisateurNotes ALTER COLUMN IDNotes nvarchar(250)
It did not work.
This is the error message : Cannot alter a column that is part of a key or an index.
Anyone has an idea what I should do? thank you Gibit
You have to drop the foreign keys and primary key index in order to modify the column and then rebuild them after.
If you're in SQL Server Management Studio and you use the Object Explorer then you can right click on the specific Primary Key or Foreign Key specified in the error message and use Script as > CREATE AND DROP to help you generate the necessary scripts for the update.

Resources