Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I learn to optimize SQL queries [closed]

I know how to write SQL queries and can get the results I need. But sometimes my queries are slow and I don't fully understand why.

What are some good resources for learning to write efficient queries and to optimize the queries I've already written?

like image 309
epotter Avatar asked Sep 17 '10 13:09

epotter


People also ask

How can I improve SQL query performance?

Popular methods for SQL table optimization and query speed improvement include: Providing a limited range of dates for time series data. Limiting the dataset in a subquery. Avoiding duplicate data.

What is used to Optimise performance of SQL queries?

Here are the 10 most effective ways to optimize your SQL queries. Indexing: Ensure proper indexing for quick access to the database. Select query: Specify the columns in SELECT query instead of SELECT* to avoid extra fetching load on the database. Running queries: Loops in query structure slows the sequence.


2 Answers

I would say the main things are:

  • Understand the set-based nature of SQL by reading platform-neutral books such as Celko's; this will help you avoid making newbie mistakes, like using cursors (or other iterative approaches) where they are not needed.
  • Learn the basics of normalization and when to denormalize; efficient queries start with well-organized data.
  • Understand where indexes can be helpful and where they can't; e.g., grasp how the cardinality of your data affects index efficiency, what SARGable queries are, and when to use multi-column indexes.
  • Learn how to use EXPLAIN PLAN or its equivalent for your platform; by observing how your query is being compiled and the resources it is consuming, you will better understand the bottlenecks.
  • Learn platform-specific methods such as indexed/materialized views, full text indexing, and methods for paging and dealing with hierarchical data.
like image 93
D'Arcy Rittich Avatar answered Oct 11 '22 18:10

D'Arcy Rittich


For MySQL specific information, chapter 7 of the reference manual is all about optimization. § 7.3, in particular, covers MySQL statement optimization. The PostgreSQL wiki similarly documents optimizing specifically for that RDBMS. Microsoft's "How To: Optimize SQL Queries" is retired; I'm not certain if there's a more recent document. Oracle has a couple documents on query optimization for the various versions.

like image 40
outis Avatar answered Oct 11 '22 19:10

outis