我听说在编写SQL命令时使用SELECT *通常是不好的做法,因为选择您特别需要的列会更有效。

如果我需要选择表中的每一列,我应该使用

SELECT * FROM TABLE

or

SELECT column1, colum2, column3, etc. FROM TABLE

在这种情况下,效率真的重要吗?如果你真的需要所有的数据,我认为SELECT *在内部会更优,但我这么说并没有真正理解数据库。

我很好奇在这种情况下最好的做法是什么。

更新:我可能应该指定,我真正想要执行SELECT *的唯一情况是,当我从一个表中选择数据时,我知道总是需要检索所有列,即使添加了新列。

然而,鉴于我所看到的反应,这似乎仍然是一个坏主意,由于我曾经考虑过的许多技术原因,SELECT *不应该被使用。


当前回答

记住,如果根据定义有一个内部连接,则不需要所有列,因为连接列中的数据是重复的。

It's not like listing columns in SQl server is hard or even time-consuming. You just drag them over from the object browser (you can get all in one go by dragging from the word columns). To put a permanent performance hit on your system (becasue this can reduce the use of indexes and becasue sending unneeded data over the network is costly) and make it more likely that you will have unexpected problems as the database changes (sometimes columns get added that you do not want the user to see for instance) just to save less than a minute of development time is short-sighted and unprofessional.

其他回答

同时也要记住变化。今天,Select *只选择您需要的列,但明天它可能还会选择我刚刚添加的varbinary(MAX)列,而您现在还可以检索所有3.18 gb的二进制数据,这些数据昨天不在表中。

这是一个老帖子,但仍然有效。作为参考,我有一个非常复杂的查询,包括:

12个表 6左连接 9个内连接 12个表共108列 我只需要54列 一个4列的Order By子句

当我使用Select *执行查询时,平均花费2869ms。 当我使用Select执行查询时,平均花费1513ms。

返回的总行数为13,949。

毫无疑问,选择列名意味着比Select *更快的性能

在某些情况下,SELECT *适用于维护目的,但一般情况下应该避免使用。

These are special cases like views or stored procedures where you want changes in underlying tables to propagate without needing to go and change every view and stored proc which uses the table. Even then, this can cause problems itself, like in the case where you have two views which are joined. One underlying table changes and now the view is ambiguous because both tables have a column with the same name. (Note this can happen any time you don't qualify all your columns with table prefixes). Even with prefixes, if you have a construct like:

选择A., B. -您可能会遇到客户端现在难以选择正确字段的问题。

一般来说,我不使用SELECT *,除非我在做一个有意识的设计决策,并指望相关的风险很低。

到目前为止,这里回答了很多很好的理由,这里还有一个没有被提到的理由。

显式地命名列将帮助您进行后续的维护。在某些情况下,您将进行更改或排除故障,并发现自己在问“这个列到底用在哪里”。

如果显式列出了名称,那么通过所有存储过程、视图等查找对该列的每个引用就很简单了。只需为您的DB模式转储一个CREATE脚本,并在其中进行文本搜索。

当且仅当需要获取所有字段的数据时,使用显式字段名并不比使用*更快。

你的客户端软件不应该依赖于返回字段的顺序,所以这也是毫无意义的。

而且有可能(尽管不太可能)需要使用*获取所有字段,因为您还不知道存在哪些字段(考虑非常动态的数据库结构)。

使用显式字段名的另一个缺点是,如果字段名很多而且很长,那么阅读代码和/或查询日志就会更加困难。

所以规则应该是:如果你需要所有的字段,使用*,如果你只需要一个子集,显式命名它们。