gpt-3.5-turbo-0125· OpenAI
WildChat-4.8M (AI2)
In postgres, how do I alter a column in a table to add references other_table(...)
- User
In postgres, how do I alter a column in a table to add references other_table(...)
- Assistant
To add a reference to another table in Postgres, you can use the
ALTER TABLEcommand with theADD CONSTRAINTclause. Here is the syntax to add a foreign key constraint to a column in a table:sqlALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY (column_name) REFERENCES other_table(other_column);Here's an example to illustrate this:
Suppose you have two tables
ordersandcustomers, and you want to add a foreign key constraint on thecustomer_idcolumn in theorderstable that references theidcolumn in thecustomerstable.sqlALTER TABLE orders ADD CONSTRAINT fk_customer_id FOREIGN KEY (customer_id) REFERENCES customers(id);This command will add a foreign key constraint on the
customer_idcolumn in theorderstable that references theidcolumn in thecustomerstable.