# 6.1. 新增資料

資料表在建立的時候，並不包含任何資料。以各種方式使用資料庫之前，要做的第一件事就是新增資料。概念上，資料是一次新增一列。當然你也可以新增多列，但就沒有辦法新增少於一列。 即使只知道某些欄位的值，也必須建立一個完整的資料列。

要建立新的資料列，請使用 [INSERT](https://github.com/pgsql-tw/documents/tree/a096b206440e1ac8cdee57e1ae7a74730f0ee146/vi-reference/i-sql-commands/insert.md) 指令。該命令需要資料表的名稱和各欄位的資料內容。例如，來看看[第 5 章](https://github.com/pgsql-tw/documents/tree/a096b206440e1ac8cdee57e1ae7a74730f0ee146/ii-the-sql-language/data-definition.md)中的產品資料表：

```
CREATE TABLE products (
    product_no integer,
    name text,
    price numeric
);
```

新增資料列的指令可能如下所示：

```
INSERT INTO products VALUES (1, 'Cheese', 9.99);
```

資料內容按資料表表中欄位的順序列出，以逗號分隔。通常，資料內容會是文字（常數），但運算表示式也是允許的。

上面的語法有缺點，就是你需要知道資料表中欄位的順序。為了避免這種情況，您可以明確地列出欄位。例如，以下兩個命令與上面的命令具有相同的效果：

```
INSERT INTO products (product_no, name, price) VALUES (1, 'Cheese', 9.99);
INSERT INTO products (name, price, product_no) VALUES ('Cheese', 9.99, 1);
```

許多用戶認為總是列出欄位名稱是一個很好的習慣。

如果你並沒有所有欄位的內容，則可以省略其中一些欄位。在這種情況下，那些欄位將會以預設值代入。如下所示：

```
INSERT INTO products (product_no, name) VALUES (1, 'Cheese');
INSERT INTO products VALUES (1, 'Cheese');
```

第二種形式是屬於 PostgreSQL 延伸寫法。 從左邊開始的欄位填入所給定的內容，其餘的欄位則使用預設值。

為了清楚起見，你也可以明確地指定個別欄位或整個資料列都使用預設值：

```
INSERT INTO products (product_no, name, price) VALUES (1, 'Cheese', DEFAULT);
INSERT INTO products DEFAULT VALUES;
```

您可以在一個命令中新增多個資料列：

```
INSERT INTO products (product_no, name, price) VALUES
    (1, 'Cheese', 9.99),
    (2, 'Bread', 1.99),
    (3, 'Milk', 2.99);
```

也可以以查詢的結果新增（可能沒有資料，一個資料列或多個資料列）：

```
INSERT INTO products (product_no, name, price)
  SELECT product_no, name, price FROM new_products
    WHERE release_date = 'today';
```

這包含完整 SQL 查詢機制（[第 7 章](https://github.com/pgsql-tw/documents/tree/a096b206440e1ac8cdee57e1ae7a74730f0ee146/ii-the-sql-language/queries.md)）用於計算需要新增的資料列。

## 小技巧

同時要新增大量資料時，請考慮使用 [COPY](https://github.com/pgsql-tw/documents/tree/a096b206440e1ac8cdee57e1ae7a74730f0ee146/vi-reference/i-sql-commands/copy.md) 指令。它不像 INSERT 指令那麼靈活，但是效率更高。有關提高批次新增資料效率的更多資訊，請參閱[第 14.4 節](https://github.com/pgsql-tw/documents/tree/a096b206440e1ac8cdee57e1ae7a74730f0ee146/ii-the-sql-language/performance-tips/144-populating-a-database.md)。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.postgresql.tw/15/the-sql-language/data-manipulation/6.1.-xin-zeng-zi-liao.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
