SQL Query Optimization Techniques
The total process of selecting the most effective method of processing a SQL statement is known as query optimization. Because SQL is a non-procedural language, the optimizer can merge, restructure, and process data in whatever sequence it wants. Based on statistics acquired about the accessed data, the database optimizes each SQL statement.
1.
SELECT fields instead
of using SELECT *
Many SQL
developers use SELECT * (read as "select all") as a shortcut to query
all accessible data from a table when executing exploratory queries. However,
if a table has a lot of fields and rows, it puts a strain on database resources
by searching a lot of data that isn't needed.
Using
the SELECT statement, you may direct the database to only query the data you
need to suit your business needs. Here's an example of a business requirement
that asks for customer shipping addresses.
2.
Avoid SELECT DISTINCT
The
SELECT DISTINCT command is useful for removing duplicates from a query. To
create distinct results, SELECT DISTINCT GROUPs all fields in the query.
However, a significant amount of computing power is necessary to achieve this
goal. Furthermore, data can be clustered to the point where it is erroneous.
Select extra fields to create unique results instead of using SELECT
DISTINCT.
3.
Create joins with INNER JOIN (not WHERE)
4.
Use WHERE instead of HAVING to define filters
The
purpose of an efficient query is to retrieve only the records that are required
from the database. HAVING statements are calculated after WHERE statements,
according to the SQL Order of Operations. A WHERE statement is more efficient
if the goal is to filter a query based on conditions.
5.
Use wildcards at the end of a phrase only
Wildcards
are used to search plaintext data, such as cities or names, to provide the most
comprehensive search possible. However, the most comprehensive search is also
the most inefficient. When a
leading wildcard is combined with an ending wildcard, the database is tasked
with searching all records for a match anywhere inside the designated field.
6.
Use LIMIT to sample query results
By
utilizing a LIMIT statement before running a query for the first time, you can
ensure that the results will be desirable and relevant. (In some DBMS systems,
the terms TOP and LIMIT are interchangeable.) The LIMIT statement only returns
the provided number of records. By using a LIMIT statement, you can avoid
stressing the production database with a huge query only to discover that it
needs to be edited or refined later.

Comments
Post a Comment