Here is an example for composite keys. The database contains companies identified by some code for instance the EIN in the USA. The companies have departments and each company can decide for unique codes to identify their departments. Company A may use BD for their buying department, while company B uses BD also, but for their base department. Then each company has employees and each company uses some employee number to identify them. Employee #123 in comapny A is another person than employee #123 in company B. One employee works in one department in one company.
create table company
(
company_no decimal(9,0),
company_name varchar(100),
primary key (company_no)
);
create table department
(
company_no decimal(9,0),
department_code varchar(20),
name varchar(100),
primary key (company_no, department_code),
foreign key(company_no) references company(company_no)
);
create table employee
(
company_no decimal(9,0),
employee_no decimal(9,0),
first_name varchar(50),
last_name varchar(50),
department_code varchar(20),
primary key (company_no, employee_no),
foreign key(company_no, department_code) references department(company_no, department_code)
);
We could also add a constraint
foreign key(company_no) references company(company_no)
to the employee table, but that would be superfluous, as we already have the constraint on a department belonging to a company.