Home > Database > Mysql Tutorial > How to Efficiently Select the Top 10 Oracle Records with Specific Conditions and Ordering?

How to Efficiently Select the Top 10 Oracle Records with Specific Conditions and Ordering?

Barbara Streisand
Release: 2025-01-18 15:47:12
Original
537 people have browsed it

How to Efficiently Select the Top 10 Oracle Records with Specific Conditions and Ordering?

Optimizing Oracle Queries: Selecting the Top 10 Records with Conditions

Oracle database queries often require retrieving a limited number of records based on specific criteria and a desired order. Simply using LIMIT with additional conditions can sometimes yield unexpected results, especially when ordering is involved. This article addresses a common scenario and offers optimized solutions.

The challenge lies in selecting the top 10 records from the HISTORY table, ordered by STORAGE_GB, while excluding records with specific APP_IDs. A naive approach using LIMIT directly might misorder the results.

The Solution: Subqueries for Precise Ordering

To ensure correct ordering before limiting the results, we employ a subquery. This approach prioritizes filtering and sorting, then applies the limit. The refined query is as follows:

<code class="language-sql">SELECT * FROM (
  SELECT DISTINCT
    APP_ID,
    NAME,
    STORAGE_GB,
    HISTORY_CREATED,
    TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') AS HISTORY_DATE
  FROM HISTORY
  WHERE
    STORAGE_GB IS NOT NULL AND
    APP_ID NOT IN (
      SELECT APP_ID
      FROM HISTORY
      WHERE TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') = '06.02.2009'
    )
  ORDER BY STORAGE_GB DESC
)
WHERE ROWNUM <= 10;</code>
Copy after login

Enhanced Performance Techniques

For improved query efficiency, consider these alternatives:

  • NOT EXISTS for Optimized Filtering: Replace NOT IN with NOT EXISTS to prevent potential Cartesian product issues, leading to faster execution.

  • RANK() Function for Ranked Selection: The RANK() function assigns a rank to each record based on the STORAGE_GB order. Selecting records with ranks less than or equal to 10 provides a more efficient method for retrieving the top 10.

By using these optimized approaches, you can efficiently retrieve the top 10 records in Oracle while maintaining the correct order and avoiding performance bottlenecks.

The above is the detailed content of How to Efficiently Select the Top 10 Oracle Records with Specific Conditions and Ordering?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template