Astronaut loading animation Circular loading bar

Try : Insurtech, Application Development

AgriTech(1)

Augmented Reality(20)

Clean Tech(7)

Customer Journey(16)

Design(39)

Solar Industry(7)

User Experience(62)

Edtech(10)

Events(34)

HR Tech(3)

Interviews(10)

Life@mantra(11)

Logistics(5)

Strategy(17)

Testing(9)

Android(48)

Backend(32)

Dev Ops(8)

Enterprise Solution(28)

Technology Modernization(4)

Frontend(29)

iOS(43)

Javascript(15)

AI in Insurance(36)

Insurtech(63)

Product Innovation(54)

Solutions(21)

E-health(11)

HealthTech(23)

mHealth(5)

Telehealth Care(4)

Telemedicine(5)

Artificial Intelligence(139)

Bitcoin(8)

Blockchain(19)

Cognitive Computing(7)

Computer Vision(8)

Data Science(17)

FinTech(51)

Banking(7)

Intelligent Automation(27)

Machine Learning(47)

Natural Language Processing(14)

expand Menu Filters

Top 10 SQL Query Optimization Tips to Improve Database Performance

5 minutes, 18 seconds read

SQL Query optimization is a process of writing thoughtful SQL queries to improve database performance. During development, the amount of data accessed and tested is less. Hence, developers get a quick response to the queries they write. But the problem starts when the project goes live and enormous data starts flooding the database. Such instances slow down SQL queries response drastically and create performance issues.

When working with large-scale data, even the most minor change can have a dramatic impact on performance.

SQL performance tuning can be an incredibly difficult task. Even a minor change can have a dramatic impact on performance. Here are the 10 most effective ways to optimize your SQL queries. 

  1. Indexing: Ensure proper indexing for quick access to the database.
  2. Select query: Specify the columns in SELECT query instead of SELECT* to avoid extra fetching load on the database.
  3. Running queries: Loops in query structure slows the sequence. Thus, avoid them.
  4. Matching records: Use EXITS() for matching if the record exists.
  5. Subqueries: Avoid correlated sub queries as it searches row by row, impacting the speed of SQL query processing.
  6. Wildcards: Use wildcards (e.g. %xx%) wisely as they search the entire database for matching results.
  7. Operators: Avoid using function at RHS of the operator.
  8. Fetching data: Always fetch limited data.
  9. Loading: Use a temporary table to handle bulk data.
  10. Selecting Rows: Use the clause WHERE instead of HAVING for primary filters.

SQL Query Optimization Tips with Examples

Tip 1: Proper Indexing

An index is a data structure that improves the speed of data retrieval operations on a database table. A unique index creates separate data columns without overlapping each other. Proper indexing ensures quicker access to the database, i.e. you’ll be able to select or sort rows faster. The following diagram explains the basics of indexing while structuring tables.

TIP 2: Use SELECT <columns> instead of SELECT *

Specify the columns in the SELECT clause instead of using SELECT *. The unnecessary columns place extra load on the database, which slows down not just the single SQL, but the whole system.

Inefficient

SELECT * FROM employees

This query fetches all the data stored in the “employees” table such as phone number, activity dates, notes from sales, etc. which might not be required for a particular scenario.

Efficient

SELECT first_name, last_name, mobile, city, state FROM employees

This query will fetch only selected columns.

Tip 3: Avoid running queries in a loop

Coding SQL queries in loops slows down the entire sequence. Instead of writing a query that runs in a loop, you can use bulk insert and update depending on the situation. Suppose there are 1000 records. Here, the query will execute 1000 times.

Inefficient

for ($i = 0; $i < 10; $i++) {  
  $query = “INSERT INTO TBL (A,B,C) VALUES . . . .”;  
  $mysqli->query($query);  
  printf (“New Record has id %d.\ “, $mysqli->insert_id);
}

Efficient

INSERT INTO TBL (A,B,C) VALUES (1,2,3), (4,5,6). . . .

Tip 4: Does My record exists?

Normally, developers use EXITS() or COUNT() queries for matching a record entry. However, EXIT() is more efficient as it will exit as soon as finding a matching record; whereas, COUNT() will scan the entire table even if the record is found in the first row.

Inefficient

IF (SELECT COUNT(1) FROM EMPLOYEES WHERE FIRSTNAME LIKE ‘%JOHN%’) > 0 PRINT ‘YES’

Efficient

IF EXISTS(SELECT FIRSTNAME FROM EMPLOYEES WHERE FIRSTNAME LIKE ‘%JOHN%’)
PRINT ‘YES’

Tip 5: A big NO for correlated subqueries

A correlated subquery depends on the parent or outer query. Since it executes row by row, it decreases the overall speed of the process.

Inefficient

SELECT c.Name, c.City,(SELECT CompanyName FROM Company WHERE ID = c.CompanyID) AS CompanyName FROM Customer c

Here, the problem is — the inner query is run for each row returned by the outer query. Going over the “company” table again and again for every row processed by the outer query creates process overhead. Instead, for SQL query optimization, use JOIN to solve such problems.

Efficient

SELECT c.Name, c.City, co.CompanyName FROM Customer c LEFT JOIN Company co   ON c.CompanyID = co.CompanyID

Tip 6: Use wildcard characters wisely

Wildcard characters can be either used as a prefix or a suffix. Using leading wildcard (%) in combination with an ending wildcard will search all records for a match anywhere within the selected field.

Inefficient

Select name from employees where name like ‘%avi%’

This query will pull the expected results of Avishek, Avinash, Avik and so on . However, it will also pull unexpected results, such as David, Xavier, Davin.    

Efficient

Select name from employees where name like ‘avi%’.

This query will pull only the expected results of Avishek, Avinash, Avik and so on. 

Tip 7: Avoid using SQL function on the RHS of the operator

Often developers use functions or methods with their SQL queries. 

Inefficient

Select * from Customer where YEAR(AccountCreatedOn) == 2005 and  MONTH(AccountCreatedOn) = 6

Note that even though AccountCreatedOn has an index, the above query changes the WHERE clause in such a way that this index cannot be used anymore.

Efficient

Select * From Customer Where AccountCreatedOn between ‘6/1/2005’ and ‘6/30/2005’

Tip 8: Always fetch limited data and target accurate results

Lesser the data retrieved, the faster the query will run. Rather than applying too many filters on the client-side, filter the data as much as possible at the server. This limits the data being sent on the wire and you’ll be able to see the results much faster.

Tip 9: Drop index before loading bulk data

If you want to insert thousands of rows in an online system, use a temporary table to load data. Ensure that this temporary table does not have any index. Since moving data from one table to another is much faster than loading them from an external source; you can now drop indexes on your primary table, move data from temporary to the final table, and finally recreate the indexes.

Tip 10: Use WHERE instead of HAVING

HAVING clause filters the rows after all the rows are selected. It is just like a filter. Do not use the HAVING clause for any other purposes. 

In the SQL Order of Operations, HAVING statements are calculated after WHERE statements. Therefore, executing the WHERE query is faster.

Hope you enjoyed reading these tips for SQL query optimization. If you have any questions, feel free to drop a comment or write to us at hello@mantralabsglobal.com.

You can learn more about SQL queries and syntax at W3Schools tutorial.

About Author: Avishek Kumar Singh is a Senior Tech Lead at Mantra Labs —  a leading application development service provider in insurtech and e-commerce domains. He has years of experience in developing robust web and mobile applications for enterprises.

Suggest reading – LAMP/MEAN Stack: Business and Developer Perspective

Common FAQs

What is SQL optimization?

SQL optimization is a process of using SQL queries in the best possible way to get accurate and fast database results. The most common database queries are INSERT, SELECT, UPDATE, DELETE, and CALL. These are coupled with subqueries to filter the results. This is where people need to think of optimization to get accurate results with fewer resources and improve database performance.

What is SQL query tuning?

SQL optimization is also known as SQL query tuning. Basically, it is a process of smartly using SQL queries to increase the speed of fetching data and improve overall database performance.

What are the different query optimization techniques?

There are two most common query optimization techniques – cost-based optimization and rule (logic) based optimization. For large databases, a cost-based query optimization technique is useful as it table join methods to deliver the required output. Rule-based optimization combines two or more queries based on relational expressions. The following example illustrates rule-based query optimization.
rule-based query optimization

Cancel

Knowledge thats worth delivered in your inbox

Platform Engineering: Accelerating Development and Deployment

The software development landscape is evolving rapidly, demanding unprecedented levels of speed, quality, and efficiency. To keep pace, organizations are turning to platform engineering. This innovative approach empowers development teams by providing a self-service platform that automates and streamlines infrastructure provisioning, deployment pipelines, and security. By bridging the gap between development and operations, platform engineering fosters standardization, and collaboration, accelerates time-to-market, and ensures the delivery of secure and high-quality software products. Let’s dive into how platform engineering can revolutionize your software delivery lifecycle.

The Rise of Platform Engineering

The rise of DevOps marked a significant shift in software development, bringing together development and operations teams for faster and more reliable deployments. As the complexity of applications and infrastructure grew, DevOps teams often found themselves overwhelmed with managing both code and infrastructure.

Platform engineering offers a solution by creating a dedicated team focused on building and maintaining a self-service platform for application development. By standardizing tools and processes, it reduces cognitive overload, improves efficiency, and accelerates time-to-market.  

Platform engineers are the architects of the developer experience. They curate a set of tools and best practices, such as Kubernetes, Jenkins, Terraform, and cloud platforms, to create a self-service environment. This empowers developers to innovate while ensuring adherence to security and compliance standards.

Role of DevOps and Cloud Engineers

Platform engineering reshapes the traditional development landscape. While platform teams focus on building and managing self-service infrastructure, application teams handle the development of software. To bridge this gap and optimize workflows, DevOps engineers become essential on both sides.

Platform and cloud engineering are distinct but complementary disciplines. Cloud engineers are the architects of cloud infrastructure, managing services, migrations, and cost optimization. On the other hand, platform engineers build upon this foundation, crafting internal developer platforms that abstract away cloud complexity.

Key Features of Platform Engineering:

Let’s dissect the core features that make platform engineering a game-changer for software development:

Abstraction and User-Friendly Platforms: 

An internal developer platform (IDP) is a one-stop shop for developers. This platform provides a user-friendly interface that abstracts away the complexities of the underlying infrastructure. Developers can focus on their core strength – building great applications – instead of wrestling with arcane tools. 

But it gets better. Platform engineering empowers teams through self-service capabilities.This not only reduces dependency on other teams but also accelerates workflows and boosts overall developer productivity.

Collaboration and Standardization

Close collaboration with application teams helps identify bottlenecks and smooth integration and fosters a trust-based environment where communication flows freely.

Standardization takes center stage here. Equipping teams with a consistent set of tools for automation, deployment, and secret management ensures consistency and security. 

Identifying the Current State

Before building a platform, it’s crucial to understand the existing technology landscape used by product teams. This involves performing a thorough audit of the tools currently in use, analyzing how teams leverage them, and identifying gaps where new solutions are needed. This ensures the platform we build addresses real-world needs effectively.

Security

Platform engineering prioritizes security by implementing mechanisms for managing secrets such as encrypted storage solutions. The platform adheres to industry best practices, including regular security audits, continuous vulnerability monitoring, and enforcing strict access controls. This relentless vigilance ensures all tools and processes are secure and compliant.

The Platform Engineer’s Toolkit For Building Better Software Delivery Pipelines

Platform engineering is all about streamlining and automating critical processes to empower your development teams. But how exactly does it achieve this? Let’s explore the essential tools that platform engineers rely on:

Building Automation Powerhouses:

Infrastructure as Code (IaC):

CI/CD Pipelines:

Tools like Jenkins and GitLab CI/CD are essential for automating testing and deployment processes, ensuring applications are built, tested, and delivered with speed and reliability.

Maintaining Observability:

Monitoring and Alerting:

Prometheus and Grafana is a powerful duo that provides comprehensive monitoring capabilities. Prometheus scrapes applications for valuable metrics, while Grafana transforms this data into easy-to-understand visualizations for troubleshooting and performance analysis.

All-in-one Monitoring Solutions:

Tools like New Relic and Datadog offer a broader feature set, including application performance monitoring (APM), log management, and real-time analytics. These platforms help teams to identify and resolve issues before they impact users proactively.

Site Reliability Tools To Ensure High Availability and Scalability:

Container Orchestration:

Kubernetes orchestrates and manages container deployments, guaranteeing high availability and seamless scaling for your applications.

Log Management and Analysis:

The ELK Stack (Elasticsearch, Logstash, Kibana) is the go-to tool for log aggregation and analysis. It provides valuable insights into system behavior and performance, allowing teams to maintain consistent and reliable operations.

Managing Infrastructure

Secret Management:

HashiCorp Vault protects secretes, centralizes, and manages sensitive data like passwords and API keys, ensuring security and compliance within your infrastructure.

Cloud Resource Management:

Tools like AWS CloudFormation and Azure Resource Manager streamline cloud deployments. They automate the creation and management of cloud resources, keeping your infrastructure scalable, secure, and easy to manage. These tools collectively ensure that platform engineering can handle automation scripts, monitor applications, maintain site reliability, and manage infrastructure smoothly.

The Future is AI-Powered:

The platform engineering landscape is constantly evolving, and AI is rapidly transforming how we build and manage software delivery pipelines. The tools like Terraform, Kubecost, Jenkins X, and New Relic AI facilitate AI capabilities like:

  • Enhance security
  • Predict infrastructure requirements
  • Optimize resource security 
  • Predictive maintenance
  • Optimize monitoring process and cost

Conclusion

Platform engineering is becoming the cornerstone of modern software development. Gartner estimates that by 2026, 80% of development companies will have internal platform services and teams to improve development efficiency. This surge underscores the critical role platform engineering plays in accelerating software delivery and gaining a competitive edge.

With a strong foundation in platform engineering, organizations can achieve greater agility, scalability, and efficiency in the ever-changing software landscape. Are you ready to embark on your platform engineering journey?

Building a robust platform requires careful planning, collaboration, and a deep understanding of your team’s needs. At Mantra Labs, we can help you accelerate your software delivery. Connect with us to know more. 

Cancel

Knowledge thats worth delivered in your inbox

Loading More Posts ...
Go Top
ml floating chatbot