سؤال

Possible Duplicate:
Which is faster/best? SELECT * or SELECT column1, colum2, column3, etc

I recall reading a number of years ago that in the scenario where you wanted to select everything from a MySQL table it was more efficient and better practice to specify every column rather than use the lazy and less-efficient SELECT * approach.

I am struggling to find any evidence of this online, so i'm not sure if it applies with newer versions of MySQL and PHP.

Would it be better to specify every column in my SELECT rather than using SELECT *?

SELECT * FROM golf_course WHERE id = 2;
هل كانت مفيدة؟

المحلول

Select * is inherently less efficient because the database has to look up the columns. Further if you have even one join you are sending unnecessary repeated data which is wasteful of database and network resourses, particularly if you do it on every query. Finally, select * doesn't specify the order of the columns, so if someone foolish drops and recreates the table with the columns in a different order, you may suddenly have your Social security number showing up in your first name column on the form or report. And if someone adds a column that you don't want displayed everywhere (say for auditing purposes or notes about the customer that you don't want the customer to ever see) you are in trouble. Further, if you do add columns, you need to determine where they should show up anyway and why not just have them willy nilly show up everywhere. Select * is an extremely bad SQL antipattern.

نصائح أخرى

Yes.

  • Your query will be easier to understand
  • You will only select the columns you need
  • If you specify all columns, it will be easier to remove those you don't want later but if you didn't and you want to do later, you will need to type all the columns
  • You'll be able to arrange the columns the way you want and reference them in your code even if more columns are added to the table later
  • You can easily add computation, concatenation
  • and more

Performance-wise, I am not sure

IMHO, calling a SELECT * will have to read all fields where are calling only the required fields will be more efficient. And when you are querying a larger database the performance may be affected using SELECT *

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top