Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Created February 29, 2024 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JerryNixon/44a77103d92c0101c63f01314c0feb5b to your computer and use it in GitHub Desktop.
Save JerryNixon/44a77103d92c0101c63f01314c0feb5b to your computer and use it in GitHub Desktop.
Demonstrating a FK does not require a PK in SQL
begin transaction;
create table Location
(
Id int primary key,
City varchar(255),
[State] char(2),
Zip char(5) unique,
);
create table Address
(
Id int primary key,
[Name] varchar(255),
Street varchar(255),
Zip char(5) references location(Zip),
);
insert into [Location]
(Id, City, [State], Zip)
values
(1, 'New York', 'NY', '10001'),
(2, 'Los Angeles', 'CA', '90001'),
(3, 'Chicago', 'IL', '60007'),
(4, 'Houston', 'TX', '77001'),
(5, 'Phoenix', 'AZ', '85001');
insert into [Address]
(Id, [Name], Street, Zip)
values
(1, 'Home', '123 Main St', '10001'),
(2, 'Work', '456 Elm St', '90001'),
(3, 'School', '789 Oak St', '60007'),
(4, 'Gym', '101 Pine St', '77001'),
(5, 'Park', '202 Cedar St', '85001');
SELECT Street, City, [State], Address.Zip
FROM Address
JOIN Location ON Address.Zip = Location.Zip;
rollback;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment