0

Let's suppose I have a table in PorstreSQL defined as:

CREATE TABLE my_table (
  id serial not null primary key,
  var1 text null,
  var2 text null unique,
  var3 text null,
  var4 text null unique
);

Is there a query to information_schema that provides the names of unique columns only? The desirable response should be:

var2
var4

The query should ignore unique keys for multiple columns together.

3
  • What do you mean by "ignore unique keys for multiple columns together"? Commented Dec 11, 2019 at 10:53
  • I mean the constraint for the unique combination of several fields. Commented Dec 11, 2019 at 11:22
  • I have amended the answer for that requirement. Commented Dec 11, 2019 at 12:31

1 Answer 1

1

You need information_schema.table_constraints and information_schema.constraint_column_usage:

SELECT table_schema, table_name, column_name
FROM information_schema.table_constraints AS c
   JOIN information_schema.constraint_column_usage AS cc
      USING (table_schema, table_name, constraint_name)
WHERE c.constraint_type = 'UNIQUE';

If you want to skip constraints with more than one column, use grouping:

SELECT table_schema, table_name, min(column_name)
FROM information_schema.table_constraints AS c
   JOIN information_schema.constraint_column_usage AS cc
      USING (table_schema, table_name, constraint_name)
WHERE c.constraint_type = 'UNIQUE'
GROUP BY table_schema, table_name
HAVING count(*) = 1;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.