Filtering and sorting篩選與排序

A sales manager asks for the customers who owe the company money, largest debt first. This chapter keeps only the rows that meet a condition, combines conditions, sorts the result, and shows how a filter that looks exact can leave customers out without any warning.

一位銷售經理要一份欠公司錢的客戶名單,欠款最多的排在最前。本章會只保留符合條件的行、組合多個條件、為結果排序,並說明一個看似準確的篩選條件,如何在毫無警告的情況下漏掉客戶。

Builds on 先修內容
Chapter 1
Reading time 閱讀時間
About 30 minutes
Tables 數據表
customer, nation, orders
Runs in 執行環境
Your browser

Who owes us money?誰欠我們錢?

The company sells to 5 market segments, recorded in c_mktsegment. The sales manager for the Building segment is about to confirm next quarter’s orders and wants a list first: every Building customer whose account balance is negative, largest debt first. In this company’s records a negative c_acctbal means the customer has been invoiced for more than it has paid.

公司把客戶分為 5 個市場板塊,記錄在 c_mktsegment 中。負責 Building(建築)板塊的銷售經理準備確認下一季的訂單,在此之前想要一份名單:所有戶口結餘為負數的 Building 客戶,欠款最多的排在最前。在這家公司的記錄中,c_acctbal 為負數,表示公司開出的發票金額多於客戶已付的款項。

The credit team will call each customer on the list before accepting another order. A customer missing from the list is not called, and keeps buying on credit. The list has to be complete, not just plausible.

信貸部會在接受新訂單前,逐一致電名單上的客戶。不在名單上的客戶不會接到電話,並會繼續賒賬購貨。所以這份名單必須完整,而不只是看起來合理。

In Excel: AutoFilter在 Excel 中:自動篩選

In Excel you would turn on AutoFilter, open the drop-down on the segment column and tick BUILDING, then open the balance column and choose Number Filters, Less Than, 0. Sort Smallest to Largest puts the largest debt first. Each SQL idea in this chapter has a counterpart there:

在 Excel 中,你會開啟「自動篩選」,打開板塊欄的下拉清單並勾選 BUILDING,再打開結餘欄,選擇「數字篩選」中的「小於」,輸入 0。「從最小到最大排序」會把欠款最多的排在最前。本章每個 SQL 概念在 Excel 中都有對應的操作:

  • Ticking values or choosing a number filter is WHERE.

    勾選數值或選擇數字篩選,相當於 WHERE。

  • Filtering two columns at once is AND.

    同時篩選兩欄,相當於 AND。

  • Ticking several values in one column is IN; the “between” number filter is BETWEEN; text filters such as “begins with” are LIKE.

    在同一欄勾選多個數值,相當於 IN;數字篩選中的「介於」相當於 BETWEEN;「開頭是」等文字篩選相當於 LIKE。

  • Sorting is ORDER BY.

    排序相當於 ORDER BY。

The comparison stops working in three places, and the third matters most for this chapter.

這個比較在三個地方不再成立,第三點對本章最重要。

  • A filter in Excel is a state of the worksheet. Nobody can see later which boxes were ticked. A SQL filter is written down: it can be saved, read by a colleague and run again next month.

    Excel 的篩選是工作表當時的狀態。事後沒有人看得到當時勾選了甚麼。SQL 的篩選條件是寫下來的:可以保存、讓同事閱讀,下個月再執行一次。

  • Excel ignores capitals. In the drop-down list, “building” and “BUILDING” are one entry. The database used here treats them as different values.

    Excel 不分大小寫。在下拉清單中,「building」和「BUILDING」是同一項。本教程使用的數據庫則把它們當作不同的值。

  • Excel shows you the values; SQL does not. The drop-down lists every distinct value in the column, so an odd one has a chance of being noticed. In SQL you type the value you expect and see only the rows that match it. Rows that do not match are simply absent.

    Excel 會讓你看到所有值,SQL 不會。下拉清單會列出該欄每一個不同的值,所以異常的值有機會被發現。在 SQL 中,你輸入預期的值,只會看到符合的行;不符合的行就這樣消失了。

Keeping the rows you need只保留需要的行

WHERE keeps the rows for which a condition is true and drops the rest. It comes after FROM. Start with the balance alone:

WHERE 只保留條件成立的行,其餘一概捨棄。它寫在 FROM 之後。先只看結餘:

count_star()
143

1 row

143 of the 1,552 customer records have a negative balance. The database checks the condition against each row in turn. COUNT(*) then counts the rows that are left. The comparison operators are:

在 1,552 條客戶記錄中,有 143 條結餘為負數。數據庫逐行檢查條件,然後由 COUNT(*) 計算剩下的行數。比較運算符如下:

Operator 運算符Meaning 意思Example 例子
=Equal to 等於c_mktsegment = 'BUILDING'
<>Not equal to (also written !=) 不等於(亦可寫作 !=)c_mktsegment <> 'BUILDING'
<Less than 小於c_acctbal < 0
<=Less than or equal to 小於或等於c_acctbal <= 0
>Greater than 大於c_acctbal > 9000
>=Greater than or equal to 大於或等於c_acctbal >= 9000
  • Text goes in single quotes: 'BUILDING'. Double quotes mean something else in most databases (a column name), so do not use them for values.

    文字要放在單引號內:'BUILDING'。在大多數數據庫中,雙引號另有用途(表示欄名),所以不要用來寫值。

  • Numbers have no quotes and no thousands separators: 9000, not '9,000'.

    數字不加引號,也不加千位分隔符:寫 9000,不要寫 '9,000'。

  • < 0 excludes zero. No balance in this table is exactly zero (0 rows), but in other data the difference between < and <= can matter, so choose deliberately.

    < 0 不包括零。這張表中沒有結餘剛好是零的記錄(0 行),但在其他數據中,< 和 <= 的分別可能很重要,要刻意選擇。

Combining conditions組合多個條件

The manager wants two conditions at once: the Building segment and a negative balance. AND keeps a row only if both are true:

經理要求兩個條件同時成立:屬於 Building 板塊,以及結餘為負數。AND 只保留兩個條件都成立的行:

count_star()
38

1 row

38 customers. Hold on to that number; Section 7 comes back to it.

38 個客戶。請記住這個數字,第 7 節會再談到它。

OR keeps a row if either condition is true. Suppose the manager also covers Machinery and asks for the negative balances in both segments. This looks right but is not:

OR 則只要任何一個條件成立就保留該行。假設經理同時負責 Machinery(機械)板塊,想要兩個板塊中結餘為負數的客戶。以下寫法看似正確,其實不然:

count_star()
347

1 row

347 rows. AND is applied before OR, as multiplication comes before addition, so the database reads the condition as “Building, or (Machinery and negative)”. The result is every one of the 326 Building records whatever their balance, plus the 21 Machinery records with a negative balance. Parentheses fix it: (c_mktsegment = 'BUILDING' OR c_mktsegment = 'MACHINERY') AND c_acctbal < 0 returns 59.

347 行。AND 比 OR 先計算,就像乘法先於加法,所以數據庫把條件理解為「Building,或者(Machinery 而且結餘為負)」。結果包括全部 326 條 Building 記錄(不論結餘多少),再加上 21 條結餘為負數的 Machinery 記錄。加上括號就能修正:(c_mktsegment = 'BUILDING' OR c_mktsegment = 'MACHINERY') AND c_acctbal < 0 返回 59。

Lists, ranges and patterns清單、範圍與模式

IN tests a value against a list. It is a shorter way to write several OR conditions on one column, and it removes the precedence problem above:

IN 檢查一個值是否在清單之中。它是在同一欄寫多個 OR 條件的簡寫,也避免了上面的運算次序問題:

count_star()
59

1 row

BETWEEN tests a range, and includes both ends. The customers who owe between 500 and 1,000:

BETWEEN 檢查一個範圍,並包括兩端的值。欠款介乎 500 至 1,000 的客戶:

count_star()
73

1 row

The smaller value comes first. BETWEEN -500 AND -1000 is read as “at least −500 and at most −1,000”, which no number satisfies, so it returns 0 rows without an error. With negative numbers the smaller value is the one further from zero, which is easy to get backwards.

較小的值要寫在前面。BETWEEN -500 AND -1000 的意思是「不少於 −500 而且不多於 −1,000」,沒有任何數字符合,所以會返回 0 行,而且不會報錯。負數之中,離零越遠的值越小,這一點很容易弄反。

LIKE matches text against a pattern. % stands for any number of characters, including none, and _ stands for exactly one. The nation table lists the company’s 25 countries:

LIKE 用模式來比對文字。% 代表任意數目的字元(包括零個),_ 代表剛好一個字元。nation 表列出公司業務涉及的 25 個國家:

n_nationkeyn_name
23UNITED KINGDOM
24UNITED STATES

2 rows

'UNITED%' means “starts with UNITED”, '%IA' means “ends with IA” and '%LAND%' means “contains LAND”. Like =, LIKE in this database distinguishes capitals from lower case.

'UNITED%' 表示「以 UNITED 開頭」,'%IA' 表示「以 IA 結尾」,'%LAND%' 表示「包含 LAND」。和 = 一樣,這個數據庫的 LIKE 也區分大小寫。

Sorting the result為結果排序

Chapter 1 noted that without an instruction a database may return rows in any order. ORDER BY gives that instruction. It comes after WHERE, and LIMIT comes last. Here are the ten largest debts in the Building segment:

第 1 章提到,如果沒有指定,數據庫可以按任何次序返回結果。ORDER BY 就是用來指定次序的。它寫在 WHERE 之後,LIMIT 則放在最後。以下是 Building 板塊中欠款最多的十個客戶:

c_custkeyc_namec_acctbal
294Customer#000000294-994.79
1235Customer#000001235-982.05
1013Customer#000001013-951.53
1244Customer#000001244-942.80
1430Customer#000001430-920.40
1284Customer#000001284-911.40
1000Customer#000001000-881.70
709Customer#000000709-867.94
872Customer#000000872-858.61
858Customer#000000858-829.37

10 rows

  • The default order is ascending, smallest first. Since the balances are negative, the smallest balance is the largest debt, so ascending is what the manager wants. Add DESC after a column to sort it in descending order.

    預設是升序,最小的排在最前。由於結餘是負數,最小的結餘就是最大的欠款,所以升序正是經理想要的。在欄名後加上 DESC 就會按降序排列。

  • Several columns can be listed. The second is used only where the first is tied. c_custkey is unique, so adding it at the end makes the order the same every time the query runs.

    可以列出多欄,只有在第一欄相同時才會用第二欄排序。c_custkey 是唯一的,加在最後可以確保每次執行查詢時次序都一樣。

  • LIMIT after ORDER BY gives a “top N”. LIMIT without ORDER BY gives any N rows.

    ORDER BY 之後加 LIMIT,得出的是「前 N 名」。沒有 ORDER BY 的 LIMIT,得出的只是任意 N 行。

Remove LIMIT 10 and run the query: you get the full list of 38 customers that would go to the manager.

刪去 LIMIT 10 再執行查詢,就會得到交給經理的完整名單,共 38 個客戶。

The customers the filter missed篩選漏掉的客戶

Is the list of 38 complete? The condition c_mktsegment = 'BUILDING' finds every row whose segment is exactly those eight capital letters. Before trusting it, ask which values the column actually holds. DISTINCT returns each different value once, and LENGTH counts its characters:

這份 38 人的名單完整嗎?條件 c_mktsegment = 'BUILDING' 會找出板塊剛好是這八個大寫字母的每一行。在相信它之前,先問這一欄實際上有哪些值。DISTINCT 會把每個不同的值返回一次,LENGTH 則計算字元數目:

c_mktsegmentcharacters
AUTOMOBILE10
AUTOMOBILE 11
BUILDING8
BUILDING 9
FURNITURE9
FURNITURE 10
HOUSEHOLD9
HOUSEHOLD 10
MACHINERY9
MACHINERY 10
automobile10
building8
furniture9
household9
machinery9

15 rows

The company has 5 segments, but the column holds 15 different values. Some were typed in lower case; others have a space at the end, which you can see only in the character count: “BUILDING ” has 9. The sales staff enter the segment by hand, and nothing in the system stops them. To =, “building” and “BUILDING ” are simply different text.

公司只有 5 個板塊,這一欄卻有 15 個不同的值。有些以小寫輸入,有些在尾部多了一個空格,只能從字元數目看出來:「BUILDING 」有 9 個字元。板塊由銷售人員人手輸入,系統並沒有加以限制。對 = 來說,「building」和「BUILDING 」根本是不同的文字。

The fix is to tidy the value before comparing it. TRIM removes spaces at both ends, and UPPER turns letters into capitals, so UPPER(TRIM(c_mktsegment)) turns all three spellings into “BUILDING”:

修正方法是在比較前先整理這個值。TRIM 會刪去兩端的空格,UPPER 會把字母轉為大寫,所以 UPPER(TRIM(c_mktsegment)) 會把三種寫法都變成「BUILDING」:

c_custkeyc_namec_acctbalc_mktsegment
294Customer#000000294-994.79BUILDING
1235Customer#000001235-982.05BUILDING
1013Customer#000001013-951.53BUILDING
1244Customer#000001244-942.80BUILDING
1430Customer#000001430-920.40BUILDING
1284Customer#000001284-911.40BUILDING
1000Customer#000001000-881.70BUILDING
709Customer#000000709-867.94BUILDING
872Customer#000000872-858.61BUILDING
858Customer#000000858-829.37BUILDING
109Customer#000000109-716.10building
1091Customer#000001091-710.53BUILDING
329Customer#000000329-651.91BUILDING
64Customer#000000064-646.64BUILDING
204Customer#000000204-627.76BUILDING
665Customer#000000665-616.79BUILDING
905Customer#000000905-600.73BUILDING
818Customer#000000818-574.39BUILDING
754Customer#000000754-566.86BUILDING
349Customer#000000349-565.35BUILDING
98Customer#000000098-551.37BUILDING
615Customer#000000615-482.48BUILDING
1223Customer#000001223-413.03BUILDING
334Customer#000000334-405.91BUILDING
1300Customer#000001300-370.44BUILDING
995Customer#000000995-341.79BUILDING
861Customer#000000861-336.80BUILDING
523Customer#000000523-275.73BUILDING
11Customer#000000011-272.60BUILDING
1061Customer#000001061-258.77BUILDING
478Customer#000000478-210.40BUILDING
1364Customer#000001364-181.69BUILDING
580Customer#000000580-181.63BUILDING
1115Customer#000001115-178.52BUILDING
1316Customer#000001316-158.39BUILDING
647Customer#000000647-132.97BUILDING
400Customer#000000400-98.46BUILDING
439Customer#000000439-61.29BUILDING
1277Customer#000001277-52.35building
978Customer#000000978-50.51BUILDING
458Customer#000000458-38.42BUILDING

41 rows

41 customers, not 38. These are the ones the first list left out:

是 41 個客戶,而不是 38 個。以下是第一份名單漏掉的客戶:

c_custkeyc_namec_acctbalc_mktsegment
109Customer#000000109-716.10building
995Customer#000000995-341.79BUILDING
1277Customer#000001277-52.35building

3 rows

The naive query missed 3 of 41 customers, about 7% of the list. They are not small cases: customer 109 owes 716.10, number 11 on the corrected list. Across the whole segment, c_mktsegment = 'BUILDING' finds 326 of 346 records and misses 20. No query raised an error, and 38 looked like a reasonable number.

原本的查詢在 41 個客戶中漏掉了 3 個,約佔名單的 7%。這些並不是無關痛癢的個案:客戶 109 欠款 716.10,在修正後的名單上排第 11 位。就整個板塊而言,c_mktsegment = 'BUILDING' 只找到 346 條記錄中的 326 條,漏掉 20 條。整個過程沒有任何查詢報錯,而 38 看起來也是個合理的數字。

Two partial fixes are worth recognising. c_mktsegment LIKE 'BUILDING%' catches the trailing space but not the lower case, and returns 39. And the original query would have returned the full list on some other databases: SQL Server, for example, by default ignores both capitals and trailing spaces when comparing text. The same SQL can give different answers on different systems, so check the data rather than relying on the database to be forgiving.

有兩種只修正了一半的做法值得認識。c_mktsegment LIKE 'BUILDING%' 能捕捉尾部空格,卻捕捉不到小寫,返回 39。此外,在某些其他數據庫上,原本的查詢會返回完整名單:例如 SQL Server 在預設設定下比較文字時,會同時忽略大小寫和尾部空格。同一條 SQL 在不同系統上可以得出不同答案,所以要檢查數據本身,而不是依賴數據庫的寬容。

When AI writes the query當 AI 替你寫查詢

Ask an AI assistant for “Building customers with a negative balance, largest debt first” and you will very likely get WHERE c_mktsegment = 'BUILDING' AND c_acctbal < 0 ORDER BY c_acctbal. The SQL is correct for clean data. The assistant has not seen your data, so it writes the value the question names, in the spelling the documentation uses.

如果你要求 AI 助手列出「結餘為負數的 Building 客戶,欠款最多的排在最前」,它很可能會給你 WHERE c_mktsegment = 'BUILDING' AND c_acctbal < 0 ORDER BY c_acctbal。對乾淨的數據而言,這條 SQL 是正確的。但助手沒有看過你的數據,所以只會按問題中提到的值、用文件中的寫法去寫。

This adds the second item to the checklist: before filtering on a text column, list its distinct values. If there are variants, either give them to the assistant in the prompt or check that its query handles them. A quick test is to count the rows matched by = and by UPPER(TRIM(...)); if the counts differ, the filter needs attention.

這為清單加上第二項:按文字欄篩選之前,先列出它所有不同的值。如果有不同寫法,要麼在提示中告訴助手,要麼檢查它的查詢是否已處理。一個快速的測試是分別計算 = 和 UPPER(TRIM(...)) 找到的行數;如果兩者不同,這個篩選條件就需要處理。

  • What does one row represent? (Chapter 1)

    一行代表甚麼?(第 1 章)

  • Does a text filter match every spelling the column actually holds? (Chapter 2)

    文字篩選是否涵蓋這一欄實際存在的所有寫法?(第 2 章)

Check your understanding自我測驗

  1. How many Automobile customers have a balance above 9,000? Write the query so that it does not miss any spelling of the segment.

    有多少個 Automobile(汽車)板塊的客戶結餘高於 9,000?寫出查詢,並確保不會漏掉該板塊的任何寫法。

    Answer 答案
    count_star()
    32

    1 row

    c_mktsegment = 'AUTOMOBILE' would return 30. The original TPC-H table gives 32, the same as the query above.

    c_mktsegment = 'AUTOMOBILE' 會返回 30。原始 TPC-H 表得出 32,與上面的查詢相同。

  2. A colleague writes WHERE c_acctbal BETWEEN -500 AND -1000 and gets no rows. The colleague concludes that no customer owes between 500 and 1,000. What went wrong?

    一位同事寫了 WHERE c_acctbal BETWEEN -500 AND -1000,結果沒有任何行,於是斷定沒有客戶欠款介乎 500 至 1,000。問題出在哪裏?

    Answer 答案

    BETWEEN needs the smaller value first, and −1,000 is smaller than −500. Written the right way round, BETWEEN -1000 AND -500, the query finds the customers in Section 5. An empty result is not proof that nothing exists; it may mean the condition can never be true.

    BETWEEN 要求較小的值在前,而 −1,000 比 −500 小。按正確次序寫成 BETWEEN -1000 AND -500,就會找到第 5 節中的客戶。結果為空並不證明甚麼都不存在,也可能代表條件根本不可能成立。

  3. List the countries in nation whose names end in IA, in alphabetical order.

    按字母次序列出 nation 中名稱以 IA 結尾的國家。

    Answer 答案
    n_name
    ALGERIA
    ETHIOPIA
    INDIA
    INDONESIA
    ROMANIA
    RUSSIA
    SAUDI ARABIA

    7 rows

  4. Find the five largest orders, by o_totalprice, placed in the first quarter of 1998. Write a date as DATE '1998-01-01'. Look closely at the result.

    找出 1998 年第一季下單、o_totalprice 最高的五張訂單。日期寫作 DATE '1998-01-01'。請仔細看看結果。

    Answer 答案
    o_orderkeyo_custkeyo_orderdateo_totalprice
    3945610161998-02-16409770.83
    3945610161998-02-16409770.83
    1577910031998-02-24405401.76
    25676941998-02-27366949.49
    4381011411998-03-15345675.99

    5 rows

    Order 39,456 appears twice. The orders table contains duplicate rows, so the duplicate pushes a real order out of the top five. Chapter 15 removes them. BETWEEN works for dates because o_orderdate is a DATE; on a column that also holds a time of day, DATE '1998-03-31' would mean midnight at the start of 31 March and exclude the rest of that day.

    訂單 39,456 出現了兩次。orders 表中有重複的行,重複的一行把一張真正的訂單擠出了前五名。第 15 章會刪除這些重複。BETWEEN 適用於日期,是因為 o_orderdate 的類型是 DATE;如果欄中還包含時間,DATE '1998-03-31' 會被理解為 3 月 31 日開始的午夜,因而排除當天其餘時間。

Sources 資料來源

  • Practice data derived from the TPC-H benchmark of the Transaction Processing Performance Council, generated with tpchgen-cli at scale factor 0.01. The inconsistent segment spellings were added for this tutorial (issue C2).
  • DuckDB, Comparisons: comparison operators and BETWEEN. DuckDB, Pattern matching: LIKE.
  • Queries run with DuckDB-WASM. Every result and figure on this page was produced with the same build.

How this tutorial was made: AI Diligence Statement