Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How bad is my query?

Ok I need to build a query based on some user input to filter the results.

The query basically goes something like this:

SELECT * FROM my_table ORDER BY ordering_fld; 

There are four text boxes in which users can choose to filter the data, meaning I'd have to dynamically build a "WHERE" clause into it for the first filter used and then "AND" clauses for each subsequent filter entered.

Because I'm too lazy to do this, I've just made every filter an "AND" clause and put a "WHERE 1" clause in the query by default.

So now I have:

SELECT * FROM my_table WHERE 1 {AND filters} ORDER BY ordering_fld; 

So my question is, have I done something that will adversely affect the performance of my query or buggered anything else up in any way I should be remotely worried about?

like image 669
Evernoob Avatar asked Sep 02 '09 15:09

Evernoob


People also ask

How can you check performance of a query?

Use the Query Store page in SQL Server Management Studio In Object Explorer, right-click a database, and then select Properties. Requires at least version 16 of Management Studio. In the Database Properties dialog box, select the Query Store page. In the Operation Mode (Requested) box, select Read Write.

How do I check if a SQL query is correct?

Check - The check is a way for you to check if you have written a legal SQL query. Arrow - This is the execute command button. This will send the query to the server and the server will write back the result to you. Square - This is the stop execution command.

Why is my query running slow?

WAITING: Queries can be slow because they're waiting on a bottleneck for a long time. See a detailed list of bottlenecks in types of Waits. RUNNING: Queries can be slow because they're running (executing) for a long time. In other words, these queries are actively using CPU resources.


1 Answers

MySQL will optimize your 1 away.

I just ran this query on my test database:

EXPLAIN EXTENDED SELECT  * FROM    t_source WHERE   1 AND id < 100 

and it gave me the following description:

select `test`.`t_source`.`id` AS `id`,`test`.`t_source`.`value` AS `value`,`test`.`t_source`.`val` AS `val`,`test`.`t_source`.`nid` AS `nid` from `test`.`t_source` where (`test`.`t_source`.`id` < 100) 

As you can see, no 1 at all.

The documentation on WHERE clause optimization in MySQL mentions this:

  • Constant folding:

    (a<b AND b=c) AND a=5 -> b>5 AND b=c AND a=5 
  • Constant condition removal (needed because of constant folding):

    (B>=5 AND B=5) OR (B=6 AND 5=5) OR (B=7 AND 5=6) -> B=5 OR B=6 

Note 5 = 5 and 5 = 6 parts in the example above.

like image 95
Quassnoi Avatar answered Oct 03 '22 23:10

Quassnoi