Showing posts with label relational database. Show all posts
Showing posts with label relational database. Show all posts

Saturday, 17 August 2013

Db2 Relationships: One-to-One, One-to-Many, and Many-to-Many

Db2 table relationships diagram showing one-to-one, one-to-many, and many-to-many relationships with primary and foreign keys
Relationships decide how Db2 tables join.

A COBOL cursor that joins CUSTOMER to ACCOUNT is only as good as the table relationship behind it. If ACCOUNT.CUST_NO does not point back to a real customer key, the program can return missing rows, duplicate rows, or orphan account records that no business user can explain.

This refresh explains the three relationship patterns used in relational database design: one-to-one, one-to-many, and many-to-many. The examples use Db2 table names, primary keys, foreign keys, and embedded SQL patterns that a mainframe developer is likely to review in batch or CICS programs.

What a Db2 Relationship Means

A relationship exists when rows in one table are associated with rows in another table. In Db2, that association is usually expressed through key columns: a primary key or unique key on the parent table, and a foreign key on the child table.

CREATE TABLE CUSTOMER
 (CUST_NO     CHAR(10) NOT NULL,
  CUST_NAME   VARCHAR(60),
  PRIMARY KEY (CUST_NO));

CREATE TABLE ACCOUNT
 (ACCT_NO     CHAR(12) NOT NULL,
  CUST_NO     CHAR(10) NOT NULL,
  BALANCE     DECIMAL(13,2),
  PRIMARY KEY (ACCT_NO),
  FOREIGN KEY (CUST_NO)
    REFERENCES CUSTOMER (CUST_NO));

In this example, CUSTOMER is the parent table and ACCOUNT is the child table. The relationship says that an account row must reference an existing customer row.

Primary Key, Foreign Key, and Parent Table

TermMeaning in Db2 designExample
Primary keyColumn or columns that uniquely identify a row in a table.CUSTOMER.CUST_NO
Foreign keyColumn or columns in one table that reference a parent key.ACCOUNT.CUST_NO
Parent tableTable that owns the referenced key.CUSTOMER
Child tableTable that stores the foreign key.ACCOUNT
Referential integrityRule that keeps child rows from pointing to missing parent rows.Account cannot reference an unknown customer.

One-to-One Relationship

A one-to-one relationship means one row in the first table matches at most one row in the second table, and one row in the second table matches at most one row in the first table.

A common design is a base table plus a detail table:

CUSTOMER
  CUST_NO       primary key
  CUST_NAME

CUSTOMER_PROFILE
  CUST_NO       primary key and foreign key
  TAX_STATUS
  CONTACT_PREF

The detail table uses the same key as the parent. This pattern is useful when optional or sensitive columns should be stored separately, but the row still belongs to exactly one parent row.

One-to-Many Relationship

A one-to-many relationship means one parent row can have many child rows, while each child row points to one parent row. This is the most common relationship in business applications.

CUSTOMER
  CUST_NO       primary key

ACCOUNT
  ACCT_NO       primary key
  CUST_NO       foreign key to CUSTOMER

A COBOL program might fetch all accounts for one customer like this:

EXEC SQL
    DECLARE C-ACCT CURSOR FOR
    SELECT A.ACCT_NO,
           A.BALANCE
      FROM ACCOUNT A
     WHERE A.CUST_NO = :WS-CUST-NO
END-EXEC.

If CUST_NO is indexed on ACCOUNT, this kind of cursor is easier for Db2 to access efficiently.

Many-to-Many Relationship

A many-to-many relationship means rows on both sides can match many rows on the other side. Do not store repeating columns such as COURSE_1, COURSE_2, and COURSE_3. Use a linking table, also called an associative or junction table.

STUDENT
  STUD_ID       primary key

COURSE
  COURSE_ID     primary key

ENROLLMENT
  STUD_ID       foreign key to STUDENT
  COURSE_ID     foreign key to COURSE
  ENROLL_DATE
  PRIMARY KEY (STUD_ID, COURSE_ID)

The linking table turns one many-to-many relationship into two one-to-many relationships. That keeps inserts, deletes, and joins easier to control.

Join Pattern for a Linking Table

A COBOL report that lists courses for one student can join through the linking table:

EXEC SQL
    DECLARE C-COURSE CURSOR FOR
    SELECT C.COURSE_ID,
           C.COURSE_TITLE,
           E.ENROLL_DATE
      FROM ENROLLMENT E
      JOIN COURSE C
        ON C.COURSE_ID = E.COURSE_ID
     WHERE E.STUD_ID = :WS-STUD-ID
     ORDER BY E.ENROLL_DATE
END-EXEC.

The cursor does not need repeating host variables for course slots. Each enrollment row is one fact.

Relationship Cardinality at a Glance

RelationshipParent and child patternDb2 design note
One-to-oneOne parent row maps to one detail row.The child key often acts as both primary key and foreign key.
One-to-manyOne parent row maps to many child rows.The foreign key belongs on the many side.
Many-to-manyMany rows on each side can match.Use a linking table with foreign keys to both parent tables.

Delete Rules Need Care

Relationships affect delete and update behavior. If a customer row has account rows, Db2 must know what should happen when someone tries to delete the customer.

Referential actionTypical meaningProduction caution
RESTRICT or NO ACTIONPrevent parent delete when child rows exist.Common for master data that must not be removed while dependent rows remain.
CASCADEDelete child rows when the parent is deleted.Use only when the business rule is explicit and tested.
SET NULLSet the child foreign key to null when the parent is deleted.Only works when a missing parent is valid for the application.

Batch purge programs need special care here. A delete that looks small in the parent table can affect many child rows.

Common Design Mistakes

  • Putting the foreign key on the wrong side of a one-to-many relationship.
  • Modeling many-to-many relationships with repeating columns instead of a linking table.
  • Using nullable foreign keys when the business rule requires a parent row.
  • Skipping indexes on foreign key columns that are frequently joined or searched.
  • Writing joins from column names alone without checking the real relationship.

How Relationships Affect Db2 Performance

Relationships are logical design, but they also affect access paths. A cursor that joins parent and child tables usually needs useful indexes on join columns and current statistics.

SELECT C.CUST_NAME,
       A.ACCT_NO,
       A.BALANCE
  FROM CUSTOMER C
  JOIN ACCOUNT A
    ON A.CUST_NO = C.CUST_NO
 WHERE C.CUST_NO = :WS-CUST-NO

After the relationship is correct, use EXPLAIN and statistics to review the access path. The Db2 SQL Optimization Tips for COBOL Programs post covers that check.

How This Fits with Other Db2 Topics

Relationships are part of relational design. They sit close to Db2 Anatomy of a Relational Database, Db2 Objects, and Db2 Indexing. For current product context, see IBM's Db2 for z/OS page and the ISO SQL framework.

FAQ

What is a one-to-many relationship in Db2?

A one-to-many relationship means one parent row can match many child rows. The child table stores a foreign key that points to the parent key.

How do I model a many-to-many relationship?

Use a linking table. The linking table stores foreign keys to both parent tables and often uses those columns as a composite primary key.

Do foreign keys improve query performance?

Foreign keys define the relationship and protect data consistency. Performance usually depends on indexes, statistics, predicates, and the access path Db2 chooses.

Good relationship design gives COBOL SQL a clean target: one parent key, clear child rows, and joins that match the business rule.

Db2 Early Vendor Implementations: Oracle, Ingres, SQL/DS, and Db2

Relational database timeline from Codd and System R through Oracle, Ingres, SQL/DS, and Db2 for MVS
SQL moved from research into mainframe work.

A COBOL program that opens a Db2 cursor in MVS has a long history behind it. SQL did not arrive as a finished mainframe product on day one. It came through research prototypes, early commercial vendors, competing query languages, and IBM product decisions that turned relational database theory into production software.

This refresh keeps the original history topic but makes it more useful for Mainframe Forum readers. The focus is the route from IBM System R and early vendors to SQL/DS and Db2, with enough context to understand why SQL became the language mainframe developers still use in embedded SQL programs.

Why Early Vendor Implementations Matter

Early relational database products were not only academic milestones. They shaped the SQL syntax, catalog concepts, optimizer behavior, and application patterns that later appeared in Db2 for z/OS and COBOL programs.

For a mainframe developer, the practical point is simple: Db2 was not created in isolation. It grew from a market where SQL, QUEL, minicomputers, mainframes, and vendor timing all mattered.

Timeline of Early Relational Database Work

YearProduct or projectWhy it mattered
1970E. F. Codd relational modelDefined the table-based model that later RDBMS products tried to implement.
1974IBM System RIBM research project that helped prove SQL and relational access could work in real systems.
1979OracleEarly commercial SQL RDBMS that reached customers before IBM's mainframe Db2 product.
1981IBM SQL/DSIBM commercial relational database product for VM and VSE environments.
1983IBM Database 2Db2 was announced for MVS, bringing IBM relational database technology to mainstream mainframe workloads.

IBM System R and the SQL Starting Point

IBM's System R project at San Jose was a research system, not the Db2 product that COBOL teams later used. Its importance came from proving that relational access could handle real database work and that SQL could be used as a higher-level data access language.

That mattered for application programmers. Instead of coding physical navigation through records, a program could ask for rows that matched predicates:

SELECT EMPNO,
       LASTNAME,
       WORKDEPT
  FROM EMP
 WHERE WORKDEPT = :WS-DEPT

The database engine decides the access path. The application states the result. That separation is one reason SQL became a natural fit for business applications on mainframes.

Oracle and the First Commercial SQL Race

Relational Software, Inc., later Oracle Corporation, moved early with a commercial SQL database. Oracle's early product reached the market before IBM's Db2 for MVS product, which gave SQL a commercial life outside IBM research labs.

The main lesson is timing. IBM did much of the research work, but other vendors saw the value of SQL and delivered products while IBM was still turning research into production offerings. Oracle's own database documentation describes SQL as a set-based, declarative interface to an RDBMS, which is the same application idea a COBOL developer sees in embedded SQL.

Ingres and the QUEL Alternative

Ingres came from the University of California, Berkeley. It was another major relational database project, and it originally used QUEL rather than SQL. QUEL had strong technical supporters, but SQL gained more commercial traction and became the standard language developers expected across products.

For Mainframe Forum readers, Ingres explains an easy-to-miss point: SQL was not the only possible relational language. It won because vendors, standards work, tools, and customers moved toward it.

SQL/DS Before Db2 for MVS

Before Db2 became the main name mainframe developers recognized, IBM shipped SQL/DS for VM and VSE environments. SQL/DS gave IBM a commercial relational database product while Db2 for MVS was still coming into view.

This distinction matters when reading older manuals, interview notes, or migration documents. SQL/DS and Db2 are related in history and SQL direction, but they were not the same product in the same operating environment.

Db2 for MVS and Mainframe COBOL Programs

IBM announced Database 2, better known as Db2, for MVS in 1983. For mainframe shops, this placed relational database access next to COBOL, CICS, batch jobs, JCL, and MVS operations.

Once Db2 became part of the mainframe application stack, COBOL programs could use embedded SQL through a precompile, bind, and runtime process:

EXEC SQL
    SELECT LASTNAME,
           WORKDEPT
      INTO :WS-LASTNAME,
           :WS-WORKDEPT
      FROM EMP
     WHERE EMPNO = :WS-EMPNO
END-EXEC.

The source statement looks simple, but the build process is not just a compile. The SQL is extracted into a DBRM, bound into a package or plan, and then run under Db2 control. The related Db2 Packages Guide for COBOL Static SQL covers that path in more detail.

What Changed for Application Design

Relational database products changed the way teams described data access. A program no longer had to hard-code every navigation step through a file or hierarchical database. The SQL statement described rows and columns, while the optimizer chose an access path from indexes, statistics, and predicates.

That shift later affected these everyday Db2 tasks:

  • Writing predicates that match available indexes.
  • Binding and rebinding static SQL after program changes.
  • Reviewing access paths with EXPLAIN.
  • Defining tables, views, indexes, and table spaces as separate database objects.
  • Keeping host variable definitions consistent with Db2 column data types.

Common Confusion in Older Db2 History Notes

Older posts and study notes sometimes compress the history into a single line such as "IBM invented SQL and then Db2 arrived." That is directionally useful but too short for a working explanation.

Confusing statementBetter reading
Db2 was the first relational database.Db2 was IBM's mainframe RDBMS product line; earlier research and vendor products came before it.
Oracle invented SQL.Oracle commercialized SQL early, but SQL came from IBM research work.
Ingres and Db2 were the same kind of system.Both were relational database efforts, but Ingres started outside IBM and used QUEL before SQL became dominant.
SQL/DS and Db2 are interchangeable names.They are historically related IBM relational products, but they served different environments.

How This Connects to Other Db2 Topics

If you are learning Db2 from the application side, this history is useful only when it connects back to daily work. After this article, the next practical topics are Db2 Origins of SQL, Db2 Binding and Rebinding, Db2 Optimizer, and Db2 Objects.

For current product context, see IBM's Db2 for z/OS product page. Oracle's database concepts documentation is also useful for general RDBMS and SQL terminology, and Actian maintains current information for Ingres.

FAQ

Was Db2 the first relational database?

No. Db2 was IBM's mainframe relational database product line, but relational research projects and early vendor products existed before Db2 for MVS reached customers.

Why did SQL win over QUEL?

SQL gained stronger vendor adoption, standards support, tooling, and customer demand. QUEL was technically respected, but SQL became the language most commercial RDBMS products supported.

Why should a COBOL programmer care about early database vendors?

The history explains why embedded SQL, bind packages, optimizers, indexes, and relational tables became normal parts of mainframe application work.

For a COBOL developer, the useful takeaway is not the vendor race by itself. It is that SQL became the shared contract between the program and the database engine.

New In-feed ads