Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL - unique

Status
Not open for further replies.

manpaul

Technical User
Joined
Jan 10, 2005
Messages
118
Location
CA
Is there a unique option in SQL

I would like to create a table with a custno and name from another table but only add the record to the new table if the custno is not in the new table already?

Only one record for custno in the new table

Paul
 
Paul,

You could use the DISTINCT keyword:
Code:
SELECT DISTINCT Custno, name FROM Table1 INTO TABLE Table2
or you can use GROUP BY:
Code:
SELECT Custno, name FROM Table1 INTO TABLE Table2 GROUP BY 1,2
If there a very large number of records, I think the SQL will run faster using GROUP BY because I think it works on the results rather than the original table.

Hope that helps,

Stewart
PS If you want to get the best response to a question, please check out FAQ184-2483 first.
 
The GROUP BY clause requires an AGGREGATE function, such as COUNT or SUM, at least in VFP8 and above.

The DISTINCT clause is the correct way to get unique records.

Mike Krausnick
Dublin, California
 
Er, I don't think that's actually correct Mike. When I saw what you wrote, I tested it out in VFP8 and grouping without an aggregate works fine.

Stewart
 
Stewart,

I agree with you.

In VFP 8.0 and above, the rule is: if you do grouping, the expressions in the SELECT list must be either the fields that take part in the grouping or aggregate functions. So, you can do grouping without aggregates, provided you are grouping on all the columns in the result set.

As for the difference in performance between DISTINCT and GROUP BY, I would guess that they would be pretty similar. VFP is clever enough to optimise both forms in the most efficient way. But that's only my guess.

Mike

__________________________________
Mike Lewis (Edinburgh, Scotland)

My sites:
Visual FoxPro (www.ml-consult.demon.co.uk)
Crystal Reports (www.ml-crystal.com)
 
Thanks

THe distinct work fine, I have to wait to learn the group by command

Paul
 
My mistake - I was going from memory and I could have sworn I read that somewhere. Another misconception obliterated!

I'd still use DISTINCT though, because that's what it's for.

Mike Krausnick
Dublin, California
 
Mike,

I'd still use DISTINCT though, because that's what it's for.

I agree with that as well. In this context, DISTINCT is much more obvious than GROUP BY.

Mike


__________________________________
Mike Lewis (Edinburgh, Scotland)

My sites:
Visual FoxPro (www.ml-consult.demon.co.uk)
Crystal Reports (www.ml-crystal.com)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top