PostgreSQL
Chapter 5 - DDL (Data Definition Language)
CREATE TABLE
In PostgreSQL, the CREATE TABLE is fundamental for defining new tables in a database. It specifies the table structure, including column names, data types, and constraints. Understanding how to use CREATE TABLE is crucial for setting up a database schema effectively. Below, you'll find a step-by-step guide to creating tables, along with sample code relevant to a banking system, including tables for customers, accounts, and transactions.
Steps to Create Tables in PostgreSQL
- Basic Syntax
CREATE TABLE table_name ( column_name data_type [constraints], ... );table_nameThe name of the table you want to create.column_nameThe name of each column in the table.data_typeThe type of data the column will hold (e.g.,INTEGER,VARCHAR).constraintsOptional rules to enforce data integrity (e.g.,PRIMARY KEY,NOT NULL).
- Example: Creating a
customerstableCREATE TABLE customers ( customer_id SERIAL PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(100) UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );customer_idA unique identifier for each customer, automatically incremented.first_nameandlast_nameRequired fields for customer names.emailA unique field for the customer's email address.created_atA timestamp for when the record was created, defaulting to the current time.
- Example: Creating an
accountstableCREATE TABLE accounts ( account_id SERIAL PRIMARY KEY, customer_id INTEGER REFERENCES customers(customer_id), account_type VARCHAR(20) NOT NULL, balance DECIMAL(15, 2) NOT NULL CHECK (balance >= 0), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );account_idA unique identifier for each account.customer_id: A foreign key linking to thecustomerstable.account_type: Type of account (e.g., savings, checking).balance: The account balance, must be non-negative.created_at: A timestamp for when the account was created.
- Example: Creating a
transactionstableCREATE TABLE transactions ( transaction_id SERIAL PRIMARY KEY, account_id INTEGER REFERENCES accounts(account_id), transaction_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, amount DECIMAL(15, 2) NOT NULL, transaction_type VARCHAR(10) CHECK (transaction_type IN ('deposit', 'withdrawal')), description TEXT );transaction_idA unique identifier for each transaction.account_idA foreign key linking to theaccountstable.transaction_dateThe date and time of the transaction.amountThe amount of money involved in the transaction.transaction_typeSpecifies whether the transaction is a deposit or withdrawal.descriptionOptional text field for additional details about the transaction.
- Considerations for Table Design
- Ensure that each table has a primary key for unique identification.
- Use foreign keys to establish relationships between tables.
- Apply constraints to enforce data integrity and business rules.
To gain complete access, login with gmail or outlook, no need of signup. click here


Comments Not Found