Friday, March 9, 2012

Newbie Basic Question - DISTINCT & PKs

Could somebody please clarify this simple question for me? I'm clearly missing something basic...

I'm in the process of trying to teach myself T-SQL out of a WROX book, and am having a problem wrapping my head around this example, I understand the concept of Primary Keys through using MS Access, but haven't used TSQL extensively (or at all for that matter...)

Using the classic "Northwind" database, using this query:

SELECT COUNT(OrderID)
FROM [Order Details]

This returns 2155, which is the total number of rows with an OrderID, the primary key. Now, as I understood it, a PK has to be unique, but yet this query on the same DB:

SELECT COUNT(DISTINCT OrderID)
FROM [Order Details]

returns 830 rows. If the PK (OrderID) is unqiue, how is the DISTINCT function returning fewer rows? Wouldn't that imply there are duplicate PKs?

I'm sure there's a simple answer to this, but I just can't seem to get my head around it... Thank you so much for taking the time to explain this to a rookie!Because orderId isn't the primary key of [order details]. The PK of that table is OrderId, ProductId. Check sp_help '[Order Details] ' for the details. OrderId is a Foreign Key reference to Orders, where the PK is orderId.|||

Aaaah.... I see, I think I mis-interpreted the information I was getting from Management Studio. Thank you so much for taking the time to correct a silly mistake!

No comments:

Post a Comment