How to optimize join query in mysql. *, `lookup_table`. 010s. In my first attempt, I was lazy and used implicit joins. Tip 7: MySQL Query Caching CREATE TABLE Growth. ON Growth (dataID, countryID); The SELECT query then arranges up to XX indicators in the results table, with XX unfortunately <10: SELECT. The query contains multiple subquery which is taking over 120s to execute. Jan 30, 2022 · I would also adjust and reverse the query to the smallest granular item The SHOWS table on the single date in the primary FROM position of the query. In MySQL 8. 2. May 16, 2022 · This article takes a look at a tutorial that explains how to optimize your MySQL server hosted on Alibaba cloud for speed and performance. Set up indexes on columns used in the WHERE clause, to speed up evaluation, filtering, and the final retrieval of results. key=a. It's also a bit Cost Estimation. sirno + sir. mysql> EXPLAIN <query> will show you the actually used fields ( key column in output) and the available indexes ( possible_keys output field). Please Help!! 10. For example you could put EXPLAIN before your select and see what the results is. | @@profiling |. An ORDER BY with and without LIMIT may return rows in different orders, as discussed in Section Chapter 8 Optimization. Jan 17, 2014 · Alas, doing conditional joins tends to result in very poor query performance. 9 Outer Join Optimization. id1, B. string_comment JOIN C ON E. id_job. Dec 10, 2010 · For other join types, the MySQL’s join optimizer calculates the order in which tables should be joined. fk_job) WHERE job. As of today, the best performance (for 1 million rows) has been: 1 - Adding an index on uri column. bfid) ) s ON (A. The first query is very slow to run (23 seconds), but removing just one field (Query 2) from the where clause causes the query to run in 0. The core logic of a database application is performed through SQL statements, whether issued directly through an interpreter or submitted behind the scenes through an API. The index entries act like pointers to the table rows, allowing the query to quickly determine which rows match a condition in the WHERE clause, and retrieve the other Apr 20, 2024 · Tip 4: Monitor the Fundamental Resources. id_job=job_application. Outer joins include LEFT JOIN and RIGHT JOIN . On the other hand, this would be a "covering" index for that specific query: Jun 4, 2021 · Here's the format of mysql code select a,b,c from table1 left join table2 on x=y left join table3 on m=n limit 100000, 10 I know know to optimize limit when I have a large offset. It can be used for a single-part or multiple-part index. C where t2. 3, “Optimizer Hints”. For example, MySQL is better at optimizing joins than subqueries, so if you find the load averages on your MySQL server hitting unacceptably high levels, examine your application code and try Oct 3, 2010 · 10. Instead, it is using idx_bucket, too. Enable query profiling to understand slow query stages. For your database to function well, you need to monitor the four indispensable resources that allow it to operate: CPU. Optimizing MySQL queries is like solving a puzzle. 9. Disk. D is null and t2a. MySQL implements an A LEFT. name = A. select d2. Jul 26, 2016 · If you want to optimize further, the next thing to do is to move the nlikes and date columns into the users_face table, then make the index on that table over the following columns in this order: (fb_id, token_valid, date, nlikes). When EXPLAIN is used with an explainable statement, MySQL displays information from the optimizer about the statement execution plan. 5 or even 5. The database has to perform string operations on each row, though it's possible MySQL is smart enough to use the index. Then you just join the other info onto that (or vice versa) – Strawberry. Sep 30, 2013 · Only in the second query does the WHERE clause get applied. Queries, in the form of SELECT statements, perform all the lookup operations in the database. id_type = t. You are searching for all People starting with "T" (the WHERE part) in book A. If your memory is running low, or if your disk is full, your database will be impacted no matter how optimized it is. For example: CREATE INDEX index1 ON newsletter_post (post_id); 2) USE only important columns for JOINS. 14 and later, this takes place during preparation rather than during the optimization phase, which helps in simplification of joins. I guess it's because of the 'Using temporary; Using filesort' in the explain of the query. id = meta. on m. With ~980 records in table A and 130. id_job DESC. key) LEFT JOIN d ON (d. countryName AS Country, 1. Option 2 - with inner join (faster but still too slow) inner join messageinfo m. created_at, nfr. Here's EXPLAIN EXTENDED output: Apr 24, 2020 · 1. 5 database at once, and this amount is expected to grow. The range access method uses a single index to retrieve a subset of table rows that are contained within one or several index value intervals. In some cases, MySQL may use an index to satisfy an ORDER BY clause and avoid the extra sorting involved in performing a filesort operation. From visits. status + r. I don't see any obvious way to make the unions faster, other than to suggest that the ID columns of all tables involved have an index on it. where A. 3 Optimizer Hints. 1, 5. Imagine you have two different phonebooks. The syntax of table_factor is extended in comparison with the SQL Standard. As you saw in your original query when removing the ORDER BY clause, the joining by itself is not a performance problem. INDEX(y) -- avoids sort, but does no filtering. Then you can skip the join in your query, and the sort order will be the order of the index, so that will be Sep 22, 2017 · I've included the actual queries and the EXPLAIN in 3 scenarios below. host. name = B. You’ve gone to the trace for that page in Retrace and you can see that it’s definitely a MySQL call that’s underperforming. string_comment JOIN B ON E. First, connect to your MySQL server as the root user: sudo mysql -u root -p. The syntax for expressing joins permits nested joins. FROM CountryData. 0. The following sections describe conditions under which the optimizer uses range access. SELECT m. To do that, I used INNER JOIN : 8. The query below works perfect by returning the Users who have made more comments than posts in the year 2010 and their counts. JOIN B join_specification as follows: Table B is set to depend on table A and all tables on which A depends. There are different reasons for that. It usually does a great job, but not all the time. EXPLAIN MySQL - using example in answer below. The best way to improve the performance of SELECT operations is to create indexes on one or more of the columns that are tested in the query. string_comment JOIN D ON E. Having date as a string introduces performance problems. Certain optimizations are applicable to comparisons that use the IN (or =ANY ) operator to test subquery results. uri. One way to get around this would be to wrap your original query in a subquery, and then order it: Sep 28, 2015 · An experienced database architect can often improve query performance by orders of magnitude through simple tweaks to the way queries are written. warehouseLocation, in that order. Jun 22, 2011 · There are always 2 things to consider when optimising queries: What indexes can be used (you may need to create indexes) How the query is written (you may need to change the query to allow the query optimser to be able to find appropriate indexes, and to not re-read data redundantly) Now the optimizer can rewrite the query as an inner join, like this: SELECT * FROM t1 JOIN t2 WHERE condition_1 AND condition_2. The EXPLAIN statement provides information about how MySQL executes statements: EXPLAIN works with SELECT , DELETE , INSERT , REPLACE, and UPDATE statements. The added flexibility may provide significant optimization opportunities. That said, you had a left and right join for the CF table, but you can't have both a cf=40 and cf IS NULL, so I simplified to just a left join on the ID AND 40 so if there IS a record in the CF table it only shows if it's value is 40 any other value would be ignored. First add an Index to tech. Indexes on the columns used in the join condition can dramatically speed up the query. Jun 24, 2021 · Prerequisites. Use x = ANY (table containing (1,2)) rather than x=1 OR x=2 . Feb 14, 2020 · How can I optimize this join query? how can I get the latest start_dt in this query? Is any way can make it faster to load and the start_dt is the latest one? If I delete the subquery for this case, I will get the record which the start_dt is not the latest one. ID IN(2,3,4) and so on Result. WHERE x > ORDER BY y. uuid, nf. Oct 22, 2010 · Short answer: Yes, customer_id should have index. We will cover essential aspects of database optimization, such as query optimization, strategic indexing, schema design, caching, configuration settings, and more. Add an additional index table2. 3 Optimizing Subqueries with the EXISTS Strategy. Aug 24, 2011 · Here is your original query: select t. Option 1 - basic select (very slow) UPDATE. 9, “Outer Join Optimization” , for further information and examples. Leave your ORM behind and get your hands dirty! Oct 27, 2011 · And if you do multiple LEFT JOINs, then you could (probably) separate them into different queries and this should make the application work a lot faster. To do this, change the LEFT JOIN on performance_schema. I hope this'd be helpful. 0 installed and configured; Access to the command prompt or command line; Fragmented database tables; Why Should You Optimize MySQL Tables? The main reason for an unoptimized MySQL table is frequently performed update and delete queries. FROM user. 2 Optimizing SQL Statements. id; This query works perfectly fine, but takes 50 minutes to run. May 23, 2018 · The other join is to make sure we get the notification's read_at time,so the follower knows if it was already read or not. username, auth. Another way to get fast updates is to delay updates May 29, 2015 · LEFT JOIN `job_application` ON (job. you can use left or inner join depending if you want to update columns to nulls) 8. From Shipper A. Jun 15, 2020 · any suggestion for the SQL to optimize this query? if I cancel " AND m. string_comment = A. This assumes the fields are small enough to fit (combined) into an index. bid = C. id = U. In this step, you’ll run the same query you ran in Step 3 one more time to check how query cache has optimized the performance of your MySQL server. LastName. It should ideally only take a few ms, specially with the indexes: Query: SELECT nf. deleted = 0. secret_word FROM user_auth_1000 auth LEFT JOIN user_meta_1000 meta ON auth. The optimizer makes decisions based on statistics and some fixed costs Consider having three tables: A, B and C and the following simple query: SELECT * FROM A LEFT JOIN ( SELECT * FROM B INNER JOIN C ON (B. Jun 12, 2019 · Step 5 — Testing Your MySQL Server with Query Cache Enabled. Jul 1, 2015 · 4. But I couldn' Jan 31, 2018 · How can i speed up the above update join query ? i was expecting about 1 hour on not-so powerful server, but 26 hours+ is too much. read_at. where exists (select 1. 2, “JOIN Clause” . string_comment FROM E JOIN A ON E. Feb 18, 2022 · And it is the notorious EAV pattern. id = user. user_id = user. The speed of the write depends on the amount of data being updated and the number of indexes that are updated. . 2 Optimizing UPDATE Statements. *, ( SELECT act_value FROM message_detail. Jan 3, 2013 · 1) LIKE Sallar Kaboli told you, you have to index your tables in columns that use in JOIN querys. This may give you additional details. C left join t2 t2a on t1. each queries individually takes less than 1 second to compute. Left Join Customer C A. Oct 3, 2010 · 10. BY does not match the index exactly, as long as all unused portions of the index and all extra ORDER BY columns are constants in the WHERE clause. uri = d2. This section discusses these optimizations, particularly with regard to the challenges that NULL values present. A rule of thumb is to have utmost a dozen joins for each query. from file_item p. A = t2. May 23, 2019 · I have one table with 100k+ rows and about 30 columns of which I can filter down to 3-rows (in this example) and then perform INNER JOIN s across 21 small lookup tables. Now the optimizer can use table t2 before table t1 if doing so would result in a better query plan. Left Join Order O A. . One multi-column index on sir. SELECT dataID, countryID, year, data. name, A. key) WHERE b Mar 18, 2017 · 1. WHERE message = m. uri, d2. This is quite fast because you have an index. May 16, 2024 · In this tutorial, you’ll learn how to improve MYSQL performance. Changes to this variable affect execution of all subsequent queries; to affect one query differently from another, it is necessary to change optimizer_switch before each one. The most optimal query can be determined by if the columns compared between the two tables are NULLable (IE: if the values of specific_product_id in either table can be NULL ). specialty_id = specialties. One means of control over optimizer strategies is to set the optimizer_switch system variable (see Section 10. Oct 22, 2016 · The index, idx_bucket is correctly being used for the outer query, but the idx_test is not used for the inner sub query when I do an EXPLAIN query plan. Jan 21, 2013 · The generic syntax is as follows: SELECT x. client_id = clients. region + sir. 1. ID = C. INNER JOIN paths AS P ON U. One multi-column index on r. The query is mentioned below: Nov 20, 2023 · One of the most effective ways to optimize joins is through Indexing. AND setting. Oct 30, 2017 · Here's a compendium of practical MySQL optimization tricks - from bottlenecks to configuration and indexes. The following discussion refers to the join syntax described in Section 13. For the best tips on how to optimize SQL query with multiple joins, check out this actionable guide. LIMIT 50. Left Join Quantity Q Q. password, meta. item_id. For example, use this query: SELECT * FROM t1 WHERE t1. This chapter explains how to optimize MySQL performance and provides examples. The latter accepts only table_reference, not a list of them inside a pair of May 1, 2023 · In this article, we will delve into ten MySQL performance tuning tips to help you optimize your database for faster query execution. 8. uid, listing. Depending on your job role (developer, DBA, or a combination of both), you might optimize at the level of individual SQL statements, entire applications, a single database server This week, I wanted to share some of my recent experiments with MySQL queries in regard to lowering the number of requests sent to the database server and, hopefully, avoiding the bottleneck that can form on sites that rely heavily on database interaction. First, check if query profiling is enabled by typing: SELECT @@PROFILING; +-------------+. Better answer: It would be best to find a query analyzer for MySql and use it to determine what the actual cause of the slow down is. file_summary_by_instance to a LEFT JOIN on a subquery: Oct 31, 2017 · The query is taking more than 1 min to fetch 1000 rows of data. You can refer to the MySQL's documentation on optimization, specifically LEFT JOIN optimization and optimization using indexes. For uncorrelated subqueries that always return one row, IN is always slower than =. Here is the query I'm running : SELECT CONCAT(H. time; That will get you the most recent message in each thread. name, P. But first, you need to narrow the problem down to MySQL. In some cases, it might not have enough information about the data and plan queries in a non-optimal way. id_currency_purchase, MIN(cr. path = P. FROM data as d2. data, nf. id) As Count_id. B = t2a. I have the following SQL but wish to improve the performance (Option 2 below currently takes about 24 seconds). id = x. Jan 1, 2014 · If this same query earlier ran faster than now; then it may not be the issue with this query rather probably with the statistics of table. where d1. It does this by arranging the joins in several orders and then estimates the various costs for each order before finally selecting the least expensive option that gives the same result as the initial order of a query. Feb 28, 2013 · 4. By leveraging indexes smartly, you can significantly enhance the performance of your queries. if you have recently done huge DML on the table; try updating stats of the table. id))!=0 in the select statement is taking too much time to fetch data. An SQL statement with poorly designed pattern that involves a lot of joins may not work well. id = p. Created a test environment and tested some hypothesis. id AND y. This indexes is important to optimize the LEFT JOIN. col_name = (SELECT a FROM t2 WHERE b = some_const); Instead of this query: Sep 5, 2014 · The original query takes 14 minutes and 24 seconds. name) FROM hosts AS H. name as type, count(p. *. EmpNo. Join specialties ON clients. INNER JOIN setting ON setting. After you are sure there are indexes you can try to re-write your query like this: SELECT DISTINCT tech. 2 - Using the following query. GROUP BY job. Oct 22, 2015 · MySQL uses a cost-based optimizer to determine the best way to execute a query. Here is the query, but it takes ~9 secs which is too slow. The last part of the discussion suggests how you can help the Sep 13, 2020 · Q. Indexes are signposts for MySQL. Also can you please provide the tips that can be used to optimize query where we have to join same table multiple times. I understand this has to perform 980 queries, but taking more than 15 minutes on a beefy machine is strange. max_time = x. Quantity. bfid = s. ID = O. My question here is: is there a way to optimize this query? I really need to squeeze the numbers. See Section 10. name; You will need to make two major changes: MAJOR CHANGE # 1 : Refactor the Query. Set indexes on the fields you use for joining. Apr 6, 2012 · At a MySQL prompt we will run the following: mysql> SET PROFILING=1; mysql> SELECT auth. product_id) as n. bid. leader_id, nf. Network. Feb 1, 2010 · 10. id. name = C. Sep 10, 2013 · When I run a select on the view, it takes about 25 seconds. INNER JOIN account ON account. Oftentimes benchmarks are made on quiescent systems. 6 (also: Percona and MariaDB versions. I'm concerned that as the tables continue to grow in size, the performance of this query is going to rapidly degrade. Aug 24, 2022 · Join optimization is one of the most potent ways MySQL helps optimize queries that involve joins. qty tacked on the end. Join clients ON clients_locations. To provide a hint about the table join order, use optimizer hints; see Section 10. May 22, 2012 · SELECT id, MIN(`column`) as cln FROM table2 GROUP BY id; add index to temporary table for faster join to table 1 (can omit this step depending on data size) ALTER TABLE tmp_operation ADD UNIQUE INDEX (id); update with simple join. WHERE user. Here we must introduce conditional pushed-down predicates guarded by the flags that are turned on when a match has been encountered. buy_rate) Now it takes about 0,5 s, which is way too long for me (it's used either updated very often, so query cache doesn't help in my case). How to query counting specific wins of team and find the winner of the series. The guidelines cover SQL operations that read and Jul 30, 2012 · The above query gets very slow when both tables have more than 500K rows. Itemdesc + sir. group by t. uid = listing. Thus, the optimization of pushing conditions out of the inner nested loops cannot be applied directly to queries with outer joins. id3, D. I need to optimize this query: cp. This is a TinyInt field (essentially a boolean 0/1 is stored). buy_rate), MAX(cr. string_comment = B. The main considerations for optimizing queries are: To make a slow SELECT WHERE query faster, the first thing to check is whether you can add an index. 2, “Switchable Optimizations” ). Tuning these statements is a top priority, whether to achieve sub-second response times for dynamic web pages, or to chop hours off the time to generate huge overnight reports. Countries. SELECT `master_table`. Any suggestions? 10. courses_uuid = 98481529319063564 " it will take 1. 1 Optimizing Queries with EXPLAIN. ORDER BY job. client_location_id = clients_locations. MySQL version 8. It generates multiple execution plans and compares them to select the plan with the lowest estimated cost. ) Several benefits as bugs have been corrected, the optimizer improved and you can set the low threshold for slow queries to less than 1 second (like 10 milliseconds). Aug 5, 2016 · Explanation. uid; mysql> SHOW PROFILE FOR QUERY 1; The output of that last line will be something like the following: Apr 11, 2013 · Consider moving to a newer version of MySQL, 5. deleted_at IS NULL. One of the first things you may want to do when trying to optimize a slow query is to profile the query to discover where exactly the query is taking the most time. D is null; Jan 21, 2012 · Any inputs on how can I optimize joins in the MySQL query? For example, consider the following query. Join clients_locations ON visits. Jan 4, 2012 · If you see unexpected behaviour in the query plan, you can force the database to update its statistics; in MySQL you can use Optimize Table - which does everything, including re-ordering the table itself, or Analyze Table which only updates the indices. name = D. Mar 6, 2017 · Now I would like to Search in another database and retrieve 5 more fields from ville_nom_reel field from 1st Query. Always include fewer tables in your join statements. This will give you far better info about slow queries. This query takes quite a while, although all of the fields that we use on the JOIN, GROUP BY and ORDER BY statements are either indexed, or declared as foreign key or primary key. Still, join seeks are unavoidable. I have a select query, that selects over 50k records from MySQL 5. They guide it to fetch data efficiently without scanning it unnecessarily. EmpNo, listing. I have 3 tables which are posts, comments and users. Example: If you frequently join the employees table with the departments table using the dept_id column, ensure both tables have indexes on these columns. FirstName, listing. Aug 2, 2018 · Optimize Joins. 16 ORDER BY Optimization. Table A is set to depend on all tables (except B) that are used in the LEFT JOIN condition. name AND E. 2 Range Optimization. 7 Nested Join Optimization. I mean, you have to only use the columns that use in SELECT part of query. id AND type = 'login' ) AS login, ( SELECT act_description FROM message_detail. Plan Comparison. 6 supports. FROM `lookup_table` x 21. Whereas with a datetime type is a simple numeric comparison and will use an index. name AND 10. Apr 10, 2024 · Optimizing MySQL Query Execution. However what I need is to sort the results using Oct 9, 2015 · 2. This section describes when MySQL can use an index to satisfy an ORDER BY clause, the filesort operation used when an index cannot be used, and execution plan information available from the optimizer about ORDER BY . flowid = f. Check What’s Running on the Instance. Optimizing MySQL: Queries and Indexes. Nov 23, 2014 · Tables: Please take a look here to see tables. id, nf. Further make sure that these have both the same datatype, encoding, and collation, else the index will also not be used. TABLEAS SELECT , INSERT. Memory. id order by t. I am learning the act of query optimization, in terms of execution time. Let’s say Retrace is reporting a slow page on one of your sites. 5. Jan 21, 2013 at 16:15. INNER JOIN urls as U ON H. Depending on your job role (developer, DBA, or a combination of both), you might optimize at the level of individual SQL statements, entire applications Jun 11, 2018 · 3. Aug 23, 2016 · Your query (as posted) can be reduced to: Select Count(Distinct visits. Assuming no index is created yet, how can i optimize this using index so the query runs faster? How do i create the index? Dec 2, 2016 · Given the following query, how can I optimize it so that the subqueries are not dependent? Jan 29, 2017 · One possible explanation as to what is going on here is that MySQL is choosing to do the ordering before it does the actual join. Indexes that are not changed do not get updated. matrix_uuid = 98414860655656981 AND c. Jan 4, 2022 · Also try to narrow down your search to see if all queries are slow or is the slowness isolated to one or a few queries. The sub query with FIND_IN_SET(id,GROUP_CONCAT(t. inner join type t on f. 2. It is easier to work on a few problematic queries than to fight the ‘everything is slow’ problems. family_id. Here's a better formulation without changing anything. UID and listing. An update statement is optimized like a SELECT query with the additional overhead of a write. Jan 9, 2013 · Try running the query without the ORDER BY and see if it makes a difference; See also these related StackOverflow threads: MySQL MAX_JOIN_SIZE errors; MySQL - SQL_BIG_SELECTS; MySQL: “The SELECT would examine more than MAX_JOIN_SIZE rows” More details about MAX_JOIN_SIZE & SQL_BIG_SELECTS from official MYSQL documentation. `data_point` x 21. inner join family f on f. It is likely issue is caused by join on the setting table, because the below two queries take about 5 seconds total. The index may also be used even if the ORDER. WHERE dataID > 522 AND year = 2017; CREATE INDEX growth_ix. Serialno, in order of most cardinality to least cardinality, with sir. 3 Optimization and Indexes. Note that this means that if you do a query like the following one, MySQL does a full scan on b because the LEFT JOIN forces it to be read before d: SELECT * FROM a JOIN b LEFT JOIN c ON (c. 8. 0245 ms. Optimization involves configuring, tuning, and measuring performance, at several levels. FROM my_table x JOIN (SELECT id,MAX (time) max_time FROM my_table GROUP BY id) y ON y. Oct 27, 2010 · I am using MySQL and I cannot optimize this query. SELECT E. FROM listing INNER JOIN tech ON tech. The optimizer estimates the cost of various query execution plans using statistical information about the data, such as row counts, data distribution, and index statistics. Dec 8, 2016 · setting. id2, C. I believe it can be optimized and I would appreciate an optimized code with an explanation. But for every phone number you have to scan through the full book B trying to find Feb 1, 2010 · 10. Dec 13, 2017 · @RDFozz - The Optimizer can start with either table in an INNER JOIN, but it needs to start with the "left" table in a join that is truly LEFT JOIN. EmpNo on their respective tables. 10. 000 in table B this takes forever. account_id. This case can get much worse if there are more than If date is not indexed, the queries will have to do a full table scan. 1 Optimizing SELECT Statements. Each piece is crucial for the desired outcome. bid) If the subquery selects too many rows this query will be a drag since MySQL won't use any indices for A. from data d1. ID. If nullable, NOT IN or NOT EXISTS is the best choice in MySQL. The trick to improve the performance is to rewrite the query to take advantage of the materialized temporary tables that MySQL 5. In this case, you are testing for two values and presumably looking to see if neither one exists. You can provide both of these, and let the Optimizer pick: INDEX(x) -- filters out unwanted rows, but you are left with a sort. projects -> hasMany -> milestones -> hasMany -> tasks. Questions: How to make query more optimize? How to reduce query redundancy? Jul 19, 2015 · As you can see, the schema is really simple but the problem is the amount of data in these tables. Try breaking this into two joins: select * from t1 left join t2 on t1. Oct 12, 2015 · No single index (composite or not) will be optimal. string_comment = C. 182s but if I add this where conditi Nov 2, 2014 · I have this query. It moves the LEFT JOINs into the SELECT part and avoids the GROUP BY. The index entries act like pointers to the table rows, allowing the query to quickly determine which rows match a condition in the WHERE clause, and retrieve the other Jun 19, 2017 · This query takes about 500 seconds to complete, whereas if I remove the IS NULL the query takes 0. The tuning guidelines in this section help to speed up all kinds of MySQL applications. If NOT nullable, `LEFT JOIN/IS NULL is the best choice in MySQL. value. Sep 6, 2016 · I have two complex SELECT queries (for the sake of example I reduce the queries to the following): SELECT id, t3_id FROM t1; SELECT t3_id, MAX(added) as last FROM t2 GROUP BY t3_id; query 1 returns 16k rows and query 2 returns 15k. flowid. Use = ANY rather than EXISTS . id4, E. ge cu wi rb er sg gr um kp ot