Skip to main content

7 posts tagged with "SQL audit"

View All Tags

Order by Random Optimization

· 5 min read
PawSQL Team
Optimize your SQL Queries by Clicks!

Problem

Functionrand(MySQL) or random(PostgreSQL) returns a random floating-point value in the range 0 to 1.0. It is useful to get a random sample of dataset using following query.

select * from orders order by rand() limit 1; 

This works fine if customer table is less than 10,000 rows. But when you have 1,000,000 rows, the overhead for sorting the rows becomes unacceptable. The reason is quiet clear: we sort all rows, but only keep one.

Avoid using STRAIGHT_JOIN

· 2 min read
PawSQL Team
Optimize your SQL Queries by Clicks!

Copyright © 2023 PawSQL

Problem Definition

STRAIGHT_JOIN is a table join method in MySQL that forces joining tables in the order defined, equivalent to an inner join in result. It gives developers some control over how the database executes the SQL query. However, it also loses out on join order optimizations by the optimizer, so should be used carefully based on the scenario. PawSQL provides a risk warning for statements using STRAIGHT_JOIN to avoid potential performance issues caused by it.

Taking the lineitem and orders tables in the tpch database as an example, the following query will join the lineitem table first and orders table second directly, indicating the database should take lineitem as the driving table and orders as the driven table for the join operation, without optimizing the table order.

SELECT *
FROM lineitem
STRAIGHT_JOIN orders ON lineitem.l_orderkey = orders.o_orderkey;

Avoid Using Natural Join

· 2 min read
PawSQL Team
Optimize your SQL Queries by Clicks!

Copyright © 2023 PawSQL

Definition

Natural join is a special type of equijoin that can be used with inner, outer and full joins. It automatically searches for all columns in both tables with the same name and type and performs an equijoin on those columns. Natural join can simplify the statement but implicit join conditions reduce code readability and understanding of relationships between tables, and are also prone to mistaken joins. PawSQL provides a risk warning for statements using natural join to avoid potential correctness issues caused by it.

Mixed Sort Directions Disable Index Usage

· 3 min read
PawSQL Team
Optimize your SQL Queries by Clicks!

Copyright © 2023 PawSQL

Problem Definition

For ORDER BY clauses, all expressions must be sorted in the same ASC or DESC direction to utilize indexes. If an ORDER BY statement uses different sort directions on multiple conditions, indexes cannot be used.

For example, creating an index on the lineitem table in TPCH:

create index l_partkey_suppkey_idx on lineitem(l_partkey, l_suppkey);