Search code examples
primary-keysnowflake-cloud-data-platform

How to get list of table primary keys in snowflake?


I want to get all primary keys of a table in list in snowflake. I used

SHOW PRIMARY KEYS IN TABLE t1

but the output is a set of columns:

"created_on"    "database_name" "schema_name"   "table_name"    "column_name"   "key_sequence"  "constraint_name"   "comment"

and I need only the column_name column. I tried to do:

select a.* from (SHOW PRIMARY KEYS IN TABLE t1) a

but I got this error:

SQL Error [1003] [42000]: SQL compilation error:
syntax error line 1 at position 17 unexpected 'SHOW'.

if somebody has an idea, please help. thanks.


Solution

  • You can use RESULT_SCAN function to process the output of the SHOW command:

    https://docs.snowflake.com/en/sql-reference/functions/result_scan.html

    SHOW PRIMARY KEYS IN TABLE t1;
    
    SELECT * FROM table(RESULT_SCAN( LAST_QUERY_ID() ));
    

    Another sample:

    SHOW PRIMARY KEYS IN TABLE test1;
    select last_query_id();
    
    This is the result:
    -------------------
    019c7ab2-3200-9e9b-0000-b4550014773e
    

    Then I use it with RESULT_SCAN:

    SELECT * FROM table(RESULT_SCAN( '019c7ab2-3200-9e9b-0000-b4550014773e'));
    

    Please note that, last_query_id will always return last query in current session. It does not return the query IDs executed with other sessions.