メインコンテンツにスキップ
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 回の試行後に解決策が利用可能になります