Wednesday, March 7, 2012

Find if 2 fields together are unique

I understand this might be trivial but;
What's a neat query to find if two fields together are unique and can be
used as a PK ?
Thanks,
-AshTry,
if exists(select 1 from table1 group by col1, col2 having count(*) > 1)
print 'not unique'
else
print 'unique'
AMB
"Ash" wrote:

> I understand this might be trivial but;
> What's a neat query to find if two fields together are unique and can be
> used as a PK ?
> Thanks,
> -Ash|||"Ash" <Ash@.discussions.microsoft.com> wrote in message
news:F4990C25-3DCA-4504-BBB4-835F7263C550@.microsoft.com...
> I understand this might be trivial but;
> What's a neat query to find if two fields together are unique and can be
> used as a PK ?
> Thanks,
> -Ash
Try this:
SELECT col_1, col_2, COUNT(*)
FROM tablename
GROUP BY col_1, col_2
HAVING COUNT(*) > 1
Rick Sawtell
MCT, MCSD, MCDBA|||Perfect! Thanks.
"Rick Sawtell" wrote:

> "Ash" <Ash@.discussions.microsoft.com> wrote in message
> news:F4990C25-3DCA-4504-BBB4-835F7263C550@.microsoft.com...
> Try this:
> SELECT col_1, col_2, COUNT(*)
> FROM tablename
> GROUP BY col_1, col_2
> HAVING COUNT(*) > 1
>
> Rick Sawtell
> MCT, MCSD, MCDBA
>
>|||select
ColA
,ColB
,count(*)
from
TestTable
group by
ColA
,ColB
having
count(*) = 1
Brian Moran
Principal Mentor
Solid Quality Learning
SQL Server MVP
http://www.solidqualitylearning.com
"Ash" <Ash@.discussions.microsoft.com> wrote in message
news:F4990C25-3DCA-4504-BBB4-835F7263C550@.microsoft.com...
> I understand this might be trivial but;
> What's a neat query to find if two fields together are unique and can be
> used as a PK ?
> Thanks,
> -Ash

No comments:

Post a Comment