How do I show unique constraints of a table in MySQL?

Viewed 38983

I created them, but I forgot which ones they are.

I just want to

  1. show them.
  2. remove all the constraints on a table.
5 Answers

This doesn't produce elegant output but is easy to remember:

SHOW CREATE TABLE table_name;

This query returns primay keys, unique keys and foreign ones :

show indexes from table_name;

The OP asked for a single table, which this will do.

In addition, removing the last where clause will show all columns for a database which are protected by unique constraints:

SELECT
  CONSTRAINT_NAME,
  TABLE_NAME,
  COLUMN_NAME
FROM information_schema.KEY_COLUMN_USAGE
WHERE
  CONSTRAINT_NAME LIKE 'UNIQ%'
  AND TABLE_SCHEMA = 'your_database_name'
  AND TABLE_NAME = 'your_table_name';

Unfortunately mysql doesn't facilitate the removal of indexes based on a query result. You could execute the output of the following query to drop all unique columns in 2 queries:

SELECT CONCAT(
  'ALTER TABLE ',
  TABLE_NAME,
  ' DROP INDEX ',
  CONSTRAINT_NAME,
  '; -- drops ',
  COLUMN_NAME,
  ' constraint'
)
FROM information_schema.KEY_COLUMN_USAGE
WHERE
  CONSTRAINT_NAME LIKE 'UNIQ%'
  AND TABLE_SCHEMA = 'your_database_name';
Related