PostgreSQL offers a rich set of data types, which is one of its most popular features as an enterprise-grade database system. Below, I'll outline key data types and provide usage examples.
Numerical Types
-
Integer Types:
SMALLINT: Used for storing smaller integers, ranging from -32768 to 32767.INTEGER: Used for storing standard-sized integers, ranging from -2147483648 to 2147483647. For example, user age or a counter.BIGINT: Used for storing large integers, ranging from -9223372036854775808 to 9223372036854775807. Suitable for large-scale statistics, such as user counts on social media platforms.SERIAL: Auto-incrementing integer, commonly used for automatically generating unique row identifiers in tables.
-
Exact Numeric Types:
NUMERICandDECIMAL: These types store exact numeric values with specified precision (total digits) and scale (digits after the decimal point). For example, financial transaction amounts.
-
Floating Point Types:
REALandDOUBLE PRECISION: Used for storing floating-point numbers, withREALbeing single-precision andDOUBLE PRECISIONbeing double-precision. Used for scientific calculations requiring approximate values.
Text Types
CHAR(n): Fixed-length string. If the string length is less than n, it is padded with spaces.VARCHAR(n): Variable-length string, up to n characters. Suitable for storing variable-length data, such as user names.TEXT: Variable-length string with no length limit. Ideal for storing large text, such as article content or user comments.
Date and Time Types
DATE: Stores only dates.TIME: Stores only times.TIMESTAMP: Stores both date and time. Commonly used for recording specific event times, such as log entries.INTERVAL: Stores time intervals.
Boolean Types
BOOLEAN: Stores true (TRUE) or false (FALSE). For example, user subscription status or yes/no options.
Enum Types
ENUM: Custom type restricting possible values for a field. For example, create anENUMtype namedmoodwith options likehappy,sad,neutral.
JSON Types
JSONandJSONB: Used for storing JSON data.JSONBis in binary format, offering faster read/write performance and index support.
Array Types
- PostgreSQL supports array data types, which can store arrays of basic types, such as integer or text arrays.
Network Address Types
- Stores IP addresses and MAC addresses, among other network-related data.
Geometric and Geographic Data Types
- Such as
POINT,LINE,CIRCLE, used for storing and querying geographic spatial data.
The comprehensive support for various data types makes PostgreSQL highly suitable for handling diverse data requirements, from traditional business data to modern JSON documents and geographic spatial data.
2024年7月24日 17:27 回复