Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql Constraints (display)

Tags:

sql

postgresql

I need to display the list of integrity constraints of my solution by indicating the name of the constraint, its type and the detail of the constraint (message that explains what validates the constraint), all sorted by table name and constraint name.

This is what I tried :

SELECT constraint_name, constraint_type
FROM user_constraints
WHERE table_name = 'mytable'

How can I display all of that and also give a message that indicates what validates the constraint ?

like image 945
fenton.raine Avatar asked Jul 30 '26 16:07

fenton.raine


1 Answers

Please try below code.

SELECT
    "ns"."nspname" AS "table_schema",
    "t"."relname" AS "table_name",
    "cnst"."conname" AS "constraint_name", pg_get_constraintdef ( "cnst"."oid" ) AS "expression",
CASE
        "cnst"."contype" 
        WHEN 'p' THEN
        'PRIMARY' 
        WHEN 'u' THEN
        'UNIQUE' 
        WHEN 'c' THEN
        'CHECK' 
        WHEN 'x' THEN
        'EXCLUDE' 
    END AS "constraint_type",
    "a"."attname" AS "column_name"
FROM
    "pg_constraint" "cnst" 
    INNER JOIN "pg_class" "t" ON "t"."oid" = "cnst"."conrelid"
    INNER JOIN "pg_namespace" "ns" ON "ns"."oid" = "cnst"."connamespace"
    LEFT JOIN "pg_attribute" "a" ON "a"."attrelid" = "cnst"."conrelid" 
    AND "a"."attnum" = ANY ( "cnst"."conkey" )
like image 63
D.Zotov Avatar answered Aug 02 '26 09:08

D.Zotov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!