SQL · Chapter 1
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
lineitemtable 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_custkey | c_name | c_address | c_nationkey | c_phone | c_acctbal | c_mktsegment | c_comment |
|---|---|---|---|---|---|---|---|
| 1 | Customer#000000001 | IVhzIApeRb ot,c,E | 15 | 25-989-741-2988 | 711.56 | BUILDING | to the even, regular platelets. regular, ironic epitaphs nag e |
| 2 | Customer#000000002 | XSTf4,NCwDVaWNe6tEgvwfmRchLXak | 13 | 23-768-687-3665 | 121.65 | AUTOMOBILE | l accounts. blithely ironic theodolites integrate boldly: caref |
| 3 | Customer#000000003 | MG9kdTD2WBHm | 1 | 11-719-748-3364 | 7498.12 | AUTOMOBILE | deposits eat slyly ironic, even instructions. express foxes detect slyly. blithely even accounts abov |
| 4 | Customer#000000004 | XxVSJsLAGtn | 4 | 14-128-190-5944 | 2866.83 | MACHINERY | requests. final, regular ideas sleep final accou |
| 5 | Customer#000000005 | KvpyuHCplrB84WgAiGV6sYpZq7Tj | 3 | 13-750-942-6364 | 794.47 | HOUSEHOLD | n accounts will have to unwind. foxes cajole accor |
SELECTsays which columns to return.*means all of them.SELECT指定要返回哪些欄,*表示全部。FROMnames the table.FROM指明從哪張表讀取。LIMIT 5stops 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_custkey | c_name | c_mktsegment | c_acctbal |
|---|---|---|---|
| 1 | Customer#000000001 | BUILDING | 711.56 |
| 2 | Customer#000000002 | AUTOMOBILE | 121.65 |
| 3 | Customer#000000003 | AUTOMOBILE | 7498.12 |
| 4 | Customer#000000004 | MACHINERY | 2866.83 |
| 5 | Customer#000000005 | HOUSEHOLD | 794.47 |
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_name | column_type | null | key | default | extra |
|---|---|---|---|---|---|
| c_custkey | BIGINT | YES | NULL | NULL | NULL |
| c_name | VARCHAR | YES | NULL | NULL | NULL |
| c_address | VARCHAR | YES | NULL | NULL | NULL |
| c_nationkey | BIGINT | YES | NULL | NULL | NULL |
| c_phone | VARCHAR | YES | NULL | NULL | NULL |
| c_acctbal | DECIMAL(15,2) | YES | NULL | NULL | NULL |
| c_mktsegment | VARCHAR | YES | NULL | NULL | NULL |
| c_comment | VARCHAR | YES | NULL | NULL | NULL |
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 欄使用了三種類型:
| Type | Holds 存放內容 | Columns in customer customer 中的欄 |
|---|---|---|
BIGINT | A whole number 整數 | c_custkey c_nationkey |
VARCHAR | Text 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 |
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 章會說明如何計算不同值的數目。以下是全部八張表的粒度:
| Table | One row is 一行代表 | Key 鍵 |
|---|---|---|
region | A region of the world 一個地區 | r_regionkey |
nation | A country 一個國家 | n_nationkey |
customer | A customer record 一條客戶記錄 | c_custkey |
supplier | A supplier 一個供應商 | s_suppkey |
part | A part the company sells 公司出售的一種零件 | p_partkey |
partsupp | One supplier’s offer of one part 某個供應商供應某種零件 | ps_partkey + ps_suppkey |
orders | An order from a customer 客戶的一張訂單 | o_orderkey |
lineitem | One 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_custkey | c_name | c_address | c_phone |
|---|---|---|---|
| 25 | Customer#000000025 | Hp8GyFQgGHFYSilH5tBfe | 22-603-468-3533 |
| 1000025 | CUSTOMER#000000025 | Hp8GyFQgGHFYSilH5tBfe | 226034683533 |
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自我測驗
-
How many rows does
ordershave? 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 章會解釋兩者的差別。 -
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 typeDATE.o_orderdate,類型是DATE。 -
lineitemhas 60,175 rows, far more thanorders. What does one row oflineitemrepresent, 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
lineitemhas several rows for most orders.代表訂單中的一行:一種零件及其數量和價格。每張訂單有 1 至 7 行,所以大多數訂單在
lineitem中都有多行。 -
Write a query that returns three rows of
lineitem, showing only the order key, the ship date and the ship mode.寫一條查詢,返回
lineitem的三行,只顯示訂單號、發貨日期和運輸方式。Answer 答案
l_orderkey l_shipdate l_shipmode 1 1996-03-13 TRUCK 1 1996-04-12 MAIL 1 1996-01-29 REG AIR
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 figure of 6,001,215 rows was generated with the same tool at scale factor 1.
- Microsoft, Excel specifications and limits: 1,048,576 rows per worksheet.
- Google Cloud, BigQuery pricing: on-demand queries are charged for the data processed in the columns selected.
- 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