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

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

SELECT * FROM TABLE

or

SELECT column1, colum2, column3, etc. FROM TABLE

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

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

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

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


当前回答

结果太大了。从SQL引擎生成结果并将结果发送到客户机的速度很慢。

客户端是一个通用的编程环境,不是也不应该被设计为过滤和处理结果(例如WHERE子句,ORDER子句),因为行数可能非常大(例如数千万行)。

其他回答

当您有一个连接时,不使用select *对于性能特别重要,因为根据定义,至少两个字段包含相同的数据。您不希望将不需要的数据从数据库服务器发送到应用程序或web服务器而浪费网络资源。使用select *似乎更简单,但这是一种糟糕的做法。由于很容易将列名拖到查询中,所以只需这样做即可。

Another issue that occurs when using select * is that there are idiots who choose to add new fields in the middle fo the table (always a bad practice), if you use select * as the basis for an insert then suddenly your column order may be wrong and you may try to insert the social security number into the honorarium (the amoutn of money a speaker may get paid to pick a non-random example) which could be a very bad thing for data integrity. Even if the select isn't an insert, it looks bad to the customer when the data is suddenly in the worng order on the report or web page.

我认为在任何情况下使用select *都不会比使用列列表更好。您可能认为这样更容易维护,但事实并非如此,而且当您不需要的字段被添加到表中时,会导致您的应用程序毫无理由地变慢。您还必须面对修复问题,如果您使用列列表就不会损坏,因此您节省的不添加列的时间将用于此操作。

明确地定义列,因为SQL Server将不需要对列进行查找来拉出它们。如果定义了列,则SQL可以跳过该步骤。

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

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

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

即使查询不是通过网络发送,SELECT *也是一种糟糕的做法。

Selecting more data than you need makes the query less efficient - the server has to read and transfer extra data, so it takes time and creates unnecessary load on the system (not only the network, as others mentioned, but also disk, CPU etc.). Additionally, the server is unable to optimize the query as well as it might (for example, use covering index for the query). After some time your table structure might change, so SELECT * will return a different set of columns. So, your application might get a dataset of unexpected structure and break somewhere downstream. Explicitly stating the columns guarantees that you either get a dataset of known structure, or get a clear error on the database level (like 'column not found').

当然,对于一个小而简单的系统来说,所有这些都不太重要。

虽然显式列出列对性能有好处,但不要太疯狂。

因此,如果您使用所有数据,为了简单起见,请尝试SELECT *(想象有许多列并执行JOIN…)查询可能会变得很糟糕)。然后,测量。与显式列出列名的查询进行比较。

不要猜测业绩,要衡量业绩!

当你有一些包含大数据的列(比如一篇文章的主体),并且在给定的查询中不需要它时,显式列表是最有用的。然后,通过在应答中不返回它,DB服务器可以节省时间、带宽和磁盘吞吐量。您的查询结果也会更小,这对任何查询缓存都是有利的。