我听说在编写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 *,在实现和部署时选择特定的列。从执行计划的角度来看,两者在现代系统中是相对相同的。但是,选择特定的列会限制必须从磁盘检索、存储在内存中并通过网络发送的数据量。

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

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

在某些情况下,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 *,除非我在做一个有意识的设计决策,并指望相关的风险很低。

我发现有些人似乎认为指定列要花费更长的时间。由于您可以将列列表从对象浏览器拖过来,因此在查询中指定列(如果您有很多列,并且需要花费一些时间将它们放在单独的行上)可能需要额外的一分钟时间。为什么人们认为这很耗时呢?