Check whether a field has the property `UNIQUE` in mysql and PHP

Jonathan de M. picture Jonathan de M. · Dec 27, 2012 · Viewed 12.9k times · Source

How can I check whether a field from a table is set as UNIQUE?

For example I have a table named users with a field email set as UNIQUE and a field picture not set as UNIQUE, I want before selecting check whether the field is set set as UNIQUE if not then don't do the SELECT.

I tried to SELECT then count the returned number of row, if more than 1 then it's not UNIQUE,

"SELECT * FROM table WHERE email='$email'"
//...some mysql php line later
if($count > 1){
    //return nothing
}

but it's not efficient, what if there is no duplicate.

What's the best way to check whether a field is set as UNIQUE in PHP?

Edit: no duplicate doesn't mean it has UNIQUE property

Answer

John Dvorak picture John Dvorak · Dec 27, 2012

From the documentation of SHOW INDEX (found by @diEcho):

SHOW INDEX returns the following fields:

Non_unique -- 0 if the index cannot contain duplicates, 1 if it can.

Column_name -- The column name.

Try:

SHOW INDEXES
FROM $tablename
WHERE Column_name='$field'
AND NOT Non_unique

Note that this assumes that there is no UNIQUE index that spans multiple columns. If there can be, then you might want to exclude these with a subquery.

Also note disabled indexes also show in this query (the possibility of disabled indexes is mentioned in the documentation on the Comment column). There doesn't seem to be a column reflecting this, so you might need to parse the Comment column if you have disabled indexes.

There's no need to compare Non_unique to a number - MySQL uses 0 and 1 for booleans anyways