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

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

SELECT * FROM TABLE

or

SELECT column1, colum2, column3, etc. FROM TABLE

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

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

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

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


当前回答

就性能而言,我看到的评论说两者是相等的。但是在可用性方面有一些+和-

当您在查询中使用(select *)时,如果有人更改了表并添加了前一个查询不需要的新字段,这是不必要的开销。如果新添加的字段是一个blob或图像字段怎么办??您的查询响应时间将会非常慢。

另一方面,如果你使用一个(select col1,col2,..),如果表被修改并添加了新的字段,如果结果集中需要这些字段,你总是需要在表修改后编辑你的选择查询。

但我建议总是使用select col1 col2…在你的查询和修改查询,如果表改变以后…

其他回答

让我们想想哪一个更快。如果你可以选择你需要的数据,那么速度会更快。然而,在测试中,您可以提取所有数据,以判断哪些数据可以根据业务需求过滤掉。

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

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.

指定你需要的列总是更好的,如果你想一次,SQL不必每次查询都想着“wtf是*”。最重要的是,稍后有人可能会向表中添加您在查询中实际上不需要的列,在这种情况下,通过指定所有列会更好。

即使查询不是通过网络发送,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').

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

您应该只选择您需要的列。即使你需要所有的列,最好列出列名,这样sql server就不需要查询系统表中的列了。

此外,如果有人向表中添加列,应用程序可能会崩溃。您的程序也会得到它没有预料到的列,而且它可能不知道如何处理它们。

除此之外,如果表有一个二进制列,那么查询将更慢,并使用更多的网络资源。