What a table really is一張表到底是甚麼

A sales director asks how many customers the company has. The table holds the answer, or seems to. This chapter writes the first queries, reads what a table’s columns and types say about it, and shows why the obvious number is not yet an answer.

銷售總監問公司有多少客戶。答案似乎就在表裏。本章會寫出第一批查詢,從表的欄和類型了解這張表,並說明為甚麼最直接得到的數字還不是答案。

Builds on 先修內容
Nothing: start here
Reading time 閱讀時間
About 25 minutes
Tables 數據表
customer, orders, lineitem
Runs in 執行環境
Your browser

Monday morning’s question星期一早上的問題

It is Monday morning, and the sales director asks a simple question: how many customers do we have? The company keeps its customers in a table called customer. Count its rows and you get 1,552.

星期一早上,銷售總監問了一個簡單的問題:我們有多少客戶?公司把客戶資料存放在一張名為 customer 的表中。數一數它的行數,會得到 1,552。

It is tempting to reply with that number. By the end of this chapter you will know why 1,552 is not yet an answer, and what to ask before you give one.

你很可能會直接回覆這個數字。讀完本章,你會明白為甚麼 1,552 還算不上答案,以及在回答之前應該先問甚麼。

A table, compared with a spreadsheet表與電子試算表的比較

If you have used Excel, a table will look familiar: rows run down, columns run across. Each row of customer is one customer record, and each column holds one piece of information about it, such as a name or a phone number.

如果你用過 Excel,表的樣子會很熟悉:行向下排列,欄向右排列。customer 的每一行是一條客戶記錄,每一欄存放這條記錄的一項資料,例如名稱或電話號碼。本教程中,「行」指 row,「欄」指 column。

Four differences matter from the start:

從一開始就有四個值得留意的分別:

  • Every column has one type. A column declared as a date can hold only dates. In Excel, any cell can hold anything.

    每一欄只有一種類型。宣告為日期的欄只能存放日期。在 Excel 中,任何儲存格都可以放任何內容。

  • Columns have names, not letters. There are no merged cells, blank header rows or totals mixed in with the data.

    欄有名稱,而不是字母。表中沒有合併儲存格、空白標題行,也不會把合計混在數據之中。

  • There are no formulas in the table. Calculations happen in the query, so the stored data stays the same whoever looks at it.

    表中沒有公式。計算在查詢中進行,所以無論誰查看,儲存的數據都保持不變。

  • Size. An Excel worksheet stops at 1,048,576 rows. Our lineitem table has 60,175 rows because the practice data is scaled down to run in a browser. At the standard size of the TPC-H benchmark it has 6,001,215, nearly six times what a worksheet can hold.

    規模。Excel 工作表最多只有 1,048,576 行。我們的 lineitem 表有 60,175 行,因為練習數據已按比例縮小,以便在瀏覽器中執行。按 TPC-H 基準測試的標準規模,它有 6,001,215 行,接近一張工作表上限的六倍。

Your first query第一條查詢

Ask the database for the first five rows of customer:

請數據庫列出 customer 的頭五行:

c_custkeyc_namec_addressc_nationkeyc_phonec_acctbalc_mktsegmentc_comment
1Customer#000000001IVhzIApeRb ot,c,E1525-989-741-2988711.56BUILDINGto the even, regular platelets. regular, ironic epitaphs nag e
2Customer#000000002XSTf4,NCwDVaWNe6tEgvwfmRchLXak1323-768-687-3665121.65AUTOMOBILEl accounts. blithely ironic theodolites integrate boldly: caref
3Customer#000000003MG9kdTD2WBHm111-719-748-33647498.12AUTOMOBILE deposits eat slyly ironic, even instructions. express foxes detect slyly. blithely even accounts abov
4Customer#000000004XxVSJsLAGtn414-128-190-59442866.83MACHINERY requests. final, regular ideas sleep final accou
5Customer#000000005KvpyuHCplrB84WgAiGV6sYpZq7Tj313-750-942-6364794.47HOUSEHOLDn accounts will have to unwind. foxes cajole accor

5 rows

  • SELECT says which columns to return. * means all of them.

    SELECT 指定要返回哪些欄,* 表示全部。

  • FROM names the table.

    FROM 指明從哪張表讀取。

  • LIMIT 5 stops after five rows.

    LIMIT 5 只返回五行。

  • The semicolon ends the statement. Writing keywords in capitals is a convention that makes queries easier to read; the database does not require it.

    分號表示語句結束。關鍵字用大寫是為了方便閱讀的慣例,數據庫並不要求。

Without an instruction about order, a database may return any five rows. Here you get customers 1 to 5 because the practice data is stored in key order. Chapter 2 shows how to ask for an order explicitly.

如果沒有指定排序,數據庫可以返回任意五行。這裏得到第 1 至 5 號客戶,是因為練習數據按鍵的順序儲存。第 2 章會說明如何明確指定排序。

Choosing columns選擇需要的欄

Most of the time you need only a few columns. List them after SELECT, separated by commas:

大多數時候你只需要幾欄。把它們列在 SELECT 後面,用逗號分隔:

c_custkeyc_namec_mktsegmentc_acctbal
1Customer#000000001BUILDING711.56
2Customer#000000002AUTOMOBILE121.65
3Customer#000000003AUTOMOBILE7498.12
4Customer#000000004MACHINERY2866.83
5Customer#000000005HOUSEHOLD794.47

5 rows

Columns come back in the order you list them. Naming them also tells the next reader of the query which information mattered.

返回的欄會按你列出的次序排列。寫明欄名,也讓之後閱讀這條查詢的人知道哪些資料是重要的。

Every column has a type每一欄都有類型

DESCRIBE lists a table’s columns and their types:

DESCRIBE 會列出表中各欄及其類型:

column_namecolumn_typenullkeydefaultextra
c_custkeyBIGINTYESNULLNULLNULL
c_nameVARCHARYESNULLNULLNULL
c_addressVARCHARYESNULLNULLNULL
c_nationkeyBIGINTYESNULLNULLNULL
c_phoneVARCHARYESNULLNULLNULL
c_acctbalDECIMAL(15,2)YESNULLNULLNULL
c_mktsegmentVARCHARYESNULLNULLNULL
c_commentVARCHARYESNULLNULLNULL

8 rows

The first two columns of the result are the ones to read: column_name and column_type. The 8 columns of customer use three types:

結果中最需要看的是頭兩欄:column_name 和 column_type。customer 的 8 欄使用了三種類型:

TypeHolds 存放內容Columns in customer customer 中的欄
BIGINTA whole number 整數c_custkey c_nationkey
VARCHARText of any length 任意長度的文字c_name c_address c_phone c_mktsegment c_comment
DECIMAL(15,2)An exact number: up to 15 digits, 2 after the point 精確數值:最多 15 位,其中 2 位在小數點後c_acctbal

A phone number is stored as text, not as a number. You never add phone numbers together, and a number would lose the dashes and any leading zero. Choose a type by what you will do with a column, not by what it looks like.

電話號碼以文字而不是數字儲存。你永遠不會把電話號碼相加,而存成數字會失去連字號和開頭的零。選擇類型要看你會怎樣使用這一欄,而不是看它的外表。

What one row represents一行代表甚麼

Before using any table, answer one question: what does one row represent? This is called the table’s grain. In customer, one row is one customer record.

使用任何一張表之前,先回答一個問題:一行代表甚麼?這稱為表的粒度(grain)。在 customer 中,一行代表一條客戶記錄。

Each record has a number in c_custkey that no other row shares. A column like this is a key: it identifies a row, as a student number identifies a student. COUNT(*) counts rows:

每條記錄在 c_custkey 中都有一個不與其他行重複的號碼。這樣的欄稱為鍵(key):它識別每一行,就像學生編號識別每一位學生。COUNT(*) 用來計算行數:

count_star()
1552

1 row

There are 1,552 rows and 1,552 different values of c_custkey, so the key is unique. Chapter 4 shows how to count distinct values. Here is the grain of all eight tables:

表中有 1,552 行,c_custkey 有 1,552 個不同的值,所以這個鍵是唯一的。第 4 章會說明如何計算不同值的數目。以下是全部八張表的粒度:

TableOne row is 一行代表Key 鍵
regionA region of the world 一個地區r_regionkey
nationA country 一個國家n_nationkey
customerA customer record 一條客戶記錄c_custkey
supplierA supplier 一個供應商s_suppkey
partA part the company sells 公司出售的一種零件p_partkey
partsuppOne supplier’s offer of one part 某個供應商供應某種零件ps_partkey + ps_suppkey
ordersAn order from a customer 客戶的一張訂單o_orderkey
lineitemOne line of an order: a part, its quantity and price 訂單中的一行:一種零件及其數量和價格l_orderkey + l_linenumber

Two tables need two columns to identify a row: an order has several lines, so a line is identified by its order and its line number. A key is a rule about what should be true. In real data rules get broken, and Part 4 checks whether these keys really are unique.

有兩張表需要兩欄才能識別一行:一張訂單有多行,所以每一行由訂單號和行號共同識別。鍵是一條「應該成立」的規則。在真實數據中,規則會被打破,第 4 部分會檢查這些鍵是否真的唯一。

Back to the question回到最初的問題

Back to the sales director. Is 1,552 the number of customers? Look at two of the rows:

回到銷售總監的問題。1,552 就是客戶數目嗎?看看其中兩行:

c_custkeyc_namec_addressc_phone
25Customer#000000025Hp8GyFQgGHFYSilH5tBfe22-603-468-3533
1000025CUSTOMER#000000025 Hp8GyFQgGHFYSilH5tBfe226034683533

2 rows

The keys differ, so the database treats these as two customers. But the address is identical, the names differ only in capital letters and a trailing space, and the phone number has the same digits without dashes. This is one company entered twice, most likely by two salespeople. The key is unique; the company is not. Chapter 16 finds every such pair.

兩行的鍵不同,所以數據庫把它們當作兩個客戶。但地址完全一樣,名稱只差在大小寫和尾部的一個空格,電話號碼的數字相同,只是沒有連字號。這是同一家公司被登記了兩次,很可能是兩位銷售人員各自建檔。鍵是唯一的,公司卻不是。第 16 章會找出所有這類重複記錄。

There is a second problem. Of the 1,552 records, 516 have never placed an order; Chapter 9 shows how to find them. Whether they count as customers is a business decision, not a SQL one.

還有第二個問題。在 1,552 條記錄中,有 516 條從未下過訂單,第 9 章會說明如何找出它們。它們算不算客戶,是業務上的決定,而不是 SQL 的問題。

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

Ask an AI assistant “How many customers do we have? The table is called customer.” and you will very likely get SELECT COUNT(*) FROM customer;. The SQL is correct. The answer is not, for the reasons above, and nothing in the query reveals it.

如果你問 AI 助手:「我們有多少客戶?表名是 customer。」它很可能會給你 SELECT COUNT(*) FROM customer;。這條 SQL 本身沒有錯,但基於上面的原因,答案是錯的,而查詢本身完全看不出這一點。

This is the first item of a checklist that grows through the tutorial: before trusting a result, ask what one row represents. Here the answer, one customer record, is not what the director meant by a customer.

這是一份清單的第一項,清單會在整個教程中逐步增加:在相信一個結果之前,先問一行代表甚麼。在這個例子中,一行代表一條客戶記錄,而這並不是總監所說的「客戶」。

Check your understanding自我測驗

  1. How many rows does orders have? Write the query.

    orders 有多少行?寫出查詢。

    Answer 答案

    SELECT COUNT(*) FROM orders; returns 15,533. The company actually received 15,000 orders; Chapter 15 explains the difference.

    SELECT COUNT(*) FROM orders; 返回 15,533。公司實際收到 15,000 張訂單,第 15 章會解釋兩者的差別。

  2. Run DESCRIBE orders; in any box above. Which column records the date an order was placed, and what is its type?

    在上面任何一個方框中執行 DESCRIBE orders;。哪一欄記錄下單日期?它是甚麼類型?

    Answer 答案

    o_orderdate, of type DATE.

    o_orderdate,類型是 DATE。

  3. lineitem has 60,175 rows, far more than orders. What does one row of lineitem represent, and why are there more of them?

    lineitem 有 60,175 行,遠多於 orders。lineitem 的一行代表甚麼?為甚麼行數較多?

    Answer 答案

    One line of an order: one part, with its quantity and price. An order has between 1 and 7 lines, so lineitem has several rows for most orders.

    代表訂單中的一行:一種零件及其數量和價格。每張訂單有 1 至 7 行,所以大多數訂單在 lineitem 中都有多行。

  4. Write a query that returns three rows of lineitem, showing only the order key, the ship date and the ship mode.

    寫一條查詢,返回 lineitem 的三行,只顯示訂單號、發貨日期和運輸方式。

    Answer 答案
    l_orderkeyl_shipdatel_shipmode
    11996-03-13TRUCK
    11996-04-12MAIL
    11996-01-29REG AIR

    3 rows

Sources 資料來源

How this tutorial was made: AI Diligence Statement