Skip to main content

Part V: Designing Your Schema

 



Designing a robust database schema is crucial for data integrity, performance, and long‐term maintainability. In this module, we’ll cover:

  • Creating and altering tables

  • Defining keys and leveraging indexes

By the end, you’ll know how to structure your data model to support reliable applications and fast queries.

Creating and Altering Tables

A well‐designed table lays the foundation of your database. Start by defining clear columns, appropriate data types, and necessary constraints.

1. CREATE TABLE Syntax

sql
CREATE TABLE employees (
  employee_id   SERIAL PRIMARY KEY,
  first_name    VARCHAR(50) NOT NULL,
  last_name     VARCHAR(50) NOT NULL,
  hire_date     DATE NOT NULL,
  email         VARCHAR(100) UNIQUE,
  salary        NUMERIC(10, 2) CHECK (salary > 0)
);

Key takeaways:

  • Use SERIAL or IDENTITY for auto-incrementing primary keys.

  • Choose string lengths (VARCHAR) based on real data.

  • Apply NOT NULL to mandatory columns.

  • Enforce business rules with CHECK constraints.

2. ALTER TABLE Examples

As requirements evolve, you’ll need to change schemas without losing data.

  • Add a new column:

    sql
    ALTER TABLE employees
    ADD COLUMN department_id INT;
    
  • Modify an existing column:

    sql
    ALTER TABLE employees
    ALTER COLUMN email TYPE VARCHAR(150);
    
  • Drop an obsolete column:

    sql
    ALTER TABLE employees
    DROP COLUMN salary;
    

Best practices:

  • Backup data before altering critical tables.

  • Test changes in a development environment first.

  • Monitor locks and downtime when applying schema updates in production.

Keys and Indexes

Proper use of keys and indexes ensures data accuracy and query performance.

1. Primary and Unique Keys

  • Primary Key: Uniquely identifies each row and enforces NOT NULL.

  • Unique Key: Guarantees column uniqueness without being the primary identifier.

sql
ALTER TABLE employees
ADD CONSTRAINT uq_employee_email UNIQUE (email);

Unique constraints prevent duplicate entries and support faster lookups when indexed.

2. Foreign Keys and Referential Integrity

Foreign keys link tables and enforce valid relationships.

sql
ALTER TABLE employees
ADD CONSTRAINT fk_dept
FOREIGN KEY (department_id)
REFERENCES departments (department_id)
ON DELETE SET NULL;

Options like ON DELETE CASCADE or SET NULL control how child rows behave when a parent is removed.

3. Indexes: Types and Usage

Indexes speed up data retrieval but add overhead on writes. Choose wisely:

  • Single‐Column Index: Ideal for columns used in WHERE or join conditions.

  • Composite Index: Covers multiple columns in specific query orders.

  • Partial Index (PostgreSQL): Indexes only a subset of rows.

sql
CREATE INDEX idx_lastname
ON employees (last_name);

4. Performance Considerations

  • Analyze query plans to identify missing or unused indexes.

  • Avoid over-indexing: too many indexes slow down INSERT, UPDATE, and DELETE.

  • Use covering indexes to satisfy queries without accessing the base table.

Conclusion

Designing your schema with clear tables, strong constraints, and strategic indexes lays the groundwork for scalable, maintainable databases. In the next session, we’ll explore advanced SQL constructs—views, stored procedures, and functions—to further encapsulate logic and boost developer productivity.

Comments

Popular posts from this blog

Alfred Marshall – The Father of Modern Microeconomics

  Welcome back to the blog! Today we explore the life and legacy of Alfred Marshall (1842–1924) , the British economist who laid the foundations of modern microeconomics . His landmark book, Principles of Economics (1890), introduced core concepts like supply and demand , elasticity , and market equilibrium — ideas that continue to shape how we understand economics today. Who Was Alfred Marshall? Alfred Marshall was a professor at the University of Cambridge and a key figure in the development of neoclassical economics . He believed economics should be rigorous, mathematical, and practical , focusing on real-world issues like prices, wages, and consumer behavior. Marshall also emphasized that economics is ultimately about improving human well-being. Key Contributions 1. Supply and Demand Analysis Marshall was the first to clearly present supply and demand as intersecting curves on a graph. He showed how prices are determined by both what consumers are willing to pay (dem...

Fundamental Analysis Case Study NVIDIA

  Executive summary NVIDIA is analyzed here using the full fundamental framework: balance sheet, income statement, cash flow statement, valuation multiples, sector comparison, sensitivity scenarios, and investment checklist. The company shows exceptional profitability, strong cash generation, conservative liquidity and net cash, and premium valuation multiples justified only if high growth and margin profiles persist. Key investment considerations are growth sustainability in data center and AI, margin durability, geopolitical and supply risks, and valuation sensitivity to execution. The detailed numerical work below uses the exact metrics you provided. Company profile and market context Business model and market position Company NVIDIA Corporation, leader in GPUs, AI accelerators, and related software platforms. Core revenue streams : data center GPUs and systems, gaming GPUs, professional visualization, automotive, software and services. Strategic advantage : GPU architecture, C...

Behavioral Portfolio Theory (BPT) – Rethinking Investor Behavior and Portfolio Construction

  Traditional finance theories like Modern Portfolio Theory (MPT) assume that investors are perfectly rational and risk-averse, aiming to maximize utility by optimizing expected returns and variance. However, decades of research in behavioral finance have shown that investors often deviate from purely rational behavior. Behavioral Portfolio Theory (BPT) , introduced by Shefrin and Statman in 2000, offers a fresh perspective by integrating psychological and emotional factors into portfolio construction. What is Behavioral Portfolio Theory? Behavioral Portfolio Theory suggests that investors mentally segment their wealth into multiple “mental accounts” or layers, each with distinct goals, risk preferences, and expectations. Unlike MPT's single-layer approach focusing on an overall risk-return tradeoff, BPT models the portfolio as a layered pyramid , where each layer reflects different investor aspirations. For example: The bottom layer prioritizes capital preservation and safe...