Why is SELECT * considered harmful?

后端 未结 15 1517
野的像风
野的像风 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:43

    Using SELECT * when you only need a couple of columns means a lot more data transferred than you need. This adds processing on the database, and increase latency on getting the data to the client. Add on to this that it will use more memory when loaded, in some cases significantly more, such as large BLOB files, it's mostly about efficiency.

    In addition to this, however, it's easier to see when looking at the query what columns are being loaded, without having to look up what's in the table.

    Yes, if you do add an extra column, it would be faster, but in most cases, you'd want/need to change your code using the query to accept the new columns anyways, and there's the potential that getting ones you don't want/expect can cause issues. For example, if you grab all the columns, then rely on the order in a loop to assign variables, then adding one in, or if the column orders change (seen it happen when restoring from a backup) it can throw everything off.

    This is also the same sort of reasoning why if you're doing an INSERT you should always specify the columns.

提交回复
热议问题