Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql - Retrieve partial index WHERE expression

Tags:

postgresql

How would I run a query (on PostgreSQL internal tables) to retrieve the conditional expression for the partial index (roles_user_group_role_idx below in this case).

# \d roles
                                Table "public.roles"
    Column     |            Type             |               Modifiers               
---------------+-----------------------------+---------------------------------------
 id            | character varying(15)       | not null default next_id('r'::bpchar)
 user_id       | character varying(15)       | not null
 group_id      | character varying(15)       | not null
 role          | character varying(255)      | not null
 language_code | character varying(2)        | 
 created_at    | timestamp without time zone | not null
 updated_at    | timestamp without time zone | not null
Indexes:
    "roles_pkey" PRIMARY KEY, btree (id)
    "roles_user_group_role_idx" UNIQUE, btree (user_id, group_id, role) WHERE language_code IS NULL

According to PostgreSQL pg_index doc, pg_index.indpred seems to be the field I need to look into. Running this query:

SELECT
    C.oid,
    I.indpred
FROM pg_catalog.pg_class C,
     pg_catalog.pg_namespace N,
     pg_catalog.pg_index I
WHERE C.relname = 'roles_user_group_role_idx'
  AND C.relnamespace = N.oid
  AND I.indexrelid = C.oid
  AND N.nspname = 'public';

gives me this, which is not quite there.

   oid   |                                                                                  indpred                                                                                  
---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 1235504 | {NULLTEST :arg {VAR :varno 1 :varattno 5 :vartype 1043 :vartypmod 6 :varcollid 100 :varlevelsup 0 :varnoold 1 :varoattno 5 :location 95} :nulltesttype 0 :argisrow false}

Am I on the right direction? How do I get the WHERE clause of the partial index? I'm using PG 9.2

like image 866
huy Avatar asked Apr 12 '26 00:04

huy


1 Answers

OK after a bit of googling I found the answer here, correct query:

SELECT
    C.oid,
    pg_get_expr(I.indpred, I.indrelid)
FROM pg_catalog.pg_class C,
     pg_catalog.pg_namespace N,
     pg_catalog.pg_index I
WHERE C.relname = 'roles_user_group_role_idx'
  AND C.relnamespace = N.oid
  AND I.indexrelid = C.oid
  AND N.nspname = 'public';

result:

   oid   |       pg_get_expr       
---------+-------------------------
 1235504 | (language_code IS NULL)
like image 177
huy Avatar answered Apr 13 '26 14:04

huy