[Solved] How to get Select Field Value Lenght in mysql query

EverSQL Database Performance Knowledge Base

How to get Select Field Value Lenght in mysql query

Database type:

Here is my example code if anyone can please explain just tell me the syntax of MySQL ...

SELECT s.sales_id,s.pid,s.quantity,IFNULL((SELECT i.invoice_id FROM
invoice AS i WHERE i.checkin_id NOT IN (SELECT crt.checkin_id FROM 
checkin_request_ticket as crt WHERE crt.salvage_part='1') AND 
i.invoice_id=s.sales_id),s.quantity) as checkquan
FROM sales as s 

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
  2. Replace In Subquery With Correlated Exists (modified query below): In many cases, an EXISTS subquery with a correlated condition will perform better than a non correlated IN subquery.
  3. Use Numeric Column Types For Numeric Values (query line: 15): Referencing a numeric value (e.g. 1) as a string in a WHERE clause might result in poor performance. Possible impacts of storing numbers as varchars: more space will be used, you won't be able to perform arithmetic operations, the data won't be self-validated, aggregation functions like SUM won't work, the output may sort incorrectly and more. If the column is numeric, remove the quotes from the constant value, to make sure a numeric comparison is done.
Optimal indexes for this query:
ALTER TABLE `checkin_request_ticket` ADD INDEX `checkin_ticket_idx_salvage_part_checkin_id` (`salvage_part`,`checkin_id`);
ALTER TABLE `invoice` ADD INDEX `invoice_idx_invoice_id` (`invoice_id`);
The optimized query:
SELECT
        s.sales_id,
        s.pid,
        s.quantity,
        IFNULL((SELECT
            i.invoice_id 
        FROM
            invoice AS i 
        WHERE
            NOT EXISTS (SELECT
                1 
            FROM
                checkin_request_ticket AS crt 
            WHERE
                (crt.salvage_part = '1') 
                AND (i.checkin_id = crt.checkin_id)) 
            AND i.invoice_id = s.sales_id), s.quantity) AS checkquan 
    FROM
        sales AS s

Related Articles



* original question posted on StackOverflow here.