Encuentra y corrige infracciones de claves externas
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Para verificar si hay una clave externa en la que falta la clave primaria correspondiente, ejecuta el siguiente comando:
Muestra de código
WITHqAS(SELECTconrelid::regclassASfk_table,confrelid::regclassASpk_table,format('(%s)',(selectstring_agg(format('fk.%I',attname),', ')FROMpg_attributeaJOINunnest(conkey)ia(nr)ONia.nr=a.attnumWHEREattrelid=conrelid))ASfk_fields,format('(%s)',(selectstring_agg(format('pk.%I',attname),', ')FROMpg_attributeaJOINunnest(confkey)ia(nr)ONia.nr=a.attnumWHEREattrelid=confrelid))ASpk_fields,pg_get_constraintdef(oid)FROMpg_constraintWHEREcontype='f')SELECTformat($sql$DO$$BEGINRAISENOTICE'checking Foreign Key %3$s%1$s ==> %4$s%2$s';END;$$;SELECT%1$s,%2$sFROM%3$sASfkLEFTJOIN%4$sASpkON%1$s=%2$sWHERE%2$sISNULLAND%1$sISNOTNULL/* any NULL on FK side bypasses FK constraint by design *//* use limit for testing, or detecting that "there is a problem in this table */-- LIMIT 10$sql$,fk_fields,pk_fields,fk_table,pk_table)FROMq\gexec
El resultado de la secuencia de comandos será similar al siguiente. Si no hay resultados, no hay incumplimientos y vuelves a compilar tu índice de forma correcta.
Salida
id|pk_id----+-------
|4(1row)
En el resultado anterior, la primera columna muestra las columnas de clave primaria, en este ejemplo, una columna llamada id. La segunda columna es la columna referente para la clave externa. Esto significa que hay una fila, pk_id=4, en la que no existe una clave primaria superior. Puedes decidir si estas claves son válidas y, si no lo son, puedes borrarlas.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-04 (UTC)"],[[["\u003cp\u003eThis code checks for foreign key violations where a foreign key references a non-existent primary key.\u003c/p\u003e\n"],["\u003cp\u003eThe provided SQL script identifies and lists rows in foreign key tables that do not have a corresponding entry in the primary key table.\u003c/p\u003e\n"],["\u003cp\u003eThe script's output displays the foreign key column(s) and the corresponding non-existent primary key column(s).\u003c/p\u003e\n"],["\u003cp\u003eA null value on the foreign key side is by design and bypasses the foreign key constraint, so it will not be identified in the output.\u003c/p\u003e\n"]]],[],null,["# Find and fix foreign key violations\n\nTo check for a foreign key where the\ncorresponding primary key is missing, run the following command: \n\n### Code Sample\n\n```sql\n WITH q AS (\n SELECT conrelid::regclass AS fk_table, \n confrelid::regclass AS pk_table, \n format('(%s)',(select string_agg(format('fk.%I', attname), ', ') \n FROM pg_attribute a \n JOIN unnest(conkey) ia(nr) ON ia.nr = a.attnum\n WHERE attrelid = conrelid)) AS fk_fields, \n format('(%s)',(select string_agg(format('pk.%I', attname), ', ') \n FROM pg_attribute a \n JOIN unnest(confkey) ia(nr) ON ia.nr = a.attnum\n WHERE attrelid = confrelid)) AS pk_fields, \n pg_get_constraintdef(oid)\n FROM pg_constraint\n WHERE contype='f'\n )\n SELECT format(\n $sql$\n DO $$ BEGIN RAISE NOTICE 'checking Foreign Key %3$s%1$s ==\u003e %4$s%2$s'; END;$$;\n SELECT %1$s, %2$s \n FROM %3$s AS fk\n LEFT JOIN %4$s AS pk ON %1$s = %2$s \n WHERE %2$s IS NULL\n AND %1$s IS NOT NULL /* any NULL on FK side bypasses FK constraint by design */\n /* use limit for testing, or detecting that \"there is a problem in this table */\n -- LIMIT 10\n $sql$, fk_fields, pk_fields, fk_table, pk_table\n )\n FROM q\n \\gexec\n \n```\n\nThe output of the script will be similar to the following. If there is no\noutput, there are no violations and you have successfully rebuilt your index. \n\n### Output\n\n```bash\n id | pk_id \n ----+-------\n | 4\n (1 row)\n \n```\n\nIn the above output, the first column shows the primary key columns, in this\nexample, a column named `id`. The second column is the referencing column for\nthe foreign key. This means there is a row, `pk_id=4`, for which a parent\nprimary key doesn't exist. You can decide if these\nkeys are valid and if they are not, you can delete them."]]