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

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

SELECT * FROM TABLE

or

SELECT column1, colum2, column3, etc. FROM TABLE

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

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

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

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


当前回答

即使查询不是通过网络发送,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 *和等效的SELECT col1、col2等的查询执行计划。这将告诉您两个查询中哪一个更有效。您还可以生成一些不同体积的测试数据,看看时间是什么。

即使查询不是通过网络发送,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 *只选择您需要的列,但明天它可能还会选择我刚刚添加的varbinary(MAX)列,而您现在还可以检索所有3.18 gb的二进制数据,这些数据昨天不在表中。

在性能方面,具有特定列的SELECT可以更快(不需要读入所有数据)。如果您的查询确实使用了所有列,那么带显式参数的SELECT仍然是首选。任何速度差异基本上都是不明显的,并且接近恒定时间。总有一天你的模式会改变,这是预防由此产生问题的好保险。

嘿,实际一点。在创建原型时使用select *,在实现和部署时选择特定的列。从执行计划的角度来看,两者在现代系统中是相对相同的。但是,选择特定的列会限制必须从磁盘检索、存储在内存中并通过网络发送的数据量。

最终,最好的计划是选择特定的列。