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

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

SELECT * FROM TABLE

or

SELECT column1, colum2, column3, etc. FROM TABLE

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

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

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

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


当前回答

准确地说出需要哪些列是更好的实践的一个原因是,将来可能会对表结构进行更改。

如果您正在使用基于索引的方法手动读入数据,用查询结果填充数据结构,那么将来当您添加/删除列时,您将会头疼地试图找出哪里出了问题。

至于哪种方法更快,我会听取别人的专业意见。

其他回答

选择特定列更好的一个原因是,它提高了SQL Server从索引访问数据的概率,而不是查询表数据。

这是我写的一篇关于它的文章:选择查询的真正原因是糟糕的索引覆盖

它也不太容易更改,因为任何消耗数据的代码都将获得相同的数据结构,而不管您将来对表模式做了什么更改。

The SELECT * might be ok if you actually needed all of the columns - but you should still list them all individually. You certainly shouldn't be selecting all rows from a table - even if the app & DB are on the same server or network. Transferring all of the rows will take time, especially as the number of rows grows. You should have at least a where clause filtering the results, and/or page the results to only select the subset of rows that need to be displayed. Several ORM tools exist depending on app language you are using to assist in querying and paging the subset of data you need. For example, in .NET Linq to SQL, Entity Framework, and nHibernate all will help you with this.

即使查询不是通过网络发送,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不必每次查询都想着“wtf是*”。最重要的是,稍后有人可能会向表中添加您在查询中实际上不需要的列,在这种情况下,通过指定所有列会更好。

准确地说出需要哪些列是更好的实践的一个原因是,将来可能会对表结构进行更改。

如果您正在使用基于索引的方法手动读入数据,用查询结果填充数据结构,那么将来当您添加/删除列时,您将会头疼地试图找出哪里出了问题。

至于哪种方法更快,我会听取别人的专业意见。