1. Home
  2. Explore
  3. Computer Science
  4. Database Design Fundamentals

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Database Design Fundamentals

Database Design Study Notes

1. Databases and Database Design

A database is a system used to store data. Data should be understood broadly as anything that can be recorded and stored, including:

  • Customer records

  • Online shopping transactions

  • Usernames, passwords, and email addresses

  • Weather events

  • Employee information

  • Orders, comments, sales, and website activity

Almost every modern application, website, and business system uses a database as its back end.

Why Database Design Matters

Database design is the process of planning how data will be organized, stored, connected, and accessed. A well-designed database:

  • Prevents incorrect or inconsistent data

  • Reduces unnecessary repetition

  • Makes updates easier

  • Improves performance

  • Protects data integrity

  • Supports appropriate security

  • Allows different users to access only the information they need

Database design is not initially a programming task. It begins with planning:

  1. Identify what information must be stored.

  2. Determine how different pieces of information are related.

  3. Organize the information into tables.

  4. Define keys, constraints, and data types.

  5. Decide how users and applications will access the data.

  6. Implement the design in a database management system.

Database design is general rather than specific to one product. The same principles can be applied to MySQL, SQL Server, Oracle, PostgreSQL, and other relational database systems.


2. Databases Compared with Spreadsheets

A spreadsheet organizes data into rows and columns, much like a database table. Spreadsheets are useful for small, simple datasets, but databases are better for complex, shared, and frequently changing information.

Querying and Filtering

A database can run a query, which is a request to retrieve or manipulate specific data.

For example, a business could request all employees who:

  • Have worked for at least three years

  • Have missed three or fewer days

  • Should receive a bonus

A spreadsheet may require manually checking every row, while a database can identify the correct employees automatically.

Selective Data Access

A database can return only selected columns or records. For example, a query could return only employee names and addresses while ignoring salary, phone number, and other information.

A spreadsheet is often more “all or nothing”:

  • If someone can access the spreadsheet, they may see everything in it.

  • If someone cannot access it, they may see nothing.

Databases allow more precise permissions.

Multiple User Roles

Different users can access different information:

  • A regular website user may access only their own username and account information.

  • A database administrator may access all users, transactions, comments, and activity records.

  • An advertising employee may access advertising-related data but not financial transactions.

  • A comments moderator may access comments without seeing sales data.

This separation improves security and prevents unauthorized access to hidden information.


3. Front End, Back End, Clients, and Servers

Front End

The front end is what a user sees and interacts with, such as:

  • A website page

  • A registration form

  • A login screen

  • A user profile

  • A shopping cart

  • An administrator dashboard

The front end hides the underlying database structure from users.

Back End

The back end consists of the systems operating behind the scenes, including:

  • The database

  • Server-side code

  • Database queries

  • Authentication logic

  • Data-processing operations

When a user registers on a website, the front end collects the information, while the back end stores it in the database.

When the user logs in later:

  1. The front end receives the username and password.

  2. The back-end code sends a query to the database.

  3. The database checks whether the credentials match.

  4. The system grants or denies access.

Client and Server

The client is the device or application requesting information. The server stores and provides the database or related services.

A client might be:

  • A web browser

  • A mobile application

  • A desktop program

  • Another server

The server processes requests and returns only the information permitted by the user’s privileges.


4. Relational Databases and Relations

A relational database stores data in tables and establishes connections between those tables.

The term relational comes from a mathematical concept called a relation, involving connections between sets of values. In database practice, a relation is commonly represented as a table.

A relational database separates information into related tables rather than placing everything in one enormous table.

For example:

  • A User table stores user information.

  • A Sale table stores sales.

  • An Order table stores orders.

  • A Comment table stores comments.

The tables are connected through keys and relationships.

Mathematical Relationship Concept

If one set contains 222 and 444, and another contains 666 and 888, combining every value from the first set with every value from the second set produces combinations such as:

  • (2,6)(2,6)(2,6)

  • (4,6)(4,6)(4,6)

  • (2,8)(2,8)(2,8)

  • (4,8)(4,8)(4,8)

Database relationships apply a similar idea to real-world entities and their attributes.


5. Entities, Attributes, Values, Rows, and Columns

Entity

An entity is anything about which data is stored.

Examples include:

  • A user

  • A customer

  • An employee

  • An order

  • A product

  • A comment

  • A class

  • A professor

  • A credit card

A specific person, such as one particular user, is an individual entity.

Entity Type

An entity type is a category of similar entities.

For example:

  • User is an entity type.

  • Caleb, Billy, and Jamie are individual user entities.

A table generally represents one entity type, so every row in a User table should represent a user.

Attribute

An attribute is a characteristic or piece of information stored about an entity.

For a user, attributes might include:

  • User ID

  • Username

  • Password

  • Email

  • First name

  • Last name

  • Address

  • Phone number

Attribute Type

An attribute type is the category of information being stored, such as username, email, or password.

A specific value is not an attribute type. For example:

  • Username is an attribute type.

  • CalebCurry is a specific username value.

Value

A value is the actual data stored in a field.

For example, in a user record:

  • The username value might be CalebCurry.

  • The email value might be example@email.com.

  • The user ID value might be 727272.

Row

A row contains all attribute values for one entity.

A user row might contain:

  • User ID: 727272

  • Username: CalebCurry

  • Email: example@email.com

  • Password: an encrypted password value

A row is also called:

  • A tuple

  • A record

  • An entry

Column

A column contains values for one attribute type across multiple entities.

For example, a username column contains the usernames of many users.

A column is also called:

  • An attribute

  • A field

Table

A table is the physical representation of a relation. It contains:

  • Columns representing attributes

  • Rows representing individual entities

  • Values stored at the intersections of rows and columns


6. Database Management Systems

A database management system, abbreviated DBMS, is software that stores, manages, retrieves, and manipulates database information.

A relational database management system, abbreviated RDBMS, is a DBMS specifically designed to work with relational databases and their tables.

Examples include:

  • MySQL

  • Microsoft SQL Server

  • Oracle Database

  • PostgreSQL

Functions of a DBMS

A DBMS can:

  • Search for specific values

  • Insert new records

  • Update existing data

  • Delete records

  • Change how data is presented

  • Manage access permissions

  • Enforce data rules

  • Maintain relationships between tables

  • Process transactions

  • Provide views of selected data

Queries

A query is a request to retrieve or manipulate data.

For example, a database could find all users who have not logged in for one year and remove or deactivate them.

Without a DBMS, the information would exist as stored data but would be much harder to search and manage efficiently.

Views

A view is a virtual presentation of selected data. It changes how the data appears without changing the underlying table structure.

Suppose a user table contains:

  • User ID

  • Username

  • Password

  • Email

  • Registration date

  • Address

Different views could show:

  • An employee view containing usernames and passwords

  • An administrator view containing all columns

  • A public profile view containing username and registration date

  • A private account view containing email but excluding sensitive administrative information

Views improve both usability and security.

Transactions

A transaction is a group of related operations treated as one complete unit.

For example, transferring money may require:

  1. Deducting money from one account.

  2. Adding the money to another account.

  3. Saving both changes.

The transaction should either complete entirely or fail entirely. If the server crashes between steps, the database should not preserve only half of the operation.

This principle prevents incomplete or contradictory data.

Consistency Between Front End and Back End

The back-end storage structure may change without requiring the front end to change.

For example, a full name might initially be stored in one column and later divided into first_name and last_name. The website can continue displaying one full name if server-side code combines the two values.

However, removing a field that the front end depends on can cause errors. Server-side programming can hide technical details and present users with a general error instead of exposing database structure.


7. SQL, DDL, and DML

SQL, or Structured Query Language, is a language used to communicate with relational databases.

SQL acts as a bridge between human instructions and database operations. SQL syntax differs slightly between database products, but the major concepts remain similar.

Data Definition Language

Data Definition Language, or DDL, defines the structure of a database.

DDL is used to create or change:

  • Databases

  • Tables

  • Columns

  • Relationships

  • Constraints

  • Indexes

A CREATE operation is an example of DDL.

Data Manipulation Language

Data Manipulation Language, or DML, operates on the data inside an existing structure.

DML is used to:

  • Insert values

  • Select or search for values

  • Update values

  • Delete values

For example, changing a username is DML because the table structure remains unchanged.

SQL Keywords

A keyword is a reserved word with a predefined meaning in SQL.

Examples include:

  • SELECT

  • CREATE

  • UPDATE

  • DELETE

  • INSERT

  • JOIN

Keywords should generally not be used as table or column names because they may cause errors or confusion.


8. Naming Conventions

A naming convention is a consistent pattern for naming database objects.

A consistent convention helps:

  • Keep a database organized

  • Make names predictable

  • Reduce confusion

  • Help other developers understand the design

  • Improve consistency across related tables

Common conventions include:

  • Lowercase table and column names

  • Underscores instead of spaces

  • Consistent foreign-key names

  • Similar names for related columns

For example:

  • user

  • user_id

  • first_name

  • registration_date

A foreign key that references user_id should normally use a related and recognizable name.

Naming conventions are not universal requirements. Different systems and organizations use different conventions, but consistency within one database is essential.


9. Database Design Levels

Database design can be viewed as a continuum from general ideas to physical implementation.

Conceptual Schema

The conceptual schema describes how real-world entities are related without focusing on technical limitations.

For example:

  • Users make sales.

  • A sale must be associated with a buyer.

  • A user may exist without making a sale.

At this stage, the focus is on meaning and relationships.

Logical Schema

The logical schema translates concepts into tables, columns, keys, and relationship structures.

For example:

  • A User table contains user attributes.

  • A Sale table contains sale attributes.

  • The sale table contains a reference to the user who made the sale.

The logical schema is more specific than the conceptual schema but remains relatively independent of a particular database product.

Physical Schema

The physical schema concerns actual implementation.

It includes decisions about:

  • Which RDBMS to use

  • Which server will host the database

  • How data will be stored

  • Which data types will be used

  • How users will connect

  • Which views and permissions will exist

  • How security will be enforced

  • How the database will be tested

The three levels can be understood as a progression:

Conceptual ideas are gradually transformed into logical structures and finally into physical implementations.


10. Data Integrity and Anomalies

Data integrity means that the data in a database is correct, consistent, valid, and properly connected.

A database with good integrity avoids:

  • Incorrect values

  • Repeating information

  • Outdated data

  • Broken relationships

  • Invalid references

  • Conflicting records

Anomalies

An anomaly is an unexpected error or inconsistency in stored data.

Common anomalies include:

  • An update changing one copy of data but not another

  • A record being inserted without required information

  • A record being deleted while related data remains incorrectly

  • One person appearing to have two different addresses

Repeating Data Problem

Suppose a user table contains:

  • User ID

  • Username

  • Phone number

  • Favorite color

If a user has multiple favorite colors, the same user information might be repeated in multiple rows:

User ID

Username

Phone

Favorite Color

7

CalebCurry

1234567

Blue

7

CalebCurry

1234567

Green

If the phone number changes, both rows must be updated. If only one changes, the database becomes inconsistent.

The solution is to separate data into related tables rather than storing multiple facts in one large table.


11. Three Types of Data Integrity

Entity Integrity

Entity integrity requires every entity to be uniquely identifiable.

A table should not contain two indistinguishable rows representing either:

  • The same entity twice, or

  • Two different entities that cannot be distinguished

A primary key, such as a user ID, normally enforces entity integrity.

Referential Integrity

Referential integrity keeps relationships between tables valid.

If a comment contains a user ID, that user ID should refer to an existing user. A comment should not refer to a user who does not exist.

Referential integrity prevents orphaned records, such as:

  • A comment with no valid commenter

  • A sale with no buyer

  • An order with no customer

Domain Integrity

Domain integrity limits the values allowed in a column.

A domain is the set or range of acceptable values for a field.

Examples:

  • A phone number should contain an appropriate number of digits.

  • A date field should contain a valid date.

  • A numeric field should not contain ordinary text.

  • A rating field might accept only values from 111 through 555.

Data types and constraints are used to enforce domain integrity.


12. NULL, Empty Values, and Anomalies

NULL means that no value is stored in a field. It does not mean zero, an empty string, or a known value of “none.”

For example, a person who has no fax number may have a NULL fax field.

NULL is different from:

  • Zero

  • An empty text value

  • The word “unknown”

  • The word “none”

A database must decide whether each column is allowed to contain NULL.


13. Atomic Values

An atomic value contains one logical item.

Atomicity is important because a column should represent one type of fact, and each field should contain one value.

Non-Atomic Examples

A single name field containing:

  • First name

  • Middle name

  • Last name

may not be atomic if the application needs to search or sort each name separately.

A better design may use:

  • first_name

  • middle_name

  • last_name

An address might similarly be separated into:

  • Street address

  • City

  • State

  • Postal code

  • Country

This makes queries such as “find all users in California” easier.

Avoiding Over-Atomicity

Atomicity does not mean splitting information into meaningless pieces.

For example:

  • A phone number can normally remain one value.

  • A word should not be split into individual letters.

  • A complete email address usually remains one value.

The goal is to store one meaningful item, not the smallest physically possible fragment.

Multiple Values in One Column

A column such as favorite_movies should not contain an unlimited list of movies in one field.

Instead, multiple movies should be represented through another table and a relationship.


14. Relationships Between Entities

A relationship describes how two entities are connected.

Examples include:

  • A user makes an order.

  • A student takes a class.

  • A professor teaches a class.

  • A customer owns a card.

  • A user posts a comment.

Relationships help determine how tables should be structured.

Parent and Child Entities

A parent is an entity that another entity depends on.

A child is an entity that depends on a parent.

Examples:

  • A user is the parent of a comment.

  • A customer is the parent of an order.

  • A cardholder may be the parent of a card.

  • A class and student can both act as parents of an enrollment record.

The child usually stores a foreign key pointing to the parent’s primary key.

The primary key is stored in the parent; the foreign key is stored in the child.


15. Cardinality: Types of Relationships

Cardinality describes how many entities on one side can be associated with entities on the other side.

The three basic relationship types are:

  1. One-to-one

  2. One-to-many

  3. Many-to-many

One-to-One Relationships

A one-to-one relationship means one entity can be related to only one entity on the other side, and vice versa.

Examples:

  • One person has one intended social security number.

  • One account has one username.

  • One cardholder has one card, if the business imposes that restriction.

A one-to-one relationship is often stored as an attribute in the same table.

For example, a user table might contain:

  • User ID

  • Name

  • Username

  • Email

The username is an attribute of that user rather than a separate entity.

One-to-One Relationships Across Two Tables

A separate table may be appropriate when the related entity has many additional attributes.

For example, a cardholder table might contain:

  • Cardholder ID

  • First name

  • Last name

  • Card ID

A separate card table might contain:

  • Card ID

  • Card number

  • Issue date

  • Maximum amount

  • Late fee

Separating the card prevents a user table from storing information about two different entities.

One-to-Many Relationships

A one-to-many relationship means one entity can be related to multiple entities, while each entity on the many side relates to only one entity on the one side.

Examples:

  • One user can post many comments.

  • One user can own many cards.

  • One customer can place many orders.

  • One professor can teach many classes.

The foreign key is stored on the many side.

For example:

  • User contains user_id as its primary key.

  • Comment contains user_id as a foreign key.

Each comment points back to one user, while one user may be referenced by many comments.

Many-to-Many Relationships

A many-to-many relationship means:

  • One entity can relate to many entities on the other side.

  • Each entity on the other side can also relate to many entities from the first side.

Examples:

  • A student can take many classes.

  • A class can contain many students.

  • An author can write many books.

  • A book can have many authors.

  • A professor can teach many classes.

  • A class can be taught by many professors.

A many-to-many relationship cannot be stored directly in a standard relational table without causing structural problems.


16. Junction Tables for Many-to-Many Relationships

A many-to-many relationship is converted into two one-to-many relationships using an intermediary table, also called a:

  • Junction table

  • Associative table

  • Linking table

Student and Class Example

Instead of storing multiple class columns in the student table or multiple student columns in the class table, three tables are used:

  1. Student

  2. Class

  3. Student_Class

The junction table contains:

  • student_id

  • class_id

Each row represents one enrollment.

Example:

Student ID

Class ID

8

75

8

89

16

75

This means:

  • Student 888 takes classes 757575 and 898989.

  • Student 161616 takes class 757575.

The junction table stores the many side of both one-to-many relationships.

Advantages

A junction table:

  • Avoids repeating columns

  • Avoids empty columns

  • Supports any number of relationships

  • Preserves referential integrity

  • Allows relationships to be added or removed easily

Each parent table points to the junction table, and each junction-table row identifies one specific connection.


17. Choosing Relationship Types

Relationship types depend on the rules of the real-world application.

For example, the relationship between professors and classes could be:

  • One-to-one if each professor teaches exactly one class and each class has one professor.

  • One-to-many if one professor teaches many classes and each class has one professor.

  • Many-to-many if professors can teach multiple classes and classes can have multiple professors.

There is no universal relationship type for every concept. The correct design depends on the rules the application must support.


18. Keys

A key is a column or group of columns used to identify records and establish relationships.

Keys help:

  • Enforce uniqueness

  • Identify entities

  • Connect tables

  • Support joins

  • Improve search performance

  • Protect referential integrity

Key Requirements

A primary identifying key should generally be:

  • Unique: no two records share the same key.

  • Stable: the key should not change.

  • Non-NULL: every record must have a key.

Poor Key Choices

The following are often poor keys:

  • Passwords, because multiple users may share one.

  • First names, because they repeat.

  • Last names, because they repeat.

  • First name plus last name, because duplicate names exist.

  • Frequently changing information, such as an address.

A username or verified email may sometimes serve as a natural key if uniqueness and stability are guaranteed.


19. Super Keys, Candidate Keys, and Primary Keys

Super Key

A super key is any set of one or more columns that uniquely identifies every row.

A super key may contain unnecessary columns.

For example, the combination of all the following might uniquely identify a user:

  • Username

  • Email

  • First name

  • Last name

  • Birthday

Although unique, this is excessive.

Candidate Key

A candidate key is the smallest set of columns that still guarantees uniqueness.

A table may have several candidate keys, such as:

  • Username

  • Email

  • A combination of name and date of birth

Primary Key

A primary key is the candidate key selected as the main identifier for the table.

A table has one primary key definition, although that key may consist of multiple columns.

A primary key:

  • Identifies each row

  • Cannot be NULL

  • Should not change

  • Is commonly indexed

  • May be referenced by foreign keys

Alternate Key

An alternate key is a candidate key that was not selected as the primary key.

Alternate keys can still be enforced as unique and may be indexed when frequently searched.


20. Natural and Surrogate Keys

Natural Key

A natural key is a value that already exists for a real-world purpose.

Examples include:

  • Username

  • Email address

  • ISBN

  • Social security number

  • A business code

Advantages:

  • No additional column is required.

  • The value already has meaning.

  • The database stores less extra data.

Disadvantages:

  • Suitable natural keys may not always exist.

  • Natural values may change.

  • Natural keys can be long or complex.

  • Foreign-key relationships may become harder to manage.

  • Real-world meaning can change over time.

Surrogate Key

A surrogate key is an artificial identifier created solely for database use.

Examples include:

  • User ID

  • Product ID

  • Order ID

  • Comment ID

  • Student ID generated internally by the database

A surrogate key is commonly an automatically generated number.

Advantages:

  • Usually short and efficient

  • Does not change when real-world data changes

  • Easy to use in relationships

  • Keeps foreign keys simple

  • Has no external meaning

Disadvantages:

  • Requires an additional column.

  • Stores extra data.

  • Can be less descriptive.

  • Developers must inspect the schema to understand what an ID represents.

If surrogate keys are used, the database should still enforce natural uniqueness where appropriate. For example, a user may have a surrogate user_id, while username is also required to be unique.

A design should generally use natural or surrogate keys consistently rather than switching unpredictably between them.


21. Foreign Keys

A foreign key is a column that references a primary key in another table, or occasionally a primary key in the same table.

For example:

  • User.user_id is a primary key.

  • Comment.user_id is a foreign key referencing User.user_id.

Foreign keys:

  • Connect related tables

  • Support parent-child relationships

  • Enforce referential integrity

  • Prevent references to nonexistent records

  • Allow joins between tables

A table may have one primary key and multiple foreign keys.

For example, a class table may contain:

  • class_id as its primary key

  • instructor_id as a foreign key

  • building_id as a foreign key

Each foreign key can reference a different table.

Foreign-Key Data Types

A foreign key and the primary key it references should generally have compatible:

  • Data types

  • Lengths

  • Character sets

  • Collations

  • Storage-related characteristics

The foreign key may allow NULL when the relationship is optional, while the primary key cannot be NULL.


22. NULL Constraints and Optional Relationships

A NOT NULL constraint requires every row to contain a value in that column.

Required Relationship

If a foreign key is NOT NULL, every child must have a parent.

Examples:

  • Every comment must have a user.

  • Every order must have a customer.

  • Every card must have an owner.

Optional Relationship

If a foreign key allows NULL, a child may exist without a related parent.

Examples:

  • A class may exist before an instructor is assigned.

  • A card may exist before it is activated.

  • A user may exist without owning a car.

Primary keys are always required, but foreign keys may be optional depending on the business rules.

A foreign-key value can change when the relationship changes. For example, a user may stop owning one car and begin owning another. The car IDs themselves should remain stable, but the user’s foreign-key reference may change.


23. Foreign-Key Constraints

Foreign-key constraints specify what should happen when a referenced parent is updated or deleted.

Common actions include:

Restrict

Restrict prevents the parent operation and generates an error if related child records exist.

For example, a user cannot be deleted while comments still reference that user.

Cascade

Cascade applies the parent operation to the children.

  • Deleting a user deletes the user’s comments.

  • Updating a referenced key updates the corresponding foreign keys.

Cascading deletion must be used carefully because it can remove many dependent records.

Set NULL

Set NULL changes the child foreign-key value to NULL when the parent is deleted or updated.

This is appropriate only when:

  • The relationship is optional.

  • The foreign-key column allows NULL.

  • Keeping the child record without a parent is meaningful.

Foreign-key constraints reduce manual maintenance and prevent inconsistent references.


24. Simple, Composite, and Compound Keys

Simple Key

A simple key consists of one column.

Examples:

  • user_id

  • username

  • email

Composite Key

A composite key consists of multiple columns used together to guarantee uniqueness. In some terminology, composite is used broadly for any multi-column key.

For example, a combination of:

  • First name

  • Last name

  • Email

may form a composite key if the combination is unique.

Compound Key

A compound key commonly refers to a multi-column key in which each component is itself a key, often foreign keys in a junction table.

For a student-class junction table:

  • student_id

  • class_id

Together they form a compound primary key. The same student may appear multiple times, and the same class may appear multiple times, but the same student-class combination must not appear twice.

Some systems use composite and compound interchangeably, so terminology may vary.


25. Indexes

An index improves the speed of searching and joining data.

Book Analogy

A book index lists topics and the pages where they occur. It avoids reading every page to find one topic.

A database index similarly helps the system locate matching rows without scanning the entire table.

Table Scan and Index Seek

Without an appropriate index, the database may perform a table scan, checking rows one by one.

With an index, the database can perform an index seek, going directly to the likely location of the desired records.

Indexes are especially valuable for:

  • Primary-key searches

  • Foreign-key joins

  • Frequently used WHERE conditions

  • Frequently searched columns

Clustered Index

A clustered index organizes the actual table data according to the index order.

Because the data can be physically organized in only one primary ordering, a table usually has at most one clustered index.

Non-Clustered Index

A non-clustered index is a separate structure containing indexed values and references to the corresponding table rows.

A table can have multiple non-clustered indexes.

Index Trade-Offs

Indexes improve read performance but introduce costs:

  • They require additional storage.

  • They must be updated when table data changes.

  • Too many indexes can slow inserts, updates, and deletes.

  • An index should be created only when it supports useful searches or joins.

Composite Indexes

A composite index covers multiple columns.

For example, an index on:

  • Last name

  • First name

may improve searches involving both fields.

The usefulness of a composite index depends on the database system and the order of its columns. Many systems can efficiently use the leading or leftmost column, but not necessarily a later column by itself.


26. Lookup Tables

A lookup table stores a fixed or limited set of allowed options.

For example, instead of storing repeated membership names directly in a member table, a database can use:

Membership Table

  • Membership ID

  • Membership name

  • Price

  • Duration

  • Other membership information

Member Table

  • Member ID

  • Name

  • Membership ID as a foreign key

This avoids storing repeated values such as Gold, Gold, and Gold in thousands of rows.

Benefits

Lookup tables:

  • Reduce repetition

  • Restrict values to valid choices

  • Improve domain integrity

  • Allow additional information about each option

  • Make updates easier

If the name of a membership changes, only the lookup row needs to be updated.


27. Entity-Relationship Diagrams

An entity-relationship diagram, or ERD, is a visual representation of database structure.

Related terms include:

  • ER model

  • ER diagram

  • Enhanced ER model

  • EER diagram

An ERD typically shows:

  • Tables or entities

  • Columns or attributes

  • Primary keys

  • Foreign keys

  • Relationships

  • Cardinality

  • Optionality

A table is commonly drawn as a box containing:

  • The table name

  • Its columns

  • Key indicators

  • Sometimes data types and constraints

ERDs generally describe the database structure rather than individual data values.

Crow’s Foot Notation

Crow’s foot notation represents cardinality visually:

  • A single line represents one.

  • A crow’s-foot symbol represents many.

  • A circle represents zero or optional.

  • A bar represents one or required.

Examples include:

  • Exactly one

  • Zero or one

  • One or many

  • Zero or many


28. Modality and Optionality

Modality describes whether participation in a relationship is required.

Examples:

  • A comment must have a user.

  • A user may have zero comments.

  • A card may or may not have an owner.

  • A class may exist before an instructor is assigned.

Cardinality describes the maximum relationship count, while modality describes whether the minimum is zero or one.

Examples:

  • Zero or one: optional one-to-one

  • One or one: required one-to-one

  • Zero or many: optional one-to-many

  • One or many: required one-to-many


29. Normalization

Normalization is a systematic process for improving database structure.

Normalization aims to:

  • Reduce repeated data

  • Eliminate update anomalies

  • Improve data integrity

  • Ensure that data is stored in logically appropriate tables

  • Create clear dependencies between attributes and keys

The primary normal forms discussed are:

  1. First normal form

  2. Second normal form

  3. Third normal form

The normal forms are cumulative:

A table in third normal form must already satisfy second normal form and first normal form.


30. First Normal Form

First normal form, or 1NF, requires values to be atomic and prevents repeating groups.

A table violates 1NF when:

  • A field contains multiple logical values.

  • A column contains lists.

  • Repeating groups are stored in one row.

  • The same entity is duplicated to represent multiple values.

Address Example

Instead of storing an entire address in one field:

  • 123 Example Lane, California, 73821

the design may separate:

  • Street address

  • City

  • State

  • Postal code

  • Country

Multiple Email Example

If a user has two email addresses, they should not be stored in one field separated by a comma.

Instead, use:

User Table

  • User ID

  • First name

  • Last name

Email Table

  • Email ID

  • Email address

  • User ID as a foreign key

Each email becomes its own row, while the user ID can repeat because it is a foreign key representing a one-to-many relationship.

1NF does not prohibit repeating foreign-key values. It prohibits storing multiple values in one field or duplicating an entire entity unnecessarily.


31. Second Normal Form

Second normal form, or 2NF, requires:

  1. The table must already be in 1NF.

  2. Every non-key attribute must depend on the entire primary key.

2NF primarily matters when the primary key is composite.

Partial Dependency

A partial dependency occurs when an attribute depends on only part of a composite key.

Suppose a junction table has:

  • Author ID

  • Book ID

  • Author position

  • ISBN

The combination of author ID and book ID identifies the relationship.

  • Author position depends on both the author and the book.

  • ISBN depends only on the book.

Therefore, ISBN is partially dependent on the composite key and does not belong in the junction table.

The solution is to place ISBN in the Book table.

Tables with Simple Keys

If a table has a single-column primary key, partial dependency is not possible because there is no “part” of the key. Such a table is automatically free of partial dependencies for 2NF purposes, provided it is already in 1NF.


32. Third Normal Form

Third normal form, or 3NF, requires:

  1. The table must already be in 2NF.

  2. Non-key attributes must not depend on other non-key attributes.

Transitive Dependency

A transitive dependency occurs when:

  • Attribute A depends on the primary key.

  • Attribute B depends on attribute A.

  • Therefore, attribute B indirectly depends on the primary key through A.

For example, a review table might contain:

  • Review ID

  • Star rating

  • Star meaning

The star meaning depends on the star rating:

  • A rating of 555 means “excellent.”

  • A rating of 333 means “average.”

The star rating depends on the review ID, but the star meaning does not directly describe the review. It describes the rating.

Corrected Design

Create a separate rating table:

Rating Table

  • Rating ID

  • Numeric rating

  • Rating meaning

Review Table

  • Review ID

  • Review text

  • Rating ID as a foreign key

  • User ID as a foreign key

This removes the transitive dependency and prevents repeated descriptions of the same rating.


33. Data Types

A data type defines what kind of value a column can store.

Every value in a column should conform to that column’s data type.

The broad categories are:

  1. String

  2. Numeric

  3. Date and time

Exact names differ among database systems.

String Types

A string contains text or characters.

Examples:

  • Names

  • Usernames

  • Email addresses

  • Comments

  • Addresses

A number enclosed as text is still a string, not a numeric value.

Fixed-Length Character Types

A fixed-length character type, commonly called CHAR, reserves a fixed number of characters.

It is useful for values with a consistent length, such as:

  • Certain codes

  • Fixed-format identifiers

  • Some postal codes

Variable-Length Character Types

A variable-length type, commonly called VARCHAR, stores text whose length can vary.

It is useful for:

  • Names

  • Usernames

  • Email addresses

  • Short descriptions

Text Types

Large text types are useful for:

  • Comments

  • Messages

  • Articles

  • Long descriptions

Numeric Types

Numeric types store numbers used in calculations.

Examples include:

  • Integers

  • Decimal numbers

  • Floating-point numbers

Integers

An integer is a whole number without a fractional component.

Examples include:

  • 777

  • 512512512

  • −52-52−52

Decimal Values

Decimal types represent base-ten values and are often preferred when exact precision is important, such as financial amounts.

Floating-Point Values

Floating-point values use binary-based internal representations. They are efficient for many calculations but may not represent some decimal fractions exactly.

For example, values such as 0.10.10.1 may require approximation in binary storage. Exact financial calculations generally require an appropriate decimal type rather than an imprecise floating-point type.

Signed and Unsigned Numbers

  • Signed numbers can be positive or negative.

  • Unsigned numbers cannot be negative.

Unsigned types are appropriate when negative values have no meaning, such as a count of items.

Date and Time Types

Date and time data types store temporal information.

  • Date: calendar date

  • Time: time of day

  • Date-time: combination of a date and time

  • Timestamp: a recorded point in time, often used to track when a record was created or modified

Timestamps are useful for:

  • Account creation time

  • Transaction time

  • Last update time

  • Comment publication time


34. Joins

A join combines related data from multiple tables into a result that is easier to read or use.

Normalization may distribute information across several tables to reduce repetition. A join reconstructs a useful presentation of that information without physically merging the tables.

For example:

  • The comment table stores a user ID.

  • The user table stores the username.

  • A join can replace the user ID with the actual username in the result.

Joins are a form of DML because they manipulate how existing data is retrieved and presented without changing the database structure.

Join Conditions

A join condition specifies how rows from two tables are related.

The most common condition compares a primary key with a foreign key:

  • User.user_id = Comment.user_id

The table name and column name are often written together to avoid ambiguity.


35. Inner Joins

An inner join returns only rows that have matching values in both tables.

Suppose:

  • A customer table contains customers.

  • A card table contains cards.

  • Some customers have no cards.

  • Some cards have no current customer.

An inner join returns only:

  • Customers with matching cards

  • Cards with matching customers

It excludes unmatched rows from both tables.

Inner Join Across Multiple Tables

For three tables, the database can join them step by step:

  1. Join the first two tables.

  2. Use the result as an intermediate set.

  3. Join that result with the third table.

  4. Apply another join condition.

As more inner joins are added, the result generally becomes more restrictive because a row must satisfy every join condition.

For a user-comment-video system:

  • Users are joined to comments through user_id.

  • Comments are joined to videos through video_id.

An inner join returns only:

  • Users who posted comments

  • Comments with valid users

  • Comments associated with valid videos

  • Videos that have matching comments


36. Left Outer Joins

A left outer join returns every row from the left table, even when no matching row exists in the right table.

When no match exists, the right-side columns contain NULL.

For a customer-card example, placing the customer table on the left returns:

  • Every customer

  • The customer’s cards when they exist

  • NULL card information for customers without cards

A left join is useful when the left table represents the complete list that must be preserved.


37. Right Outer Joins

A right outer join returns every row from the right table, even when no matching row exists in the left table.

For a customer-card example, placing the card table on the right returns:

  • Every card

  • The card’s customer when one exists

  • NULL customer information for cards without customers

A right join is functionally similar to reversing the table order and using a left join. Many developers prefer left joins for consistency and readability.


38. Full Outer Joins

A full outer join returns all rows from both tables:

  • Matching rows are combined.

  • Unmatched rows from the left are retained.

  • Unmatched rows from the right are retained.

  • Missing values are represented as NULL.

Support for full outer joins differs among database systems, and some systems simulate them using other operations.


39. Joins, NULL, and NOT NULL

Constraints affect join results.

For example, if every comment must have a user, the comment’s user_id should be NOT NULL. If every comment must belong to a video, video_id should also be NOT NULL.

In that case:

  • An inner join can return all valid comments.

  • A left join from comments preserves every comment.

  • A left join from users preserves every user, including users with no comments.

The correct join depends on which rows must be preserved.

A useful planning method is:

  1. Identify the table whose rows must all appear.

  2. Place it on the preserved side of an outer join.

  3. Determine which related rows are optional.

  4. Check whether foreign keys allow NULL.

  5. Select inner or outer joins according to the required result.


40. Aliases

An alias is a temporary alternate name for a table or column.

Aliases improve readability and make SQL easier to write.

Table Aliases

A table alias can shorten repeated table names.

For example, a long table name can be assigned a short alias such as u. Columns can then be referenced as:

  • u.user_id

  • u.email

Aliases are especially important in self-joins, where the same table must be treated as two logical sources.

Column Aliases

A column alias changes the name displayed in the result.

For example:

  • first_name can be displayed as First Name.

  • A calculated column can be given a readable label.

  • A second email column can be labeled Referred By.

Column aliases change the presentation of the query result, not the underlying column name.


41. Self-Joins

A self-join joins a table to itself.

It is useful when rows in a table reference other rows in the same table.

Referral Example

A user table might contain:

  • User ID

  • Username

  • Email

  • Referred-by user ID

The referred_by column is a foreign key referencing another row in the same user table.

A self-join can retrieve:

  • The current user’s information

  • The email or name of the person who referred that user

Because the table is used twice, each logical instance must receive a different alias, such as:

  • u1 for the current user

  • u2 for the referring user

The join condition compares:

  • u1.referred_by

  • u2.user_id

Self-joins can represent hierarchical or recursive relationships such as:

  • Employee and manager

  • Parent and child categories

  • Referral chains

  • Organizational structures


42. Overall Database Design Process

A practical database design process can follow these steps:

  1. Identify the data

    • Determine what information the system must store.

  2. Identify entities

    • List users, products, orders, comments, classes, and other objects.

  3. Identify attributes

    • Determine what facts must be stored about each entity.

  4. Ensure atomicity

    • Make sure each field contains one meaningful value.

  5. Determine relationships

    • Identify one-to-one, one-to-many, and many-to-many relationships.

  6. Create tables

    • Give each entity its own appropriate table.

  7. Choose keys

    • Select primary keys and determine whether natural or surrogate keys are appropriate.

  8. Add foreign keys

    • Connect child tables to parent tables.

  9. Apply constraints

    • Define uniqueness, NULL rules, data types, and foreign-key actions.

  10. Normalize the design

    • Check first, second, and third normal forms.

  11. Add lookup tables

    • Separate fixed sets of repeated options.

  12. Plan indexes

    • Index primary keys, foreign keys, and frequently searched columns.

  13. Design views and joins

    • Decide how normalized data will be presented to users and applications.

  14. Consider security

    • Limit access according to user roles and responsibilities.

  15. Implement and test

    • Build the physical database and test insertions, updates, deletions, queries, joins, and constraints.

A strong database design separates information logically while preserving the relationships needed to reconstruct useful, accurate, and secure views of the data.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent