Sql ключевое слово join
Содержание:
- Получайте только нужные данные
- Пример — сортировка результатов по возрастанию
- SQL Учебник
- Introduction to SQL ORDER BY clause
- Examples
- SORT operator
- Пример использования атрибутов ASC и DESC.
- UPDATE таблица
- Example — Sorting Results in Ascending Order
- SQL Учебник
- SQL Учебник
- SQL Учебник
- Example 4 – ORDER BY Column Number
- Пример — сортировка результатов по убыванию
- Пример сортировки без использования атрибута ASC / DESC
- Update предупреждение!
- Синтаксис
- SQL Server ORDER BY clause example
- A) Sort a result set by one column in ascending order
- B) Sort a result set by one column in descending order
- C) Sort a result set by multiple columns
- D) Sort a result set by multiple columns and different orders
- E) Sort a result set by a column that is not in the select list
- F) Sort a result set by an expression
- G) Sort by ordinal positions of columns
- Example — Using both ASC and DESC attributes
- SQL ORDER BY clause examples
- Syntax and Parameters of SQL ORDER BY
- Example — Sorting Results in descending order
- Пример — использование атрибутов ASC и DESC
Получайте только нужные данные
Идеология «чем больше данных, тем лучше» ‑ это не то, что вам нужно для написания SQL-запросов: вы рискуете не только затуманить свои идеи, получая данных на много больше, чем вам нужно, но также производительность вашего запроса может пострадать от того, что он будет выбираться слишком много данных.
Вот почему обычно рекомендуется заботиться об инструкции , операторах и .
Первое, что вы уже можете проверить, когда вы написали свой запрос, является ли оператор максимально возможно компактным. При этом ваша цель – удалить ненужные столбцы из оператора . Таким образом вы будете запрашивать только те данные, которые служат цели вашего запроса.
Помните, что коррелированный подзапрос – это подзапрос, который использует значения из внешнего запроса
И обратите внимание, что, хотя и может здесь использоваться в качестве «константы», это выглядит очень запутанно для понимания вашего запроса другими разработчиками!. Рассмотрим следующий пример, чтобы понять, что мы подразумеваем под использованием константы:
Рассмотрим следующий пример, чтобы понять, что мы подразумеваем под использованием константы:
SELECT driverslicensenr, name FROM Drivers WHERE EXISTS (SELECT '1' FROM Fines WHERE fines.driverslicensenr = drivers.driverslicensenr);
Совет: полезно знать, что наличие коррелированного подзапроса не является хорошей идеей. Вы всегда можете отказаться от него, например, переписав запрос через :
SELECT driverslicensenr, name FROM drivers INNER JOIN fines ON fines.driverslicensenr = drivers.driverslicensenr;
Оператор используется для возврата только различных значений. – это условие, которого, при возможности, лучше всего избегать. Как вы можете видеть и на других примерах, время выполнения увеличивается только в том случае, если вы добавили это предложение в свой запрос. Поэтому всегда стоит подумать над тем, действительно ли вам нужна операция , чтобы получить нужный вам результат.
Когда вы используете оператор в запросе, индекс не используется, если шаблон начинается с или . Эти шаблоны запрещают использование индексов базы данных (если он имеются). Ну и конечно, с другой стороны, этот тип запроса потенциально оставляет открытой возможность для извлечения слишком большого количества записей, которые не обязательно могут удовлетворять цели вашего запроса.
Отметим еще раз – знания структуры хранимых данных могут помочь вам сформулировать шаблон, который будет правильно фильтровать все данные, чтобы выбрать из базы только те строки, которые действительно важны для вашего запроса.
Пример — сортировка результатов по возрастанию
Чтобы отсортировать результаты в порядке возрастания, вы можете указать атрибут ASC. Если после поля в предложении ORDER BY не указано значение (ASC или DESC), порядок сортировки по умолчанию будет соответствовать возрастающему. Давайте рассмотрим это дальше.
В этом примере у нас есть таблица customers со следующими данными:
customer_id | first_name | last_name | favorite_website |
---|---|---|---|
4000 | Justin | Bieber | google.com |
5000 | Selena | Gomez | bing.com |
6000 | Mila | Kunis | yahoo.com |
7000 | Tom | Cruise | oracle.com |
8000 | Johnny | Depp | NULL |
9000 | Russell | Crowe | google.com |
Введите следующий SQL оператор.
PgSQL
SELECT *
FROM customers
ORDER BY last_name;
1 |
SELECT* FROMcustomers ORDERBYlast_name; |
Будет выбрано 6 записей. Вот результаты, которые вы должны получить.
customer_id | first_name | last_name | favorite_website |
---|---|---|---|
4000 | Justin | Bieber | google.com |
9000 | Russell | Crowe | google.com |
7000 | Tom | Cruise | oracle.com |
8000 | Johnny | Depp | NULL |
5000 | Selena | Gomez | bing.com |
6000 | Mila | Kunis | yahoo.com |
В этом примере будут возвращены все записи из таблицы customers, отсортированные по полю last_name в порядке возрастания, и будет эквивалентен следующему SQL предложению ORDER BY.
PgSQL
SELECT *
FROM customers
ORDER BY last_name ASC;
1 |
SELECT* FROMcustomers ORDERBYlast_nameASC; |
Большинство программистов пропускают атрибут ASC при сортировке в порядке возрастания.
SQL Учебник
SQL ГлавнаяSQL ВведениеSQL СинтаксисSQL SELECTSQL SELECT DISTINCTSQL WHERESQL AND, OR, NOTSQL ORDER BYSQL INSERT INTOSQL Значение NullSQL Инструкция UPDATESQL Инструкция DELETESQL SELECT TOPSQL MIN() и MAX()SQL COUNT(), AVG() и …SQL Оператор LIKESQL ПодстановочныйSQL Оператор INSQL Оператор BETWEENSQL ПсевдонимыSQL JOINSQL JOIN ВнутриSQL JOIN СлеваSQL JOIN СправаSQL JOIN ПолноеSQL JOIN СамSQL Оператор UNIONSQL GROUP BYSQL HAVINGSQL Оператор ExistsSQL Операторы Any, AllSQL SELECT INTOSQL INSERT INTO SELECTSQL Инструкция CASESQL Функции NULLSQL ХранимаяSQL Комментарии
Introduction to SQL ORDER BY clause
To sort a result set returned by a SELECT statement, you use the clause. The following query illustrates how to use the clause in a statement:
The clause allows you to sort the result set by a column or an expression with a condition that the value in the column or the returned value of the expression must be sortable i.e., the data type of the result must be the character, numeric or date-time.
To sort a result set in ascending order, you use keyword, and in descending order, you use the keyword. If you don’t specify any keyword explicitly, the clause sorts the result set in ascending order by default.
To sort multiple columns, you just need to specify additional columns in the clause. You can sort by one column in ascending order and another column in descending order.
Examples
I think the easiest way to learn is to see examples. So, I’ll show you a few ways you can use the SQL ORDER BY clause in Oracle.
I’ll be using this table to perform the SELECT queries on.
SALESPERSON_ID | FIRST_NAME | SALARY | COMMISSION | HIRE_DATE |
1 | John | 90000 | 1000 | 1-Jan-16 |
2 | Sally | 95000 | 500 | 5-Sep-16 |
3 | Mark | 101000 | 800 | 12-Aug-16 |
4 | Tina | 87000 | 900 | 24-Oct-16 |
5 | Steve | 100000 | 500 | 2-Feb-16 |
6 | Michelle | 120000 | 600 | 3-Dec-16 |
7 | Alex | 85000 | (null) | 17-Jan-16 |
8 | Jo | 115000 | 1200 | 30-Oct-16 |
Example 1 – ORDER BY Column Name
This example orders by a single column name.
SALESPERSON_ID | FIRST_NAME | SALARY | COMMISSION | HIRE_DATE |
7 | Alex | 85000 | (null) | 17-Jan-16 |
8 | Jo | 115000 | 1200 | 30-Oct-16 |
1 | John | 90000 | 1000 | 1-Jan-16 |
3 | Mark | 101000 | 800 | 12-Aug-16 |
6 | Michelle | 120000 | 600 | 3-Dec-16 |
2 | Sally | 95000 | 500 | 5-Sep-16 |
5 | Steve | 100000 | 500 | 2-Feb-16 |
4 | Tina | 87000 | 900 | 24-Oct-16 |
All of the records are ordered by the first_name column. ASC or DESC was not specified, so by default, they are ordered in ASC order.
Example 2 – ORDER BY Column Name using ASC
This example orders by a column name and uses the ASC keyword.
SALESPERSON_ID | FIRST_NAME | SALARY | COMMISSION | HIRE_DATE |
7 | Alex | 85000 | (null) | 17-Jan-16 |
4 | Tina | 87000 | 900 | 24-Oct-16 |
1 | John | 90000 | 1000 | 1-Jan-16 |
2 | Sally | 95000 | 500 | 5-Sep-16 |
5 | Steve | 100000 | 500 | 2-Feb-16 |
3 | Mark | 101000 | 800 | 12-Aug-16 |
8 | Jo | 115000 | 1200 | 30-Oct-16 |
6 | Michelle | 120000 | 600 | 3-Dec-16 |
This sorts the data in the table by salary in ascending order, which for numbers, is from smallest to highest.
SORT operator
The task of the sort operator is to put in order the received input data. The following query will retrieve data from the SalesOrderDetail table and the ORDER BY statement provides that the result set will return in ascending order according to the ModifiedDate column.
1 |
SELECTCarrierTrackingNumber FROMSales.SalesOrderDetail ORDERBYModifiedDateASC |
When we check the query plan after the execution of the query, we will see that the storage engine reads the data by way of the clustered index scan operator. As a second step, the sort operator takes 121.317 rows as input and sorts them in ascending order.
Now, let’s take a new example query. This query will use an enlarging copy of the Adventureworks database and it will sort approximately 453.341 rows.
1 |
SELECTCreditCardApprovalCode,AccountNumber FROMSales.SalesOrderHeaderEnlarged WHERE DueDate>’20150601′ ORDERBYDueDateASC |
In the compilation phase of the query plan, the query optimizer calculates the memory requirement of the query based
on the estimated number of rows and row sizes, and this memory requirement is called a memory grant or query work
buffer. For some reasons (outdated statistics, wrong cardinality estimation, parameter sniffing, badly defined data
types) the memory grant might be calculated as wrong.
In the execution plan, we see a warning sign on the sort operator which means that the memory grant is not enough
for the sort operation and the query required more memory to perform the sort operation. In this circumstance,
during the execution of the query, the sort operator uses the tempdb database to meet the memory deficit. When we
analyze the sort operator properties, we can find out more detailed information about the tempdb spill issue.
The sort operator uses 45 MB memory but this memory amount is not enough to perform sorting all rows, for this
reason, sort operator used the tempdb database. During the execution of a query, the memory grant can not be changed
dynamically and insufficient memory grant estimations cause this type of issue.
Tip: Row Mode Memory Grant Feedback
feature in SQL Server 2019 helps to overcome this problem without any code changing. The main idea of this feature
is to adjust the memory grant requirement of a query to use the last execution memory grant information. With the
help of this feature, we can assume that several executions of the query the memory grant must be adjusted. The
below image illustrates memory grant changings after the four execution of the query. In the last execution of the
query, the optimizer has decided to find the proper memory grant amount for this query
At the same time, the following options can consider overcoming the tempdb spill issue:
- Creating an index that tunes the ORDER BY statement performance
- Using the MIN_GRANT_PERCENT query option
- Update the outdated statistics
Пример использования атрибутов ASC и DESC.
При сортировке набора результатов с использованием ORDER BY оператора MySQL вы можете использовать атрибуты ASC и DESC в одном предложении SELECT.
Например:
MySQL
SELECT supplier_city, supplier_state
FROM suppliers
WHERE supplier_name = ‘Microsoft’
ORDER BY supplier_city DESC, supplier_state ASC;
1 |
SELECTsupplier_city,supplier_state FROMsuppliers WHEREsupplier_name=’Microsoft’ ORDER BYsupplier_cityDESC,supplier_stateASC; |
Этот пример MySQL оператора ORDER BY будет возвращать все записи, отсортированные по полю supplier_city, в порядке убывания, с вторичной сортировкой по supplier_state в порядке возрастания.
UPDATE таблица
Следующая инструкция SQL обновляет первого клиента (CustomerID = 1) с новым контактным лицом и новым городом.
Пример
UPDATE Customers
SET ContactName = ‘Alfred Schmidt’, City= ‘Frankfurt’
WHERE CustomerID = 1;
Выбор из таблицы «Customers» теперь будет выглядеть следующим образом:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Alfred Schmidt | Obere Str. 57 | Frankfurt | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
Example — Sorting Results in Ascending Order
To sort your results in ascending order, you can specify the ASC attribute. If no value (ASC or DESC) is provided after a field in the ORDER BY clause, the sort order will default to ascending order. Let’s explore this further.
In this example, we have a table called customers with the following data:
customer_id | last_name | first_name | favorite_website |
---|---|---|---|
4000 | Jackson | Joe | techonthenet.com |
5000 | Smith | Jane | digminecraft.com |
6000 | Ferguson | Samantha | bigactivities.com |
7000 | Reynolds | Allen | checkyourmath.com |
8000 | Anderson | Paige | NULL |
9000 | Johnson | Derek | techonthenet.com |
Enter the following SQL statement:
Try It
SELECT * FROM customers ORDER BY last_name;
There will be 6 records selected. These are the results that you should see:
customer_id | last_name | first_name | favorite_website |
---|---|---|---|
8000 | Anderson | Paige | NULL |
6000 | Ferguson | Samantha | bigactivities.com |
4000 | Jackson | Joe | techonthenet.com |
9000 | Johnson | Derek | techonthenet.com |
7000 | Reynolds | Allen | checkyourmath.com |
5000 | Smith | Jane | digminecraft.com |
This example would return all records from the customers sorted by the last_name field in ascending order and would be equivalent to the following SQL ORDER BY clause:
Try It
SELECT * FROM customers ORDER BY last_name ASC;
SQL Учебник
SQL ГлавнаяSQL ВведениеSQL СинтаксисSQL SELECTSQL SELECT DISTINCTSQL WHERESQL AND, OR, NOTSQL ORDER BYSQL INSERT INTOSQL Значение NullSQL Инструкция UPDATESQL Инструкция DELETESQL SELECT TOPSQL MIN() и MAX()SQL COUNT(), AVG() и …SQL Оператор LIKESQL ПодстановочныйSQL Оператор INSQL Оператор BETWEENSQL ПсевдонимыSQL JOINSQL JOIN ВнутриSQL JOIN СлеваSQL JOIN СправаSQL JOIN ПолноеSQL JOIN СамSQL Оператор UNIONSQL GROUP BYSQL HAVINGSQL Оператор ExistsSQL Операторы Any, AllSQL SELECT INTOSQL INSERT INTO SELECTSQL Инструкция CASESQL Функции NULLSQL ХранимаяSQL Комментарии
SQL Учебник
SQL ГлавнаяSQL ВведениеSQL СинтаксисSQL SELECTSQL SELECT DISTINCTSQL WHERESQL AND, OR, NOTSQL ORDER BYSQL INSERT INTOSQL Значение NullSQL Инструкция UPDATESQL Инструкция DELETESQL SELECT TOPSQL MIN() и MAX()SQL COUNT(), AVG() и …SQL Оператор LIKESQL ПодстановочныйSQL Оператор INSQL Оператор BETWEENSQL ПсевдонимыSQL JOINSQL JOIN ВнутриSQL JOIN СлеваSQL JOIN СправаSQL JOIN ПолноеSQL JOIN СамSQL Оператор UNIONSQL GROUP BYSQL HAVINGSQL Оператор ExistsSQL Операторы Any, AllSQL SELECT INTOSQL INSERT INTO SELECTSQL Инструкция CASESQL Функции NULLSQL ХранимаяSQL Комментарии
SQL Учебник
SQL ГлавнаяSQL ВведениеSQL СинтаксисSQL SELECTSQL SELECT DISTINCTSQL WHERESQL AND, OR, NOTSQL ORDER BYSQL INSERT INTOSQL Значение NullSQL Инструкция UPDATESQL Инструкция DELETESQL SELECT TOPSQL MIN() и MAX()SQL COUNT(), AVG() и …SQL Оператор LIKESQL ПодстановочныйSQL Оператор INSQL Оператор BETWEENSQL ПсевдонимыSQL JOINSQL JOIN ВнутриSQL JOIN СлеваSQL JOIN СправаSQL JOIN ПолноеSQL JOIN СамSQL Оператор UNIONSQL GROUP BYSQL HAVINGSQL Оператор ExistsSQL Операторы Any, AllSQL SELECT INTOSQL INSERT INTO SELECTSQL Инструкция CASESQL Функции NULLSQL ХранимаяSQL Комментарии
Example 4 – ORDER BY Column Number
This example shows you how to order your results by specifying a column number.
SALESPERSON_ID | FIRST_NAME | SALARY | COMMISSION | HIRE_DATE |
4 | Tina | 87000 | 900 | 24-Oct-16 |
5 | Steve | 100000 | 500 | 2-Feb-16 |
2 | Sally | 95000 | 500 | 5-Sep-16 |
6 | Michelle | 120000 | 600 | 3-Dec-16 |
3 | Mark | 101000 | 800 | 12-Aug-16 |
1 | John | 90000 | 1000 | 1-Jan-16 |
8 | Jo | 115000 | 1200 | 30-Oct-16 |
7 | Alex | 85000 | (null) | 17-Jan-16 |
This sorts the results by the second column in the SELECT clause. In this case, it is the first_name column (salesperson_id is column 1, first_name is column 2, salary is 3, and so on).
This is the order of the columns in the SELECT clause, and not the table.
I try to avoid using column numbers when ordering, as it’s not clear which column is being ordered. Also, if the sequence that the columns are mentioned in the SELECT clause is changed, then the ordering will break, or order by the incorrect values.
Example 5 – ORDER BY a Column Alias
This example shows you how you can order by a column alias. This is very helpful to reduce the amount of code you write and to keep your logic in one place (the SELECT clause, for example).
SALESPERSON_ID | FIRST_NAME | TOTAL_EARNINGS |
7 | Alex | (null) |
6 | Michelle | 120600 |
8 | Jo | 116200 |
3 | Mark | 101800 |
5 | Steve | 100500 |
2 | Sally | 95500 |
1 | John | 91000 |
4 | Tina | 87900 |
This query shows the salespeople in order of their total earnings. Using a column alias in the SQL ORDER BY clause is helpful, especially when working with complicated functions.
Example 6 – ORDER BY an Expression
This example shows how you can order by an expression.
SALESPERSON_ID | FIRST_NAME | SALARY/52 |
6 | Michelle | 2307.692308 |
8 | Jo | 2211.538462 |
3 | Mark | 1942.307692 |
5 | Steve | 1923.076923 |
2 | Sally | 1826.923077 |
1 | John | 1730.769231 |
4 | Tina | 1673.076923 |
7 | Alex | 1634.615385 |
This query shows the weekly salary of each salesperson.
Example 7 – ORDER BY Function
This example shows how you can use ORDER BY with a function.
SALESPERSON_ID | FIRST_NAME | FLOOR(SALARY/52) |
6 | Michelle | 2307 |
8 | Jo | 2211 |
3 | Mark | 1942 |
5 | Steve | 1923 |
2 | Sally | 1826 |
1 | John | 1730 |
4 | Tina | 1673 |
7 | Alex | 1634 |
You can see that the results have been ordered by the function value.
Example 8 – ORDER BY with NULLS FIRST
This example shows how the NULLS FIRST keyword works.
SALESPERSON_ID | FIRST_NAME | SALARY | COMMISSION |
7 | Alex | 85000 | (null) |
2 | Sally | 95000 | 500 |
5 | Steve | 100000 | 500 |
6 | Michelle | 120000 | 600 |
3 | Mark | 101000 | 800 |
4 | Tina | 87000 | 900 |
1 | John | 90000 | 1000 |
8 | Jo | 115000 | 1200 |
As you can see, the NULL values are shown at the top of the list.
Example 9 – ORDER BY with NULLS LAST
This example shows how the NULLS LAST keyword works.
SALESPERSON_ID | FIRST_NAME | SALARY | COMMISSION |
2 | Sally | 95000 | 500 |
5 | Steve | 100000 | 500 |
6 | Michelle | 120000 | 600 |
3 | Mark | 101000 | 800 |
4 | Tina | 87000 | 900 |
1 | John | 90000 | 1000 |
8 | Jo | 115000 | 1200 |
7 | Alex | 85000 | (null) |
As you can see, the NULL values are shown at the bottom of the list.
Example 10 – ORDER BY Two Columns
This example shows how you can use SQL ORDER BY with two columns.
SALESPERSON_ID | FIRST_NAME | SALARY | COMMISSION |
2 | Sally | 95000 | 500 |
5 | Steve | 100000 | 500 |
6 | Michelle | 120000 | 600 |
3 | Mark | 101000 | 800 |
4 | Tina | 87000 | 900 |
1 | John | 90000 | 1000 |
8 | Jo | 115000 | 1200 |
7 | Alex | 85000 | (null) |
This query orders by the commission values in ascending order, then for records where the commission is the same, it orders by salary in ascending order.
Example 11 – ORDER BY Two Columns in Different Order
This example orders by two columns, but they are in a different order.
SALESPERSON_ID | FIRST_NAME | SALARY | COMMISSION |
5 | Steve | 100000 | 500 |
2 | Sally | 95000 | 500 |
6 | Michelle | 120000 | 600 |
3 | Mark | 101000 | 800 |
4 | Tina | 87000 | 900 |
1 | John | 90000 | 1000 |
8 | Jo | 115000 | 1200 |
7 | Alex | 85000 | (null) |
This query orders by the commission values in ascending order, then for records where the commission is the same, it orders by salary in descending order.
So, that’s how you can use the SQL ORDER BY clause in Oracle SQL to order your results. It’s a powerful clause and has a few keywords to get you the result that you need.
Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!
Пример — сортировка результатов по убыванию
При сортировке набора результатов в порядке убывания вы используете атрибут DESC в предложении ORDER BY. Давайте внимательнее посмотрим.
В этом примере у нас есть таблица suppliers со следующими данными:
supplier_id | supplier_name | city | state |
---|---|---|---|
100 | Yandex | Moscow | Russian |
200 | Lansing | Michigan | |
300 | Oracle | Redwood City | California |
400 | Bing | Redmond | Washington |
500 | Yahoo | Sunnyvale | Washington |
600 | DuckDuckGo | Paoli | Pennsylvania |
700 | Qwant | Paris | France |
800 | Menlo Park | California | |
900 | Electronic Arts | San Francisco | California |
Введите следующий SQL оператор.
PgSQL
SELECT *
FROM suppliers
WHERE supplier_id > 40
ORDER BY supplier_id DESC;
1 |
SELECT* FROMsuppliers WHEREsupplier_id>40 ORDERBYsupplier_idDESC; |
Будет выбрано 5 записей. Вот результаты, которые вы должны получить.
supplier_id | supplier_name | city | state |
---|---|---|---|
900 | Electronic Arts | San Francisco | California |
800 | Menlo Park | California | |
700 | Qwant | Paris | France |
600 | DuckDuckGo | Paoli | Pennsylvania |
500 | Yahoo | Sunnyvale | Washington |
В этом примере будет отсортирован набор результатов по полю supplier_id в порядке убывания.
Пример сортировки без использования атрибута ASC / DESC
MySQL оператор ORDER BY может использоваться без указания атрибута ASC или DESC. Когда этот атрибут опущен в предложении ORDER BY, порядок сортировки по умолчанию равен ASC или по возрастанию.
Например:
MySQL
SELECT city
FROM customers
WHERE customer_name = ‘Dell’
ORDER BY city;
1 |
SELECTcity FROMcustomers WHEREcustomer_name=’Dell’ ORDER BYcity; |
Этот пример MySQL ORDER BY возвратит все записи, отсортированные по полю city, в порядке возрастания и будет эквивалентен следующему примеру ORDER BY:
MySQL
SELECT city
FROM customers
WHERE customer_name = ‘Apple’
ORDER BY city ASC;
1 |
SELECTcity FROMcustomers WHEREcustomer_name=’Apple’ ORDER BYcityASC; |
Большинство программистов опускают атрибут ASC при сортировке в порядке возрастания.
Update предупреждение!
Будьте осторожны при обновлении записей. Если вы опустите предложение WHERE, все записи будут обновлены!
Пример
UPDATE Customers
SET ContactName=’Juan’;
Выбор из таблицы «Customers» теперь будет выглядеть следующим образом:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Juan | Obere Str. 57 | Frankfurt | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Juan | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Juan | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 | Around the Horn | Juan | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Juan | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
Синтаксис
Синтаксис оператора ORDER BY в MySQL:
SELECT expressions
FROM tables
ORDER BY expression ;
Параметры или аргументы
expressions — столбцы или вычисления, которые вы хотите получить.
tables — таблицы, из которых вы хотите получить записи. Должна быть хотя бы одна таблица, перечисленная в операторе FROM.
WHERE conditions — необязательный. Условия, которые должны быть выполнены для выбранных записей.ASC — необязательный. Сортирует результирующий набор по expression в порядке возрастания (по умолчанию, если атрибут не указан).DESC — необязательный. Сортирует результирующий набор по expression в порядке убывания.
SQL Server ORDER BY clause example
We will use the table in the sample database from the demonstration.
A) Sort a result set by one column in ascending order
The following statement sorts the customer list by the first name in ascending order:
In this example, because we did not specify or , the clause used by default.
B) Sort a result set by one column in descending order
The following statement sorts the customer list by the first name in descending order.
In this example, because we specified the explicitly, the clause sorted the result set by values in the column in the descending order.
C) Sort a result set by multiple columns
The following statement retrieves the first name, last name, and city of the customers. It sorts the customer list by the city first and then by the first name.
D) Sort a result set by multiple columns and different orders
The following statement sorts the customers by the city in descending order and the sort the sorted result set by the first name in ascending order.
E) Sort a result set by a column that is not in the select list
It is possible to sort the result set by a column that does not appear on the select list. For example, the following statement sorts the customer by the state even though the column does not appear on the select list.
Note that the column is defined in the table. If it was not, then you would have an invalid query.
F) Sort a result set by an expression
The function returns the number of characters of a string. The following statement uses the function in the clause to retrieve a customer list sorted by the length of the first name.
G) Sort by ordinal positions of columns
SQL Server allows you to sort the result set based on the ordinal positions of columns that appear in the select list.
The following statement sorts the customers by first name and last name. But instead of specifying the column names explicitly, it uses the ordinal positions of the columns:
In this example, 1 means the column and 2 means the column.
Using the ordinal positions of columns in the clause is considered as bad programming practice for a couple of reasons.
- First, the columns in a table don’t have ordinal positions and need to be referenced by name.
- Second, when you modify the select list, you may forget to make the corresponding changes in the clause.
Therefore, it is a good practice to always specify the column names explicitly in the clause.
In this tutorial, you have learned how to use the SQL Server clause to sort a result set by columns in ascending or descending order.
Example — Using both ASC and DESC attributes
When sorting your result set using the SQL ORDER BY clause, you can use the ASC and DESC attributes in a single SELECT statement.
In this example, let’s use the same products table as the previous example:
product_id | product_name | category_id |
---|---|---|
1 | Pear | 50 |
2 | Banana | 50 |
3 | Orange | 50 |
4 | Apple | 50 |
5 | Bread | 75 |
6 | Sliced Ham | 25 |
7 | Kleenex | NULL |
Now enter the following SQL statement:
Try It
SELECT * FROM products WHERE product_id <> 7 ORDER BY category_id DESC, product_name ASC;
There will be 6 records selected. These are the results that you should see:
product_id | product_name | category_id |
---|---|---|
5 | Bread | 75 |
4 | Apple | 50 |
2 | Banana | 50 |
3 | Orange | 50 |
1 | Pear | 50 |
6 | Sliced Ham | 25 |
This example would return the records sorted by the category_id field in descending order, with a secondary sort by product_name in ascending order.
SQL ORDER BY clause examples
We will use the table in the sample database for the demonstration.
1) Using SQL clause to sort values in one column example
The following statement retrieves the employee id, first name, last name, hire date, and salary from the table:
It seems that the rows appear as they are stored in the table. To sort employees by first names alphabetically, you add an clause to query as follows:
The result set now is sorted by the column.
2) Using SQL clause to sort values in multiple columns example
To sort by the employees by the first name in ascending order and the last name in descending order, you use the following statement:
First, the database system sorts the result set by the first name in ascending order, then it sorts the sorted result set by the last name in descending order. Notice the change in position of two employees: and
3) Using SQL clause to sort values in a numeric column example
SQL allows you to sort data alphabetically as shown in the previous example and also sort data numerically. For example, the following statement selects employee data and sorts the result set by salary in the descending order:
4) Using SQL to sort dates example
Besides the character and numeric, SQL allows you to sort the result set by date. The following statement sorts the employees by values in the column in the ascending order.
To view the latest employees who have just joined the company, you sort the employees by the hire dates in the descending order as shown in the following statement:
In this tutorial, you have learned how to use the SQL clause to sort the result set based on one or more columns in the ascending or descending order.
Syntax and Parameters of SQL ORDER BY
The syntax of the Oracle SQL ORDER BY clause is:
In this clause:
- column_name is one of the columns in your SELECT clause or in your table that you want to order by.
- column_position is a number that refers to the position of a column in your SELECT statement.
- expression is a valid SQL expression that you want to order your results by
- ASC or DESC can be used to specify the order of the data. ASC is ascending, and DESC is descending. This is optional, and if it is not provided, the default sort order is ASC.
- NULLS FIRST or NULLS LAST can be used to specify how NULL values are sorted. NULLS FIRST means that NULL values are shown at the top of the list, and NULLS LAST means that NULL values are shown at the bottom of the list. The default treatment if this is not specified is NULLS FIRST if the sort is DESC, or NULLS LAST if the sort is ASC or not specified.
Also, the column that you order by does not need to exist in the SELECT clause. So you don’t need to see the column in your results to use it in the ORDER BY.
Example — Sorting Results in descending order
When sorting your result set in descending order, you use the DESC attribute in your ORDER BY clause. Let’s take a closer look.
In this example, we have a table called suppliers with the following data:
supplier_id | supplier_name | city | state |
---|---|---|---|
100 | Microsoft | Redmond | Washington |
200 | Mountain View | California | |
300 | Oracle | Redwood City | California |
400 | Kimberly-Clark | Irving | Texas |
500 | Tyson Foods | Springdale | Arkansas |
600 | SC Johnson | Racine | Wisconsin |
700 | Dole Food Company | Westlake Village | California |
800 | Flowers Foods | Thomasville | Georgia |
900 | Electronic Arts | Redwood City | California |
Enter the following SQL statement:
Try It
SELECT * FROM suppliers WHERE supplier_id > 400 ORDER BY supplier_id DESC;
There will be 5 records selected. These are the results that you should see:
supplier_id | supplier_name | city | state |
---|---|---|---|
900 | Electronic Arts | Redwood City | California |
800 | Flowers Foods | Thomasville | Georgia |
700 | Dole Food Company | Westlake Village | California |
600 | SC Johnson | Racine | Wisconsin |
500 | Tyson Foods | Springdale | Arkansas |
Пример — использование атрибутов ASC и DESC
При сортировке набора результатов с помощью SQL предложения ORDER BY вы можете использовать атрибуты ASC и DESC в одном операторе SELECT.
В этом примере давайте использовать ту же таблицу products, что и в предыдущем примере.
product_id | product_name | category_id |
---|---|---|
1 | Pear | 50 |
2 | Banana | 50 |
3 | Orange | 50 |
4 | Apple | 50 |
5 | Bread | 75 |
6 | Sliced Ham | 25 |
7 | Kleenex | NULL |
Теперь введите следующий SQL оператор.
PgSQL
SELECT *
FROM products
WHERE product_id <>
ORDER BY category_id DESC,
product_name ASC;
1 |
SELECT* FROMproducts WHEREproduct_id<> ORDERBYcategory_idDESC, product_nameASC; |
Будет выбрано 6 записей. Вот результаты, которые вы должны получить.
product_id | product_name | category_id |
---|---|---|
5 | Bread | 75 |
4 | Apple | 50 |
2 | Banana | 50 |
3 | Orange | 50 |
1 | Pear | 50 |
6 | Sliced Ham | 25 |
В этом примере возвращаются записи, отсортированные по полю category_id в порядке убывания, а вторичная сортировка — по полю product_name в порядке возрастания.