0Pricing
PostgreSQL Performance & Query Optimization · 课时

选择合适的数据类型

为列选择最高效的数据类型,以减少存储空间并优化查询处理。

选择合适的数据类型 是 CoddyKit 上的免费 PostgreSQL Performance & Query Optimization 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 PostgreSQL Performance & Query Optimization 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 PostgreSQL Performance & Query Optimization 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Data Types Matter

Choosing the correct data type for your columns in PostgreSQL is a fundamental step in designing an efficient database.

It impacts storage, query performance, and data integrity. Selecting the right type ensures your data is stored efficiently and processed quickly.

Picking Integer Types

PostgreSQL offers several integer types, each with a different storage size and value range:

  • SMALLINT: 2 bytes, range -32,768 to +32,767
  • INTEGER (or INT): 4 bytes, range -2,147,483,648 to +2,147,483,647
  • BIGINT: 8 bytes, range -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807

Always choose the smallest integer type that can safely store your expected data range to minimize disk space and improve performance.

Integer Type Demo

Let's see how different integer types are defined. Notice how we pick the smallest type that fits the value.

CREATE TABLE product_counts (
  small_count SMALLINT,
  medium_count INTEGER,
  large_count BIGINT
);

INSERT INTO product_counts (small_count, medium_count, large_count)
VALUES (100, 50000, 1000000000);

SELECT * FROM product_counts;

Numeric Precision

When dealing with decimal numbers, especially monetary values, precision is key:

  • NUMERIC(p, s): Stores exact numbers. p is the total number of digits (precision), s is the number of digits after the decimal point (scale). Essential for financial data.
  • REAL (4 bytes) and DOUBLE PRECISION (8 bytes): Store approximate floating-point numbers. They are faster but can introduce tiny rounding errors, making them unsuitable for money.

Use NUMERIC when exactness is critical; use REAL or DOUBLE PRECISION for scientific or less critical calculations where approximation is acceptable.

Text Storage Choices

For storing text strings, PostgreSQL offers:

  • VARCHAR(n): Variable-length string with a user-defined maximum length n. If you try to insert a longer string, it will be truncated or an error will occur.
  • TEXT: Variable-length string with no explicit maximum length. It's often the most flexible choice.
  • CHAR(n): Fixed-length string. If the string is shorter than n, it's padded with spaces. Generally discouraged due to potential performance issues and space waste.

For most modern applications, VARCHAR (without a length, acting like TEXT) or simply TEXT are preferred for their flexibility and efficient storage.

VARCHAR vs. TEXT

Here's an example demonstrating VARCHAR with a length constraint and TEXT without one. Both store data efficiently based on actual length.

CREATE TABLE messages (
  short_msg VARCHAR(50),
  long_msg TEXT
);

INSERT INTO messages (short_msg, long_msg)
VALUES ('Hello World', 'This is a much longer message that can span multiple lines and characters.');

SELECT short_msg, LENGTH(short_msg), long_msg, LENGTH(long_msg) FROM messages;

Handling Dates & Times

PostgreSQL provides robust date/time types:

  • DATE: Stores date only (year, month, day).
  • TIME: Stores time of day only (hour, minute, second, fractional seconds).
  • TIMESTAMP: Stores date and time. It does NOT store timezone information.
  • TIMESTAMPTZ (TIMESTAMP WITH TIME ZONE): Stores date and time, and converts it to UTC upon storage. It's the recommended type for most applications to avoid timezone headaches.

Always prefer TIMESTAMPTZ for event timestamps unless you have a very specific reason not to.

Special Types: Boolean & UUID

Two other useful data types:

  • BOOLEAN: Stores true/false values. It's highly efficient, requiring only 1 byte of storage. PostgreSQL accepts 'true', 'false', 't', 'f', '1', '0', 'yes', 'no' as inputs.
  • UUID: Stores Universally Unique Identifiers. These are 128-bit quantities, useful for generating unique primary keys without database sequence contention, especially in distributed systems.

UUIDs can be generated by PostgreSQL using functions like gen_random_uuid() from the pgcrypto extension.

Type Conversion Overhead

While PostgreSQL often handles implicit type conversions (e.g., converting a string '123' to an integer), this comes with a performance cost.

When you compare or join columns of different data types, PostgreSQL might need to perform a conversion on one or both sides, which can prevent indexes from being used and slow down queries.

Always strive to compare and join columns that have identical data types. If conversion is necessary, use explicit casting (e.g., column::INTEGER) to make it clear and sometimes help the query planner.

Data Type Challenge

Imagine you are designing a table to store user registration details. One column needs to store whether a user has verified their email, and another needs to store a unique, globally identifiable user ID that can be generated anywhere.

Data Type Summary

We've covered the importance of choosing appropriate data types for performance, storage, and integrity.

  • Choose the smallest integer type that fits your data.
  • Use NUMERIC for exact decimal values (like money).
  • Prefer TIMESTAMPTZ for storing dates and times with timezone awareness.
  • BOOLEAN is best for true/false flags, and UUID for globally unique identifiers.
  • Avoid unnecessary type conversions to maintain query performance.

Careful data type selection is a cornerstone of efficient database design.

常见问题解答

「选择合适的数据类型」课时是免费的吗?

是的 — 「选择合适的数据类型」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 PostgreSQL Performance & Query Optimization 课程的其余内容,请升级到 CoddyKit PRO。 PostgreSQL Performance & Query Optimization 课程共包含 4 节课。

「选择合适的数据类型」这节课中我会学到什么?

为列选择最高效的数据类型,以减少存储空间并优化查询处理。 你通过在浏览器中直接运行的动手代码来练习 PostgreSQL Performance & Query Optimization,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 PostgreSQL Performance & Query Optimization 需要有经验吗?

无需任何先前经验。CoddyKit 上的 PostgreSQL Performance & Query Optimization 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「选择合适的数据类型」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 PostgreSQL Performance & Query Optimization 课中编写并运行代码吗?

能。每节 PostgreSQL Performance & Query Optimization 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 规范化与反规范化的权衡
  2. 选择合适的数据类型
  3. 对大型表进行分区
  4. 设计主键与代理键
← 返回 PostgreSQL Performance & Query Optimization