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

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

SELECT * FROM TABLE

or

SELECT column1, colum2, column3, etc. FROM TABLE

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

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

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

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


当前回答

select *是一件坏事,有四个主要原因:

The most significant practical reason is that it forces the user to magically know the order in which columns will be returned. It's better to be explicit, which also protects you against the table changing, which segues nicely into... If a column name you're using changes, it's better to catch it early (at the point of the SQL call) rather than when you're trying to use the column that no longer exists (or has had its name changed, etc.) Listing the column names makes your code far more self-documented, and so probably more readable. If you're transferring over a network (or even if you aren't), columns you don't need are just waste.

其他回答

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

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

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

如果你需要每一列,那么只需使用SELECT *,但记住,顺序可能会改变,所以当你消费的结果访问他们的名字,而不是通过索引。

我将忽略关于*需要如何获得列表的注释-解析和验证命名列的机会等于处理时间,如果不是更多的话。不要过早地优化;-)

select *是一件坏事,有四个主要原因:

The most significant practical reason is that it forces the user to magically know the order in which columns will be returned. It's better to be explicit, which also protects you against the table changing, which segues nicely into... If a column name you're using changes, it's better to catch it early (at the point of the SQL call) rather than when you're trying to use the column that no longer exists (or has had its name changed, etc.) Listing the column names makes your code far more self-documented, and so probably more readable. If you're transferring over a network (or even if you aren't), columns you don't need are just waste.

每次都定义你想要SELECT的列。没有理由不这样做,性能的提高是非常值得的。

他们不应该给“SELECT *”选项

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

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

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

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