我听说在编写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.

其他回答

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

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

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

这是一个老帖子,但仍然有效。作为参考,我有一个非常复杂的查询,包括:

12个表 6左连接 9个内连接 12个表共108列 我只需要54列 一个4列的Order By子句

当我使用Select *执行查询时,平均花费2869ms。 当我使用Select执行查询时,平均花费1513ms。

返回的总行数为13,949。

毫无疑问,选择列名意味着比Select *更快的性能

对服务器来说,指定列名肯定更快。但是,如果

性能不是大问题(例如,这是一个网站内容数据库,每个表中有数百行,可能是数千行,但不是数百万行);和 你的工作是使用公共框架创建许多小型的类似应用程序(例如面向公众的内容管理网站),而不是创建一个复杂的一次性应用程序;和 灵活性很重要(为每个站点定制大量的db模式);

那么你最好坚持使用SELECT *。在我们的框架中,大量使用SELECT *允许我们将一个新的网站托管内容字段引入到一个表中,赋予它CMS的所有好处(版本控制、工作流/审批等),同时只在几个点上修改代码,而不是几十个点。

我知道DB专家们会因此而恨我——请继续,投我反对票——但在我的世界里,开发人员的时间是稀缺的,而CPU周期是丰富的,所以我相应地调整我所节省的和浪费的。

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