Updated on 2023-10-18 GMT+08:00

SQL Usage

Database Design

  • Ensure that all characters are stored and represented in utf-8 or utf8mb4 format. Comments must be provided for tables and fields.
  • Avoid using large transactions.

    For example, if multiple SELECT and UPDATE statements are executed in a high-frequency transaction, the database concurrency capability is severely affected because resources such as locks held by the transaction can be released only when the transaction is rolled back or committed. In this case, data write consistency must also be considered.

Index Design

  • Reduce the use of ORDER BY that cannot be used with indexes based on the actual service requirements. The statements such as ORDER BY, GROUP BY, and DISTINCT consume many CPU resources.
  • If a complex SQL statement is involved, use the existing index design and add EXPLAIN before the SQL statement. EXPLAIN can help you optimize the index by adding some query restrictions.
  • Execute new SELECT, UPDATE, or DELETE statements with EXPLAIN to check the index usage and ensure no Using filesort and Using temporary are displayed in the Extra column. If the number of scanned rows exceeds 1,000, exercise caution when executing these statements. Analyze slow query logs and delete unused slow query statements every day.
    EXPLAIN:
    • type: ALL, index, range, ref, eq_ref, const, system, NULL (The performance is sorted from poor to good from left to right.)
    • possible_keys: indicates the indexes from which MySQL can choose to find the rows in this table. If there is an index on a field, the index is listed but may not be used by the query.
    • key: indicates the key (index) that MySQL actually decided to use. If key is NULL, MySQL found no index to use for executing the query more efficiently. To force MySQL to use or ignore an index listed in the possible_keys column, use FORCE INDEX, USE INDEX, or IGNORE INDEX in your query.
    • ref: shows which columns or constants are compared to the index named in the key column to select rows from the table.
    • rows: indicates the estimated number of rows to be read for required records based on table statistics and index selection.
    • Extra:
      • Using temporary: To resolve the query, MySQL needs to create a temporary table to hold the result. This typically happens if the query contains GROUP BY and ORDER BY clauses that list columns differently.
      • Using filesort: MySQL must do an extra pass to find out how to retrieve the rows in sorted order.
      • Using index: The column information is retrieved from the table using only information in the index tree without having to do an additional seek to read the actual row. If Using where is displayed at the same time, it indicates that desired information needs to be obtained by using the index tree and reading rows of the table.
      • Using where: In WHERE clause, Using where is displayed when the desire data is obtained without reading all the data in the table or the desire data cannot be obtained by only using indexes. Unless you specifically intend to fetch or examine all rows from the table, you may have something wrong in your query if the Extra value is not Using where and the table join type is ALL or index.
  • If a function is used on a WHERE statement, the index becomes invalid.

    For example, in WHERE left(name, 5) = 'zhang', the left function invalidates the index on name.

    You can modify the condition on the service side and delete the function. When the returned result set is small, the service side filters the rows that meet the condition.

Database SQL Query

  • Optimize the ORDER BY... LIMIT statements by indexes to improve execution efficiency.
  • If statements contain ORDER BY, GROUP BY, or DISTINCT, ensure that the result set filtered by the WHERE condition contains up to 1000 lines. Otherwise, the SQL statements are executed slowly.
  • For ORDER BY, GROUP BY, and DISTINCT statements, use indexes to directly retrieve sorted data. For example, use key(a,b) in where a=1 order by b.
  • When using JOIN, use indexes on the same table in the WHERE condition.

    Example:

    select t1.a, t2.b from t1,t2 where t1.a=t2.a and t1.b=123 and t2.c= 4

    If the t1.c and t2.c fields are the same, only b on t1 is used.

    In this case, if t2.c=4 in the WHERE condition is changed to t1.c=4,(b,c) can be used. This may occur during field redundancy design (anti normal form).

  • If deduplication is not required, use UNION ALL, which does not perform sorting operations and is faster than UNION.

  • To implement paging query in code, specify that if count is set to 0, the subsequent paging statements are not executed.
  • Do not frequently execute COUNT on a table. It takes a long time to perform COUNT on a table with a large amount of data. Generally, the response speed is in seconds. If you need to frequently perform the COUNT operation on a table, introduce a special counting table.
  • If only one record is returned, use LIMIT 1. If data is correct and the number of returned records in the result set can be determined, use LIMIT as soon as possible.
  • When evaluating the efficiency of DELETE and UPDATE statements, change the statements to SELECT and then run EXPLAIN. A large number of SELECT statements will slow down the database, and write operations will lock tables.
  • TRUNCATE TABLE is faster and uses fewer system and log resources than DELETE. If the table to be deleted does not have a trigger and the entire table needs to be deleted, TRUNCATE TABLE is recommended.
    • TRUNCATE TABLE does not write deleted data to log files.
    • A TRUNCATE TABLE statement has the same function as a DELETE statement without a WHERE clause.
    • TRUNCATE TABLE statements cannot be written with other DML statements in the same transaction.
  • Do not use negative queries to avoid full table scanning. Negative queries indicate the following negative operators are used: NOT, !=, <>, NOT EXISTS, NOT IN, and NOT LIKE.

    If a negative query is used, the index structure cannot be used for binary search. Instead, the entire table needs to be scanned.

  • Do not perform JOIN on more than three tables. The data types of the fields to be joined must be the same.
  • During multi-table associated query, ensure that the associated fields have indexes. When joining multiple tables, select the table with a smaller result set as the driving table to join other tables. Pay attention to table indexes and SQL performance even if two tables are joined.

SQL Statement Development

  • Spiting single SQL statements.

    For example, in the OR condition f_phone='10000' or f_mobile='10000', the two fields have their own indexes, but only one of them can be used.

    You can split the statement into two SQL statements or use UNION ALL.

  • If possible, perform the complex SQL calculation or service logic at the service layer.
  • Use a proper paging method to improve paging efficiency. Skipping paging is not recommended for large pages.
    • Negative example: SELECT * FROM table1 ORDER BY ftime DESC LIMIT 10000,10;

      It causes a large number of I/O operations because MySQL uses the read-ahead policy.

    • Positive example: SELECT * FROM table1 WHERE ftime < last_time ORDER BY ftime DESC LIMIT 10;

      Recommended pagination mode: Transfer the threshold value of the last page.

  • Execute UPDATE statements in transactions based on primary keys or unique keys. Otherwise, a gap lock is generated and the locked data range is expanded. As a result, the system performance deteriorates and a deadlock occurs.
  • Do not use foreign keys and cascade operations. The problems of foreign keys can be solved at the application layer.

    Example:

    If student_id is a primary key in the student table, student_id is a foreign key in the score table. If student_id is updated in the student table, student_id in the score table is also updated. This is a cascade update.

    • Foreign keys and cascade updates are suitable for single-node clusters with low concurrency and are not suitable for distributed cluster with high concurrency.
    • Cascade updates may cause strong blocks and foreign keys affect the INSERT operations.
  • If possible, do not use IN. If it is required, ensure that the number of set elements after IN should be at most 500.
  • To reduce the number of interactions with the database, use batches of SQL statements. For example, INSERT INTO... VALUES (XX),(XX),(XX)....(XX), the number of XX should be within 100.
  • Do not use stored procedures, which are difficult to debug, extend, and transplant.
  • You are not advised to use triggers, event schedulers, and views for service logic. The service logic must be processed at the service layer to avoid logical dependency on the database.
  • Do not use implicit type conversion.

    The conversion rules are as follows:

    1. If at least one of the two parameters is NULL, the comparison result is also NULL. However, when <=> is used to compare two NULL values, 1 is returned.
    2. If both parameters are character strings, they are compared as character strings.
    3. If both parameters are integers, they are compared as integers.
    4. When one parameter is a hexadecimal value and the other parameter is a non-digit value, they are compared as binary strings.
    5. If one parameter is a TIMESTAMP or DATETIME value and the other parameter is a CONSTANT value, they are compared as TIMESTAMP values.
    6. If one parameter is a DECIMAL value and other parameter is a DECIMAL or INTEGER value, they are compared as DECIMAL values. If the other argument is a FLOATING POINT value, they are compared as FLOATING POINT values.
    7. In other cases, both parameters are compared as FLOATING POINT values.
    8. If one parameter is a string and the other parameter is an INT value, they are compared as FLOATING POINT values (by referring to item 7)

      For example, the type of f_phone is varchar. If f_phone in (098890) is used in the WHERE condition, two parameters are compared as FLOATING POINT values. In this case, the index cannot be used, affecting database performance.

      If f_user_id = '1234567', the number is directly compared as a character string. For details, see item 2.

  • If possible, ensure that the number of SQL statements in a transaction should be as small as possible, no more than 5. Long transactions will lock data for a long time, generate many caches in MySQL, and occupy many connections.
  • Do not use NATURAL JOIN.

    NATURAL JOIN is used to implicitly join column, which is difficult to understand and may cause problems. The NATURAL JOIN statement cannot be transplanted.