I have a Postgresql schema that contains many tables
I set a rule where every foreign key column has its name starting with "fk_"
But I just noticed that for some of those fields, I forgot to set the foreign key constraints
Would you help me building a request that identifies all the fields starting with fk that do not have a foreign key constraint set ?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Yes, I'd be happy to help you with that. We'll use the system catalogs to query the schema metadata. Here's the request you asked for:
sql
SELECT
table_name,
column_name
FROM
information_schema.columns
WHERE
table_schema NOT IN ('pg_catalog', 'information_schema') -- exclude system schemas
AND column_name LIKE 'fk_%' -- columns starting with 'fk_'
AND (table_name, column_name) NOT IN (
SELECT
table_name,
column_name
FROM
information_schema.key_column_usage
WHERE
table_schema NOT IN ('pg_catalog', 'information_schema')
AND constraint_name LIKE 'fk_%' -- foreign key constraints start with 'fk_'
)
ORDER BY
table_name,
column_name;
Let me explain what this query does:
We start by querying information_schema.columns, which contains metadata about all columns in the database.
We filter out system schemas (pg_catalog and information_schema) as we're only interested in our own schema.
We select only columns whose name starts with fk_ using the LIKE operator.
Now, here's the magic part: we use a NOT IN clause to exclude columns that do have a foreign key constraint. We query information_schema.key_column_usage, which lists all columns that participate in a constraint (including foreign keys).
We apply the same schema filter as before.
We filter foreign key constraints by checking if the constraint_name starts with fk_. By convention, PostgreSQL names foreign key constraints fk_<table>_<column>_fkey (you can verify this by running \d <table_name> in psql).
If a column is found in this result set, it means it has a foreign key constraint, so we exclude it from our final result using NOT IN.
Finally, we order the results by table and column name for easier reading.
Run this query, and you'll get a list of tables and columns starting with fk_ that don't have a foreign key constraint set.
Example use case:
Suppose your schema has the following tables:
sql
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
fk_customer_id INTEGER, -- OOPS! No FK constraint
total DECIMAL(10, 2)
);
CREATE TABLE customers (
id SERIAL PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE order_items (
id SERIAL PRIMARY KEY,
fk_order_id INTEGER REFERENCES orders(id), -- FK constraint set
product_id INTEGER
);