Created
February 29, 2024 17:01
-
-
Save JerryNixon/44a77103d92c0101c63f01314c0feb5b to your computer and use it in GitHub Desktop.
Demonstrating a FK does not require a PK in SQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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