跳转到主要内容
eLearner.app
模块 9 · 第 1 课(共 4)课程中的33/57~10 min
模块课程(1/4)

高级数据类型和 ENUM

In the previous lesson we saw the basic CREATE TABLE command. Let's now explore some advanced data types that PostgreSQL offers to model our domains in a more precise and safe way.

Numeric and text types

PostgreSQL has several types for numbers and text. Choosing the right one helps both with validation and with storage space.

SQL
CREATE TABLE advanced_products (
  id           SERIAL PRIMARY KEY,
  name         VARCHAR(50) NOT NULL,
  description  TEXT,
  -- NUMERIC(p,s) dove p = cifre totali, s = cifre decimali
  price        NUMERIC(10, 2) NOT NULL,
  featured     BOOLEAN DEFAULT FALSE
);
  • TEXT vs VARCHAR(n): In Postgres performance is identical. You use VARCHAR(n) only when you want to explicitly limit the inserted length at the database level.
  • NUMERIC(10, 2): Perfect for money or arithmetic precision. Here it allows at most 8 integer digits and 2 decimals (10 in total). If you insert 10.555, Postgres rounds it to 10.56.

The UUID type

For secure identifiers exposed on the web (such as public IDs in URLs), UUID is often preferred over the classic SERIAL increment.

SQL
CREATE TABLE public_orders (
  id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  customer    TEXT NOT NULL,
  total       NUMERIC(10, 2)
);

ENUM (Enumerations)

Often a column must contain only one of a few predefined values (e.g. order status: "new", "paid", "shipped"). One approach is to use the CHECK keyword, but PostgreSQL offers custom ENUM types.

SQL
-- Dobbiamo prima creare il tipo:
CREATE TYPE order_status AS ENUM ('nuovo', 'pagato', 'spedito', 'cancellato');

-- Ora possiamo usarlo in una tabella:
CREATE TABLE orders_demo (
  id SERIAL PRIMARY KEY,
  status order_status NOT NULL DEFAULT 'nuovo'
);

This guarantees that no one can ever insert an invalid status, protecting data consistency.

Try it

锻炼#sql.m9.l1.e1
尝试:0加载中...

Create a 'user_reviews' table with: id (SERIAL pk), test_id (UUID with default gen_random_uuid()), score (integer not null), and content (TEXT). None of the other fields needs explicit constraints beyond the type.

正在加载编辑器...
显示提示

Write CREATE TABLE user_reviews (...) and then the various fields. Remember the commas.

3 次尝试后可用的解决方案

Review exercise

锻炼#sql.m9.l1.e2
尝试:0加载中...

First create the ENUM type 'user_role' with values 'admin' and 'user'. Then create the 'enum_users' table with id (SERIAL pk) and role (the type you just created, NOT NULL).

正在加载编辑器...
显示提示

Don't forget the ; to separate the two statements (the CREATE TYPE and the CREATE TABLE).

3 次尝试后可用的解决方案