O LinkedIn e terceiros usam cookies essenciais e não essenciais para fornecer, proteger, analisar e aprimorar nossos Serviços, e para exibir anúncios relevantes (inclusive anúncios profissionais e com vaga) dentro e fora do LinkedIn. Saiba mais na nossa Política de Cookies.
Selecione Aceitar para consentir ou Rejeitar para recusar cookies não essenciais para este uso. Você pode atualizar suas opções nas suas configurações quando quiser.
As consultas SQL são essenciais para recuperar e manipular dados de bancos de dados, mas também podem afetar o desempenho e a eficiência de seus aplicativos de BI. Se você deseja otimizar suas consultas SQL e reduzir o tempo de execução e o consumo de recursos, aqui estão algumas dicas que você pode seguir.
Principais especialistas neste artigo
Selecionados pela comunidade a partir de 46 contribuições. Saiba mais
Os índices são estruturas de dados que ajudam a acelerar a pesquisa e a recuperação de dados de tabelas. Eles agem como ponteiros que direcionam o mecanismo de banco de dados para o local dos dados desejados, sem examinar a tabela inteira. Você pode criar índices em colunas que são usadas com frequência em consultas, como chaves primárias, chaves estrangeiras ou colunas com alta cardinalidade (valores únicos). No entanto, tenha cuidado para não usar índices em excesso, pois eles também podem retardar as operações de inserção, exclusão e atualização e ocupar espaço de armazenamento extra.
Agradecemos o aviso. Você não verá mais esta contribuição
Rather than writing complex queries containing multiple references to tables and/or subqueries and/or joins on the return value of functions (negating any indexing on the columns passed).
Create temporary tables with clustered indexes (testing to ensure that the create time is less than the reduced execution time), and use functions at the time of inserting.
Even if not optimal, the resultant code will be far easier to read and maintain.
Agradecemos o aviso. Você não verá mais esta contribuição
1. Minimize the use of wildcard characters
2. Increase Query Performance with Indexes
3. Use appropriate data types:
4. Avoid using SELECT *
5. Use subqueries judiciously: Subqueries can be useful in SQL queries, but they can also slow down query performance. If possible, try to use joins instead of subqueries.
6. Use EXPLAIN to analyze queries
7. Optimize database design
Agradecemos o aviso. Você não verá mais esta contribuição
using indexes can also help in saving memory and performance improvement during query execution as it adds a pointer to the actual data set rather than adding the actual data every time it runs when it is used wisely. So when you have key columns at your disposal use them to relate the tables and get the job done. however too much use of indices can hamper the operation and increase the system overhead.
Agradecemos o aviso. Você não verá mais esta contribuição
While using indexes speeds up query performance, it is necessary to know the type of index to use depending on the type of query and data structure.
1. The B-Tree index can be used for range-based searches.
2. Bitmap indexes can be used for categorical data or columns with few unique values.
3. Partial indexes can improve the query performance when we use a specific subset of data.
4. Full-text indexes can be used to support text-based searches.
These are some of the many types, but it is essential to understand the pros and cons of each index type before choosing an index type.
Some databases support adaptive indexing where the system dynamically creates/improves index based on patterns
Agradecemos o aviso. Você não verá mais esta contribuição
Nem todas as consultas SQL são criadas iguais. Alguns são eficientes, rápidos e devolvem o que você precisa. Outros são lentos, consomem muitos recursos e podem retornar mais dados do que o necessário. Para otimizar as consultas SQL, você deve se concentrar em selecionar apenas as colunas necessárias, evitar o uso de funções em predicados, limitar o uso de subconsultas e usar uniões em vez de junções sempre que possível.
Agradecemos o aviso. Você não verá mais esta contribuição
Think of indexes like a book's table of contents - they help find information quickly. Ensure columns used frequently in WHERE clauses or JOIN conditions have indexes.
Agradecemos o aviso. Você não verá mais esta contribuição
Indexes can significantly speed up data retrieval. Ensure that columns used in WHERE clauses, JOIN conditions, and ORDER BY clauses are indexed appropriately.
Agradecemos o aviso. Você não verá mais esta contribuição
To make informed decisions, we need to keep Optimizing SQL queries and it is crucial for improving the performance of database operations.
One fundamental approach is to ensure that your database tables are properly indexed, as indexes significantly speed up data retrieval. Analyze the specific requirements of your queries and create indexes on columns frequently used in WHERE clauses or join conditions. Additionally, strive to write efficient and concise queries by selecting only the necessary columns and using appropriate filtering conditions. Minimize the use of SELECT *, as it can retrieve more data than needed. Utilizing proper normalization techniques in database design can also enhance performance by reducing redundant data.
Ao escrever consultas SQL, você deve selecionar apenas as colunas necessárias para sua análise ou relatório e evitar usar o asterisco (*) para selecionar todas as colunas. Dessa forma, você pode reduzir a quantidade de dados transferidos do banco de dados para sua ferramenta de BI e melhorar o tempo de resposta e a largura de banda da rede. Você também pode usar aliases para renomear as colunas para clareza e legibilidade.
Agradecemos o aviso. Você não verá mais esta contribuição
It's a very common practice to use select * from table. However it's good for beginners ad definitelybit would work for smaller datasets and would not create much harm. However when using it in large Database, we have to be careful. Unnecessary use of * would call for all the column and all the records we want to avoid it in some scenarios. So instead of select * use select colour_name1, column_name2 from table
Agradecemos o aviso. Você não verá mais esta contribuição
SQL queries depends on our requirements and type of dataset. I'll provide few tips for optimising SQL queries.
1. Be Selective with Columns:
Resist the urge to use SELECT *. Instead, be specific about the columns you need. This not only reduces data transfer but also makes query execution more efficient.
2. Choose Joins Wisely:
JOIN operations are powerful but can be resource-intensive, especially with large tables. Optimize performance by selecting the right JOIN type (INNER, LEFT, RIGHT) based on your specific needs.
Agradecemos o aviso. Você não verá mais esta contribuição
In the realm of SQL query optimization, the principle of "less is more" holds immense significance. Rather than opting for the wildcard (*) to select all columns, it's wise to meticulously list only those columns essential for your specific analysis or reporting needs. This disciplined approach has multifaceted advantages.
Selecting only the columns you need minimizes the volume of data transferred from the database to your BI tool. This efficiency is particularly pronounced when dealing with large datasets. By transmitting only the pertinent information, you reduce the strain on network bandwidth, ultimately leading to a more streamlined and responsive data retrieval process.
Agradecemos o aviso. Você não verá mais esta contribuição
When you're using SQL queries, it's better to pick only the columns you really need for your report or analysis. Don't select all columns using *.
This method saves time and space because it transfers less data from the database to your BI tool. Overall, you can expect to see improved query performance and better downstream performances.
Agradecemos o aviso. Você não verá mais esta contribuição
Use EXISTS and IN: When checking for the existence of a subquery, consider using EXISTS instead of IN. EXISTS is often more efficient.
Avoid SELECT * Only retrieve the columns you need rather than using SELECT * to fetch all columns. This reduces data transfer and improves performance.
Agradecemos o aviso. Você não verá mais esta contribuição
Most times, people usually use the SELECT * FROM Table quiery to fetch all columns with the idea that they might need to use some of the specified columns in the future.
This practice is not ideal. Instead of fetching all columns, specify only the columns you require. This reduces the workload on the database.
As junções são operações SQL poderosas que permitem combinar dados de várias tabelas com base em uma coluna ou condição comum. No entanto, se você usar muitas associações ou ingressar em tabelas grandes, também poderá aumentar a complexidade e o custo de suas consultas. Para otimizar suas junções, é melhor usar junções internas em vez de junções externas, pois elas são mais rápidas e eficientes. Além disso, junte tabelas em colunas indexadas, pois isso melhora o desempenho e a precisão da operação de junção. Também é importante unir tabelas na ordem de seu tamanho, do menor para o maior, pois isso reduz o número de linhas que precisam ser processadas. Por fim, use junções explícitas em vez de junções implícitas, pois elas são mais legíveis e menos propensas a erros.
Agradecemos o aviso. Você não verá mais esta contribuição
Joins are very effective operations in sql but at the same time they are very costly. So while using joins we must be careful of what results are we looking for. We must carefully choose the type of join we are going to use according to the action we are about to perform. In most cases inner join serves well but it's not true everytime . So we have to be mindful
Agradecemos o aviso. Você não verá mais esta contribuição
We all have been using joins but probably did not think much about optimizing joins to improve query performance. One thing I will strongly suggest is to evaluate the order in which you join the tables. Begin with the joins that will yield a smaller result. If you have not yet understood the data quite well and are joining the data just for the same reason then please consider a query optimizer. Some DB systems have optimizers that could be of great help.
Another way to optimize a query would be to filter the query BEFORE making the joins. This will be really helpful to get results faster and you will be billed less!
Agradecemos o aviso. Você não verá mais esta contribuição
Proper JOINs: Choose the appropriate type of JOIN (INNER, LEFT, RIGHT) based on your actual requirements. This can impact both result accuracy and query speed.
Filtros e condições são cláusulas SQL que permitem definir os critérios para selecionar ou excluir dados de suas consultas. Essas cláusulas podem ajudá-lo a refinar o escopo e o tamanho de seus dados, bem como melhorar a precisão e a relevância de seus resultados. Por exemplo, você pode usar a cláusula WHERE para filtrar linhas com base em uma condição ou expressão, HAVING para filtrar grupos com base em uma função ou expressão agregada, LIMIT para limitar o número de linhas retornadas por uma consulta, BETWEEN para filtrar valores dentro de um intervalo especificado, IN para filtrar valores dentro de uma lista especificada e LIKE para filtrar valores que correspondam a um padrão.
Agradecemos o aviso. Você não verá mais esta contribuição
Instead of applying operations on large set of data it is a good option to apply some filters using where clause having etc LIMIT, IN, BETWEEN. LIKE can be used to match wildcards. It would reduce the data overhead and queries will return faster as they are more optimized in comparison to the one when we see applying operations on all datasets.
Agradecemos o aviso. Você não verá mais esta contribuição
To improve query performance, restrict the data retrieved by specifying particular columns rather than employing 'SELECT *'. Moreover, utilize the WHERE clause to promptly exclude unnecessary rows at the outset of the query.
Agradecemos o aviso. Você não verá mais esta contribuição
Os filtros e condições podem ser usados para otimizar consultas de várias maneiras. Por exemplo, se uma consulta só precisa de um subconjunto dos dados, é possível usar um filtro para reduzir a quantidade de dados que precisam ser processados.
Outra forma de otimizar consultas é usando condições para evitar a necessidade de processar registros que não correspondem a um determinado critério. Por exemplo, se uma consulta só precisa de registros onde o valor da venda é maior que R$ 1.000,00, é possível usar a condição valor > 1000 para evitar processar registros onde o valor da venda é menor ou igual a R$ 1.000,00.
Agradecemos o aviso. Você não verá mais esta contribuição
Careful use of GROUP BY:Be mindful when using GROUP BY, and ensure that the selected columns in the SELECT statement align with the GROUP BY clause. Aggregating functions (COUNT, SUM, AVG, etc.) should be used appropriately.
Optimize Subqueries:If possible, try to rewrite subqueries as JOINs. Subqueries can be performance bottlenecks.
Agradecemos o aviso. Você não verá mais esta contribuição
Utilizing filters and appropriate conditions can improve query performance.
Ensure WHERE clauses are as specific as possible. Use =, <>, >, < instead of functions or calculations in WHERE clauses.
Subconsultas e CTEs (Expressões de tabela comuns) são técnicas SQL que ajudam a simplificar e organizar consultas, evitando repetir o mesmo código ou lógica. As subconsultas podem ser usadas para aninhar uma consulta em outra, geralmente na cláusula SELECT, FROM ou WHERE. Por exemplo, uma subconsulta pode calcular um valor agregado ou uma coluna derivada que pode ser usada na consulta principal. As CTEs também podem ser usadas para definir uma tabela ou exibição temporária que pode ser referenciada na mesma consulta, geralmente com uma cláusula WITH. Isso é útil para criar consultas recursivas ou funções de janela que podem ser usadas na consulta principal.
A otimização de consultas SQL é essencial para aplicativos de BI. Seguindo essas dicas, você pode escrever consultas SQL mais eficientes e eficazes que economizarão tempo e recursos.
Agradecemos o aviso. Você não verá mais esta contribuição
It is a good practice to use sub queries in a nested format in a large query in an ordered manner. While organizing these queries pay special attention on the way the information is retrieved. Common table expression can be reused for creation of views which are frequently called upon by calling recursion
Este é um espaço para compartilhar exemplos, histórias ou insights que não se encaixam em nenhuma das seções anteriores. O que mais gostaria de acrescentar?
Agradecemos o aviso. Você não verá mais esta contribuição
Everything depends on requirements. Sometimes, a SUBQUERY is more suitable than a CTE.
Selecting specific columns also depends on the requirements, but I prefer using SELECT * FROM table with a LIMIT clause to quickly understand the data.
However, I usually handle most of the filtration in the first CTE and then proceed with further analysis.
Agradecemos o aviso. Você não verá mais esta contribuição
Like all code, SQL has competing constraints and you need to consciously choose what you're optimizing FOR.
Are you trying to make it run fastest? Make it more human-readable? Make it more reliable on messy data?
These will often take your SQL in different directions, so intentionality with WHAT you're trying to optimize is key.
Agradecemos o aviso. Você não verá mais esta contribuição
Efficient indexing on frequently queried columns accelerates data retrieval. Select only necessary columns and rows to minimize data returned, avoiding SELECT * for better efficiency. Prioritize INNER JOINs over OUTER JOINs and utilize JOINs instead of subqueries when possible. Construct well-organized WHERE clauses, placing the most selective conditions first. Regularly update statistics, utilize stored procedures, and maintain a normalized database design. Be cautious with subqueries and consider UNION ALL instead of UNION for improved performance. Evaluate query execution plans with EXPLAIN and employ database sharding for large datasets. Regular maintenance and connection pooling further optimize SQL performance.
Agradecemos o aviso. Você não verá mais esta contribuição
Optimizing SQL queries means making them faster and efficient:
Indexing: Like a book's contents, use indexes for quicker data retrieval.
Selective Retrieval: Fetch specific columns and filter using WHERE clauses.
*Avoid SELECT : Specify needed columns to reduce workload.
Smart Joins: Use necessary joins to avoid slowing queries.
Refine WHERE Clauses: Be specific and avoid complex functions.
Mind Functions: Functions on columns can hinder index use.
Database Design: Normalize tables for better performance.
Update Stats: Helps query optimizer generate efficient plans.
Use EXPLAIN: Analyze query plans to fix issues.
Test and Monitor: Regularly check performance and optimize.
Agradecemos o aviso. Você não verá mais esta contribuição
To optimize SQL queries,
Start with indexing; modern databases, like SQL Server 2016+, support column store indexes for efficient aggregation queries whereas regular indexes aid data retrieval based on conditions.
Next check the query execution plan for optimization insights, focusing on joins, conditions, and subqueries.
Materialized views can assist in some cases.
For extensive data, consider partitioning.
Distributed databases and data warehouses (e.g., Redshift, Snowflake) are options for large workloads, but assess the necessity. For most small to medium analytics needs, a regular SQL database suffices.
Explore creating smaller data marts or using the Lambda architecture for improved reporting and dashboarding requirements.
Agradecemos o aviso. Você não verá mais esta contribuição
It's not magical, a performatic query requires a good knowledge about how DBMS works and what data are loaded and organized.
Data model, MER, brings lights about data and a explain tool shows what kind of operations is done by DBMS to evaluate a query.
Every DBMS has your way to deal with queries, I remember a time where working with a huge number of lines and joins on Teradata the firsts explain shows time to evaluate query that my 4 generation will see, and, after tuning and changing some joins order the results come in seconds. I frequently use a handsome experience to write queries and explain tool to validate.
Agradecemos o aviso. Você não verá mais esta contribuição
Boas práticas em consultas SQL são essenciais para garantir eficiência, segurança e manutenibilidade em sistemas de gerenciamento de bancos de dados. Manter consultas simples e compreensíveis facilita a manutenção do código. Regularmente, revisar e refatorar consultas complexas evita gargalos e problemas de escalabilidade. Comentários claros e documentação são boas práticas para facilitar a compreensão futura. Em resumo, seguir boas práticas em consultas SQL promove desempenho eficiente, segurança robusta e manutenibilidade duradoura nos sistemas de banco de dados.
Agradecemos o aviso. Você não verá mais esta contribuição
Refine Logic: Restructure or break down queries for efficiency.
Limit Wildcards: Use them sparingly, especially at the start in LIKE clauses.
Spare Temporary Tables: Use them judiciously to avoid overhead.
Avoid Functions on Indexes: Prevents optimal index use.
Analyze Execution Plans: Helps identify performance bottlenecks.
Regularly Update Statistics: Keeps database optimizer informed.
Minimize Network Traffic: Reduce data transfer in distributed databases.
Optimize Data Types/Sizes: Choose appropriate types for faster processing
Agradecemos o aviso. Você não verá mais esta contribuição
Enhance subquery efficiency by revising correlated or nested queries, exploring alternative methods like JOINs for better performance.
Continuously track query performance through profiling tools and database statistics, pinpointing slower queries, and scrutinizing their execution plans to further fine-tune and optimize them.