search
HomeDatabaseOracleHow to sort query results in oracle

In Oracle, you can use the "SELECT" statement and the "ORDER BY" clause to sort the query. You can sort the query result set of one or more columns in ascending or descending order. The syntax "SELECT field name" FROM data table name ORDER BY field name [ASC|DESC]".

How to sort query results in oracle

The operating environment of this tutorial: Windows 7 system, Oracle 11g version, Dell G3 computer.

In Oracle, you can use the "SELECT" statement and the "ORDER BY" clause to sort queries.

In Oracle, row data records are stored in the table in a non-specified order, regardless of the order in which the rows are inserted into the database. To query row records by column in ascending or descending order, you must explicitly instruct the Oracle database how to sort.

For example, you might want to list all customers alphabetically by name, or display all customers in order from lowest to highest credit limit.

To sort the queried data, add the ORDER BY clause to the SELECT statement as follows.

ORDER BY clause can sort the result set of one or more columns in ascending or descending order.

Syntax:

SELECT
    字段名,
FROM
    table_name
ORDER BY
    字段名 [ASC | DESC] [NULLS FIRST | NULLS LAST]

To sort the result set by a column, you can list the column after the ORDER BY clause.

It is a sorting order according to the column name, which can be:

  • ASC means sorting in ascending order

  • DESC means sorting in descending order

By default, the ORDER BY clause is used whether or not ASC is specified. Both sort the rows in ascending order. If you want to sort the rows in descending order, use DESC explicitly.

NULLS FIRST Place NULL values ​​before non-NULL values, NULLS LAST before non-## Place the NULL value after the #NULL value.

ORDER BY clause can sort data by multiple columns, and each column may have a different sort order.

Note that the

ORDER BY clause is always the last clause in a SELECT statement.

Example of Oracle ORDER BY clause

The following will use the

customers table in the sample database for demonstration.

How to sort query results in oracle

The following statement retrieves the customer's from the customers (

customers) table: name, address and credit limit:

SELECT name, address, credit_limit FROM customers;

Execute the above query statement and get the following results-

How to sort query results in oracle

As you can see in the screenshot, row records The order is unspecified.

1. Example of sorting rows by column

#To sort customer names alphabetically in ascending order, use the following statement:

SELECT name,address,credit_limit
FROM customers
ORDER BY name ASC;

Execute the above example code and get the following results -

How to sort query results in oracle

ASC instructs Oracle to sort the rows in ascending order. But ASC is optional, and if omitted, by default, the ORDER BY clause sorts the rows by the specified column in ascending order.

Therefore, the following expression:

ORDER BY name ASC

is equivalent to -

ORDER BY name

To order customer names in descending alphabetical order, ORDER BY

Explicitly use DESC after the column name in the clause, as shown below: <pre class='brush:php;toolbar:false;'>SELECT name, address, credit_limit FROM customers ORDER BY name DESC;</pre>Execute the above query statement and get the following results-

How to sort query results in oracle

2. Example of sorting rows by multiple columns To sort multiple columns, you can separate them with commas

ORDER BY

each column in the sentence. See the following Contacts (

contacts

) table in the sample database. For example, to sort by

first_name

in ascending order and the last_name column in descending order, use the following statement: <pre class='brush:php;toolbar:false;'>SELECT first_name, last_name FROM contacts ORDER BY first_name, last_name DESC;</pre>Execute From the above sample code, you can see the following results -

##As you can see from the screenshot above, How to sort query results in oraclecontact_id

is

91 and 311The values ​​of first_name of these two records are the same, and the values ​​of last_name are arranged in descending order. In this example, Oracle first sorts the rows by first_name

in ascending order to create the initial result set. Oracle then sorts the initial result set on

last_name in descending order. See results similar to the following:

In the above result: How to sort query results in oracle

  • 首先,按first_name升序排序。
  • 其次,如果两个名字相同,按last_name降序排列,如Daniel GlassDaniel CostnerDianne SenDianne DerekDoretha TylerDorotha Wong

3、按列位置排序行示例

不需要指定用于排序数据的列名称。如果您愿意,可以使用ORDER BY子句中列的位置。

请参考下语句 -

SELECT name, credit_limit,address
FROM customers
ORDER BY 2 DESC, 1;

在这个例子中,name列的位置是1credit_limit列的位置是2。相当于以下查询语句 -

SELECT name, credit_limit,address
FROM customers
ORDER BY credit_limit DESC, name;

ORDER BY子句中,使用这些列位置来指示Oracle对行进行排序。

4、用NULL值排序行的示例

请参阅示例数据库中的以下地区(locations)表:

How to sort query results in oracle

以下语句按城市(city)和州(state)检索位置并对其进行排序:

SELECT country_id, city, state
FROM locations 
ORDER BY state DESC;

执行上面查询语句,得到以下结果 -

How to sort query results in oracle

state列有NULL值,这意味着state数据与某些城市(例如:Beijing, HiroshimaLondon)无关。

当使用非NULL值对混合NULL进行排序时,Oracle允许指定哪个应该首先出现。

例如,以下语句按升序对state列进行排序,并首先将NULL值放置在前面。

SELECT country_id, city, state
FROM
    locations
ORDER BY
    state ASC NULLS FIRST;

要放置NULL值在后面,可以使用NULLS LAST,如下面的语句所示:

SELECT country_id, city, state
FROM
    locations
ORDER BY
    state ASC NULLS LAST;

执行上面示例查询语句,得到以下结果:

How to sort query results in oracle

5、按函数或表达式排序数据

ORDER BY子句可在一列上应用一个函数,例如字符串函数,数学函数等,并按函数的结果对数据进行排序。

例如,以下语句使用ORDER BY子句中的UPPER()函数来区分客户名称的大小写:

SELECT customer_id, name
FROM customers
ORDER BY UPPER( name );

执行上面查询语句,得到以下结果 -

How to sort query results in oracle

推荐教程:《Oracle教程

The above is the detailed content of How to sort query results in oracle. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Oracle's Purpose: Business Solutions and Data ManagementOracle's Purpose: Business Solutions and Data ManagementApr 13, 2025 am 12:02 AM

Oracle helps businesses achieve digital transformation and data management through its products and services. 1) Oracle provides a comprehensive product portfolio, including database management systems, ERP and CRM systems, helping enterprises automate and optimize business processes. 2) Oracle's ERP systems such as E-BusinessSuite and FusionApplications realize end-to-end business process automation, improve efficiency and reduce costs, but have high implementation and maintenance costs. 3) OracleDatabase provides high concurrency and high availability data processing, but has high licensing costs. 4) Performance optimization and best practices include the rational use of indexing and partitioning technology, regular database maintenance and compliance with coding specifications.

How to delete oracle library failureHow to delete oracle library failureApr 12, 2025 am 06:21 AM

Steps to delete the failed database after Oracle failed to build a library: Use sys username to connect to the target instance. Use DROP DATABASE to delete the database. Query v$database to confirm that the database has been deleted.

How to create cursors in oracle loopHow to create cursors in oracle loopApr 12, 2025 am 06:18 AM

In Oracle, the FOR LOOP loop can create cursors dynamically. The steps are: 1. Define the cursor type; 2. Create the loop; 3. Create the cursor dynamically; 4. Execute the cursor; 5. Close the cursor. Example: A cursor can be created cycle-by-circuit to display the names and salaries of the top 10 employees.

How to export oracle viewHow to export oracle viewApr 12, 2025 am 06:15 AM

Oracle views can be exported through the EXP utility: Log in to the Oracle database. Start the EXP utility, specifying the view name and export directory. Enter export parameters, including target mode, file format, and tablespace. Start exporting. Verify the export using the impdp utility.

How to stop oracle databaseHow to stop oracle databaseApr 12, 2025 am 06:12 AM

To stop an Oracle database, perform the following steps: 1. Connect to the database; 2. Shutdown immediately; 3. Shutdown abort completely.

What to do if the oracle log is fullWhat to do if the oracle log is fullApr 12, 2025 am 06:09 AM

When Oracle log files are full, the following solutions can be adopted: 1) Clean old log files; 2) Increase the log file size; 3) Increase the log file group; 4) Set up automatic log management; 5) Reinitialize the database. Before implementing any solution, it is recommended to back up the database to prevent data loss.

How to create oracle dynamic sqlHow to create oracle dynamic sqlApr 12, 2025 am 06:06 AM

SQL statements can be created and executed based on runtime input by using Oracle's dynamic SQL. The steps include: preparing an empty string variable to store dynamically generated SQL statements. Use the EXECUTE IMMEDIATE or PREPARE statement to compile and execute dynamic SQL statements. Use bind variable to pass user input or other dynamic values ​​to dynamic SQL. Use EXECUTE IMMEDIATE or EXECUTE to execute dynamic SQL statements.

What to do if oracle deadlockWhat to do if oracle deadlockApr 12, 2025 am 06:03 AM

Oracle Deadlock Handling Guide: Identify Deadlocks: Check for "deadlock detected" errors in log files. View deadlock information: Use the GET_DEADLOCK package or the V$LOCK view to obtain deadlock session and resource information. Analyze deadlock diagram: Generate deadlock diagram to visualize the lock holding and waiting situation and determine the root cause of the deadlock. Rollback deadlock sessions: Use the KILL SESSION command to roll back the session, but it may cause data loss. Interrupt deadlock cycle: Use the DISCONNECT SESSION command to disconnect the session and release the held lock. Prevent deadlocks: Optimize queries, use optimistic locking, conduct transaction management, and regularly

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)