search
HomeDatabaseSQL[SQL Learning] The connection between ordered index and order by

Generally, there are two implementation methods for order by. One is to use the ordered index to automatically implement it. That is to say, using the orderliness of the ordered index does not require additional sorting operations. The other is to sort the results after selecting them. Using ordered index is of course the fastest, but there are some restrictions. Let’s take a look at the test below.

Test data: The student table has two fields id, sid, and id is the primary key. There are a total of 20W records, with IDs ranging from 1 to 200000, and sids also ranging from 1 to 200000.

The first situation:

The order by field is neither in the where condition nor in the select

select sid from zhuyuehua.student where sid
[SQL Learning] The connection between ordered index and order by
##Second case:

order by The field is not in the where condition but in the select.

select id,sid from zhuyuehua.student where sid

[SQL Learning] The connection between ordered index and order by
The third case:

The order by field is in the where condition but not in the select.

select sid from zhuyuehua.student where sid

[SQL Learning] The connection between ordered index and order by##Fourth case:

The order by field is in the where condition but not in the select. Sort in reverse order

select sid from zhuyuehua.student where sid


[SQL Learning] The connection between ordered index and order byTest results:

The field of order by is not in the where condition and is not in the select There is a sorting operation

The field of order by is not in the where condition but in select There is a sorting operation

The field of order by is in the where condition but not in the select No sorting operation

The fields of order by are in the where condition but not in the select (reverse order) No sorting operation

Conclusion:


When the order by field appears in the where condition, the index will be used without sorting operation.
In other cases, order by will not perform sorting operations. analyze:


Why only when the order by field appears in the where condition, the index of the field will be used to avoid sorting.
This is about how the database gets the data we need. A SQL can actually be divided into three steps.

1. Get data

2. Process data

3. Return the processed data

For example, the above statement select sid from zhuyuehua.student where sid
Step 1: Generate execution based on where condition and statistical information Plan, get data.

Step 2: Sort the obtained data.


When executing data processing (order by), the database will first check the execution plan of the first step to see whether the fields of order by use indexes in the execution plan. If so, you can use the index order to directly obtain the sorted data.
If not, sort operation. Step 3: Return the sorted data.

in addition:

The above 50,000 data sort only took 25ms. Maybe you think the sort does not take up much resources. However, since the data in the above table is ordered, sorting takes less time. If it is a relatively unordered table, the sort time will increase a lot. In addition, sorting operations are generally performed in memory, which is a kind of CPU consumption for the database. Due to the enhanced performance of the CPU, ordinary sorting of dozens or hundreds of records will not have a great impact on the system. big. But when your record set increases to more than one million records, you need to pay attention to whether you must do this. Sorting of large record sets not only increases CPU overhead, but also may cause hard disk sorting due to insufficient memory. When a hard disk occurs Performance drops dramatically when sorting.

Note: ORACLE or DB2 have a space for SORT operations (the memory sorting mentioned above). For example, in ORACLE, it is the user global area (UGA), which contains settings for parameters such as SORT_AREA_SIZE. If the amount of data being sorted is large, sorting overflow (hard disk sorting) will occur, and the performance will be reduced a lot.

Summarize:



When the fields in order by appear in the where condition, the index will be used without sorting. To be more precise, the fields in order by are in the execution plan When using indexes, no sorting operation is required. #This conclusion is not only valid for order by, but also for other operations that require sorting. For example,

group by, union, distinct, etc.
If you want to know more tutorials about sql, please pay attention to the PHP Chinese website

sql video tutorial

!


  • [SQL Learning] The connection between ordered index and order by
  • Size: 16 KB
  • [SQL Learning] The connection between ordered index and order by
  • Size : 16 KB
  • [SQL Learning] The connection between ordered index and order by
  • Size: 20.6 KB
  • [SQL Learning] The connection between ordered index and order by
  • ##Size : 21 KB

    The above is the detailed content of [SQL Learning] The connection between ordered index and order by. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
    SQL Security Best Practices: Protecting Your Database from VulnerabilitiesSQL Security Best Practices: Protecting Your Database from VulnerabilitiesMay 09, 2025 am 12:23 AM

    Best practices to prevent SQL injection include: 1) using parameterized queries, 2) input validation, 3) minimum permission principle, and 4) using ORM framework. Through these methods, the database can be effectively protected from SQL injection and other security threats.

    MySQL: A Practical Application of SQLMySQL: A Practical Application of SQLMay 08, 2025 am 12:12 AM

    MySQL is popular because of its excellent performance and ease of use and maintenance. 1. Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2. Insert and query data: operate data through INSERTINTO and SELECT statements. 3. Optimize query: Use indexes and EXPLAIN statements to improve performance.

    Comparing SQL and MySQL: Syntax and FeaturesComparing SQL and MySQL: Syntax and FeaturesMay 07, 2025 am 12:11 AM

    The difference and connection between SQL and MySQL are as follows: 1.SQL is a standard language used to manage relational databases, and MySQL is a database management system based on SQL. 2.SQL provides basic CRUD operations, and MySQL adds stored procedures, triggers and other functions on this basis. 3. SQL syntax standardization, MySQL has been improved in some places, such as LIMIT used to limit the number of returned rows. 4. In the usage example, the query syntax of SQL and MySQL is slightly different, and the JOIN and GROUPBY of MySQL are more intuitive. 5. Common errors include syntax errors and performance issues. MySQL's EXPLAIN command can be used for debugging and optimizing queries.

    SQL: A Guide for Beginners - Is It Easy to Learn?SQL: A Guide for Beginners - Is It Easy to Learn?May 06, 2025 am 12:06 AM

    SQLiseasytolearnforbeginnersduetoitsstraightforwardsyntaxandbasicoperations,butmasteringitinvolvescomplexconcepts.1)StartwithsimplequerieslikeSELECT,INSERT,UPDATE,DELETE.2)PracticeregularlyusingplatformslikeLeetCodeorSQLFiddle.3)Understanddatabasedes

    SQL's Versatility: From Simple Queries to Complex OperationsSQL's Versatility: From Simple Queries to Complex OperationsMay 05, 2025 am 12:03 AM

    The diversity and power of SQL make it a powerful tool for data processing. 1. The basic usage of SQL includes data query, insertion, update and deletion. 2. Advanced usage covers multi-table joins, subqueries, and window functions. 3. Common errors include syntax, logic and performance issues, which can be debugged by gradually simplifying queries and using EXPLAIN commands. 4. Performance optimization tips include using indexes, avoiding SELECT* and optimizing JOIN operations.

    SQL and Data Analysis: Extracting Insights from InformationSQL and Data Analysis: Extracting Insights from InformationMay 04, 2025 am 12:10 AM

    The core role of SQL in data analysis is to extract valuable information from the database through query statements. 1) Basic usage: Use GROUPBY and SUM functions to calculate the total order amount for each customer. 2) Advanced usage: Use CTE and subqueries to find the product with the highest sales per month. 3) Common errors: syntax errors, logic errors and performance problems. 4) Performance optimization: Use indexes, avoid SELECT* and optimize JOIN operations. Through these tips and practices, SQL can help us extract insights from our data and ensure queries are efficient and easy to maintain.

    Beyond Retrieval: The Power of SQL in Database ManagementBeyond Retrieval: The Power of SQL in Database ManagementMay 03, 2025 am 12:09 AM

    The role of SQL in database management includes data definition, operation, control, backup and recovery, performance optimization, and data integrity and consistency. 1) DDL is used to define and manage database structures; 2) DML is used to operate data; 3) DCL is used to manage access rights; 4) SQL can be used for database backup and recovery; 5) SQL plays a key role in performance optimization; 6) SQL ensures data integrity and consistency.

    SQL: Simple Steps to Master the BasicsSQL: Simple Steps to Master the BasicsMay 02, 2025 am 12:14 AM

    SQLisessentialforinteractingwithrelationaldatabases,allowinguserstocreate,query,andmanagedata.1)UseSELECTtoextractdata,2)INSERT,UPDATE,DELETEtomanagedata,3)Employjoinsandsubqueriesforadvancedoperations,and4)AvoidcommonpitfallslikeomittingWHEREclauses

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version