How to avoid “OR” in MariaDB for better performance?

Avoiding the use of the “OR” operator in MariaDB can help improve query performance by reducing the number of rows that need to be scanned and filtered. Here are some strategies to avoid using “OR” in your MariaDB queries:

  1. Use the “IN” operator instead of “OR” when filtering by multiple values. For example, instead of “WHERE name = ‘John’ OR name = ‘Mary'”, use “WHERE name IN (‘John’, ‘Mary’)”. This can be more efficient because the database can use an index on the “name” column to quickly find the matching rows.
  2. Use boolean algebra to rewrite complex conditions that use “OR” into simpler conditions that use “AND”. For example, instead of “WHERE (name = ‘John’ OR age > 30) AND gender = ‘male'”, use “WHERE name = ‘John’ AND gender = ‘male’ OR age > 30 AND gender = ‘male'”. This can be more efficient because the database can use indexes on the “name” and “gender” columns to quickly filter rows before applying the more expensive “age” condition.
  3. Use subqueries to split complex conditions that use “OR” into simpler queries that each filter by a single value. For example, instead of “WHERE name = ‘John’ OR (age > 30 AND gender = ‘male’)”, use “WHERE name = ‘John’ OR (SELECT 1 FROM users WHERE age > 30 AND gender = ‘male’ AND name = ‘John’ LIMIT 1)”. This can be more efficient because the subquery can use indexes to quickly filter rows, and the main query can use an index on the “name” column to quickly find matching rows.
  4. Use UNION queries to combine the results of multiple simpler queries. For example, instead of “SELECT * FROM users WHERE name = ‘John’ OR name = ‘Mary'”, use “SELECT * FROM users WHERE name = ‘John’ UNION SELECT * FROM users WHERE name = ‘Mary'”. This can be more efficient because each query can use an index on the “name” column to quickly find matching rows, and the UNION operator can eliminate duplicates.

By using these strategies, you can avoid using “OR” in your MariaDB queries and improve their performance.

About Shiv Iyer 422 Articles
Open Source Database Systems Engineer with a deep understanding of Optimizer Internals, Performance Engineering, Scalability and Data SRE. Shiv currently is the Founder, Investor, Board Member and CEO of multiple Database Systems Infrastructure Operations companies in the Transaction Processing Computing and ColumnStores ecosystem. He is also a frequent speaker in open source software conferences globally.