What is the reason not to use select *?

后端 未结 20 2777
独厮守ぢ
独厮守ぢ 2020-11-21 07:14

I\'ve seen a number of people claim that you should specifically name each column you want in your select query.

Assuming I\'m going to use all of the columns anyway

20条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 08:03

    The essence of the quote of not prematurely optimizing is to go for simple and straightforward code and then use a profiler to point out the hot spots, which you can then optimize to be efficient.

    When you use select * you're make it impossible to profile, therefore you're not writing clear & straightforward code and you are going against the spirit of the quote. select * is an anti-pattern.


    So selecting columns is not a premature optimization. A few things off the top of my head ....

    1. If you specify columns in a SQL statement, the SQL execution engine will error if that column is removed from the table and the query is executed.
    2. You can more easily scan code where that column is being used.
    3. You should always write queries to bring back the least amount of information.
    4. As others mention if you use ordinal column access you should never use select *
    5. If your SQL statement joins tables, select * gives you all columns from all tables in the join

    The corollary is that using select * ...

    1. The columns used by the application is opaque
    2. DBA's and their query profilers are unable to help your application's poor performance
    3. The code is more brittle when changes occur
    4. Your database and network are suffering because they are bringing back too much data (I/O)
    5. Database engine optimizations are minimal as you're bringing back all data regardless (logical).

    Writing correct SQL is just as easy as writing Select *. So the real lazy person writes proper SQL because they don't want to revisit the code and try to remember what they were doing when they did it. They don't want to explain to the DBA's about every bit of code. They don't want to explain to their clients why the application runs like a dog.

提交回复
热议问题