开发者

Write a query to return the list of unique names from table

开发者 https://www.devze.com 2023-04-01 01:51 出处:网络
Here is the table: table开发者_StackOverflow社区 A ( idintegerprimary key, namevarchar(20), ageinteger

Here is the table:

table开发者_StackOverflow社区 A (
 id    integer       primary key,
 name  varchar(20),
 age   integer
)

The interview question is:

Write a query to return the list of unique names from table .

Here is my solution:

select id from A group by name;

My question: is this the efficient way to return the list of the unique names?


No, because you're returning the IDs, not the names. That query won't even work in many DBMS' because selected columns have to either be in the group by clause or have an aggregating function (like max() or sum() and so on) applied to them.

You would need:

select name from a group by name

It's usually even more efficient if the name column is indexed.

The other common way of doing this is:

select distinct name from a


I would go with

SELECT DISTINCT name FROM A

or

SELECT name FROM A GROUP BY name

both are well understood. As for which one is faster, it may depend on the RDBMS in question.


Select Distinct name FROM A is possibly the best bet you can get. There is no concept of getting list. You can create a list in the programming language which is linked to your database.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号