Why is SELECT * considered harmful?

后端 未结 15 1465
野的像风
野的像风 2020-11-21 04:12

Why is SELECT * bad practice? Wouldn\'t it mean less code to change if you added a new column you wanted?

I understand that SELECT COUNT(*)

15条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 04:46

    The asterisk character, "*", in the SELECT statement is shorthand for all the columns in the table(s) involved in the query.

    Performance

    The * shorthand can be slower because:

    • Not all the fields are indexed, forcing a full table scan - less efficient
    • What you save to send SELECT * over the wire risks a full table scan
    • Returning more data than is needed
    • Returning trailing columns using variable length data type can result in search overhead

    Maintenance

    When using SELECT *:

    • Someone unfamiliar with the codebase would be forced to consult documentation to know what columns are being returned before being able to make competent changes. Making code more readable, minimizing the ambiguity and work necessary for people unfamiliar with the code saves more time and effort in the long run.
    • If code depends on column order, SELECT * will hide an error waiting to happen if a table had its column order changed.
    • Even if you need every column at the time the query is written, that might not be the case in the future
    • the usage complicates profiling

    Design

    SELECT * is an anti-pattern:

    • The purpose of the query is less obvious; the columns used by the application is opaque
    • It breaks the modularity rule about using strict typing whenever possible. Explicit is almost universally better.

    When Should "SELECT *" Be Used?

    It's acceptable to use SELECT * when there's the explicit need for every column in the table(s) involved, as opposed to every column that existed when the query was written. The database will internally expand the * into the complete list of columns - there's no performance difference.

    Otherwise, explicitly list every column that is to be used in the query - preferably while using a table alias.

提交回复
热议问题