• subscribe
July 19, 2005 12:00 AM

Using Fields as Primary Keys

SQL Server Pro
InstantDoc ID #46890

What's a quick query to find out whether two fields together are unique and if I can use the combination as a primary key?

Intermediate and advanced users will know this is a simple query to write, however, I see questions like this regularly so I know it's a question that novices struggle with. Here's a simple query to get the information you want.

SELECT ColA,ColB,COUNT(*)
FROM TestTable
GROUP BY ColA,ColB
HAVING COUNT(*) > 1

In this case, the query returns a list of all unique combinations for ColA and ColB in which the combination of ColA and ColB isn't unique. Using the HAVING clause is like using a WHERE clause that's applied to the results after the GROUP BY has been applied. By saying we only want to see the result of combinations that have a count greater than 1, we'll see all value pairs for ColA and ColB that aren't unique.



ARTICLE TOOLS

Comments
    There are no comments to display. Be the first one!
You must log on before posting a comment.

Are you a new visitor? Register Here