r/learnSQL • • 18d ago

Really struggling with the concept of KEYS

I have been teaching myself SQL in Snowflake for about the past few weeks at work as it is now part of my job. I've been able to understand almost every part of the basics from SELECT to FROM to ORDER and other beginner things but those damned PRIMARY, HASH, and FOREIGN keys that are completely eluding my understanding.

I have access to the directory of all of our tables and whatnot, but when I see a HK or a HK_FK or am asked what a PRIMARY key is I freeze up because it's like I hit a mental block.

Is there an "Explain Like I'm 5" way of describing what keys are and how they're used? It will only help me in the end if there is a way.

20 Upvotes

18 comments sorted by

13

u/r3pr0b8 18d ago

a primary key is a column in which every value is not null and unique, and can thus be used to identify each row

a foreign key is a column which may or may not be null, but if there's a value, then that value must exist in the primary key of some table (possibly its own)

3

u/Comfortable-Zone-218 17d ago

This is a good, short, clear definition. Not sure if you live in the USA, but for many US government databases they will use your SSN as the primary key as your unique identifier, as an example.

One side note. You mentioned HASH. That is not a primary or foreign key, but instead is a type of index. PKs and FKs should also be indexed. But they can be of several different types like b-tree, gin, brin, and hash.

2

u/BranchLatter4294 17d ago

Or columns...keys do not have to be a single column but usually are.

4

u/Far_Swordfish5729 18d ago

Sure. Imagine I have a list of customer accounts. As a user of that data (like a customer service application), I would really like to find a unique customer quickly. When making changes I want to make sure I’m changing the right customer and only that customer. The identifier for that customer is usually an id of some kind and in the database it will be marked as the table’s primary key. As to what it physically is, it’s usually a large number of some kind (a sequential int, possibly a guid). We don’t want to use their name because names are not unique (John Smith) and don’t want a string because they’re bigger. If the customer table came from somewhere else we don’t trust not to have duplicates, we might add our own surrogate key and make that our primary key. If the customer exists in multiple systems, they might have a unique customer id column with their common id in addition to our primary key, so we can use that id when we call other systems.

Now let’s say I have a table of orders. Each order is for a customer. To make that connection, each order will have our customer id on it. The order will have an order id as its PK (unique order number) plus its customer id. The customer id is not unique in this table. One customer may have many orders. It’s a reference to the customer row in the customer table so we can find it in a join for example. That reference is a foreign key. It will be constrained to only use existing customer ids so you won’t have orphaned orders.

Behind the scenes, each of these fields will either by used to physically sort the rows of the table (clustering) or will be part of an index used to find rows by id quickly at scale (a catalog if you will). It’s not mandatory but very common. These ids are pathways and relationships between tables used for querying and we design table schema’s to use them.

3

u/dreamoforganon 18d ago edited 18d ago

Nice explanation. Just to add about Hash Keys. As the parent post explains we don't usually use names etc as primary keys, and instead generate a 'surrogate key' for each row. The most common way is to use a sequence or GUID column, but a Hash Key is another option.

HKs apply a hash function to specified columns in a table to generate an almost-certain-to-be-unique value. This means the primary key can be determined by anything that knows the appropriate field values. In the example in the parent reply, to query for a customer's orders we need to join between the customer table and order table, because only the customer table knows the surrogate key. Let's say the surrogate primary key in the customer table was a hash of name + address. Now if we know those two bits of data we can query the user's orders directly by generating the hash and just doing 'select from orders where customer_pk = hash(name, address)'

HKs can also help in data load scenarios - imagine we re-ran an import job with the same data. If we used a sequence to generate PKs on insert we might get duplicated rows, a hash Key would generate PK violations and fail, avoiding the creation of duplicate rows.

2

u/BrupieD 18d ago

To take the ELI5 to heart, keys allow your query to find rows faster. Tables can be enormous, so where do you start? Do you scroll through every row of a multi-million row table? This is the problem to solve.

It helps if you understand how data is stored in SQL. Data is stored in 8 KB pages. Each page has multiple rows. Each page is structured to make specific rows easy to find. Tiny tables might have only one page. Giant tables might have thousands or tens of thousands of pages that each have hundreds of rows. SQL is designed to optimize throughput of pages.

So, how do you find the relevant page(s)? You need a guide. A map. Primary keys generally are based on sorting, especially numerical sorting. That's great if your query has those numbers as part of the join or in the where clause.

But what if you have different kinds of data? Say, you only care about a frequently used element like a customer code that's used in other tables? That might be a reason for building a foreign key - the customer codes are unique to the customer table (it is a primary key there) but not elsewhere. But if I need the customer name, I can only get it from the customer table.

When you need some pages from the customer table, and some pages from other tables, your keys and indexes need guides to direct them to find the right pages. I sometimes think of it as being in a giant shopping mall with a shopping list. I know some items will be in different stores.

2

u/lolcrunchy 18d ago edited 18d ago

Primary keys uniquely identify each record in a table.

When you use a table's primary key as a reference in another table, you call it a foreign key.

A table of people may have person_id as a primary key. A table of sales orders may have an order_placed_by field. If Bob with person_id 53 placed the order, 53 is in the sales record. That 53 is a foreign key in the sales table and a primary key in the people table.

1

u/DickBrainTime 18d ago edited 4d ago

A possible source of the confusion is that you're seeing two different uses of the word key in the same warehouse:

  • Primary key (PK): the identifier for one row. CUSTOMERS(customer_id=42, name='Sam'): customer_id identifies that customer.
  • Foreign key (FK): a reference to another row. ORDERS(order_id=900, customer_id=42): order_id identifies this order; customer_id points at Sam. That's why JOIN orders o ON o.customer_id = c.customer_id works.
  • HK / HK_FK: these are likely your team's column naming conventions for a hash key and a reference to one. In some warehouse/Data Vault designs, the customer identifier is derived deterministically from a business key using a hash function; the order carries the same customer hash for joins. The PK-versus-FK relationship hasn't changed. The exact input fields, normalization and algorithm are specific to your warehouse, so ask how your team calculates them rather than trying to hash a name and hope it matches.

One Snowflake-specific gotcha: on standard Snowflake tables, declared PRIMARY KEY and FOREIGN KEY constraints are generally informational, not enforced (hybrid tables are different). A column can have a PK declaration yet still contain duplicate values if your load process allows them. So think of a key as a role/relationship first, not as magic syntax that always cleans your data.

I'd pick one HK and corresponding HK_FK from your actual schema, inspect 2-3 sample rows and trace which original business key each represents. That usually makes the names click. Snowflake's constraint reference spells out the standard-versus-hybrid difference: https://docs.snowflake.com/en/sql-reference/constraints

1

u/nicopassaglia 18d ago

feel free to checkout getsheetdrill.com/sql to learn

1

u/Massive_Show2963 17d ago

Primary Key:
Also known as PK, a primary key is a special kind of entity attribute that uniquely defines a record in a database table.
A primary key uniquely identifies each record in a database table, ensuring that no two rows can have the same primary key value.
Additionally, a primary key cannot contain NULL values, which further enforces its uniquenes.
In other words, there cannot be two (or more) records that share the same value for the primary key attribute (no duplicates).

Foreign Key:
Also known as FK, a foreign key is a reference to a primary key in a table (this is the basis of relationships of an SQL database).
It is used to identify the relationships between entities.
Note that foreign keys need not be unique. Multiple records can share the same values.

I've created these tutorials that introduces these database design concepts:
Introduction To Database Design Concepts
Introduction To SQL Joins

1

u/RevolutionaryRush717 17d ago edited 17d ago

Super Key

Any set of attributes that uniquely identifies a row.

Candidate Key

A minimal super key (remove any column and uniqueness is lost).

Primary Key

The candidate key chosen as the main identifier.

Alternate Key

Candidate keys not chosen as the primary key.

Natural Key

A key with business meaning (e.g., Social Security Number, email address).

Surrogate Key

An artificial key with no business meaning (e.g., auto-increment ID, UUID).

Foreign Key

References a key in another table, enforcing referential integrity.

Composite (Compound) Key

A key consisting of multiple columns.

Unique Key

A constraint ensuring uniqueness; often implemented as a candidate key.

Secondary Key

A non-unique attribute used for retrieval/indexing (more common in older database literature).

Key Hierarchy

1 Super Key
2└─ Candidate Key
3 ├─ Primary Key
4 └─ Alternate Key

5 Natural Key
6 Surrogate Key
7 Composite Key
8 Foreign Key

1

u/Foodforbrain101 17d ago

Honestly I'm surprised no one flagged this as an indicator that you might lack broader familiarity with data modeling, and how relational database management systems are designed and work. I would include as part of that roadmap things like normalization, OLTP vs OLAP design, dimensional (Kimball-style) modeling, and more.

I think understanding more about how and why relational databases are designed to store data for an app (start simple, like a task tracker or a ticket system) vs for a data warehouse (to facilitate analytical queries) will help expedite learning and enrich your AI/google searches.

Otherwise, equally useful is roadmap.sh for data engineering and there's another one for data analysts.

Good luck!

1

u/slrworkbooks 17d ago

Primary key: a name tag. Picture a classroom where every kid wears a name tag with a number on it, and no two kids have the same number. A primary key is that number. It's the column, or sometimes a combination of columns, that identifies exactly one row in a table. In a CUSTOMERS table it's usually something like CUSTOMER_ID. It has two rules: it can't be blank, and it can't repeat. If you ever need to say "this exact row and no other," the primary key is how you do it.

Foreign key: a note pointing to someone else's name tag. Now picture a lunch-order sheet. Instead of writing out a kid's whole name, address, and teacher on every order, you just write their name-tag number. Someone can look that number up on the class roster later. That number on the order sheet is a foreign key: a column in one table that holds a primary key value from another table. ORDERS.CUSTOMER_ID is a foreign key pointing at CUSTOMERS.CUSTOMER_ID. The data lives in one place, and other tables just point to it.

This is the main thing keys do for you day to day: keys are what you join on.

SELECT c.customer_name, o.order_date, o.amount
FROM orders o
JOIN customers c
  ON o.customer_id = c.customer_id;   -- foreign key = primary key

When you're working out how to join two tables, you're really asking which column in table A holds the name-tag numbers from table B.

Hash key: a fingerprint of the name tag. Prefixes like HK_ usually mean your warehouse is built with a design pattern called Data Vault, which is common in Snowflake shops. Instead of a plain ID like CUSTOMER_ID = 48213, the warehouse runs the real identifier through a hashing function such as MD5 or SHA. That turns it into a fixed-length scrambled string like 7f3a9c.... The same input always gives the same fingerprint, so every system that loads data can compute the key independently and still match up. You never read a hash key or type one in. You only join on it. It works as a primary key; it just looks like gibberish.

HK_FK is probably a hash key used as a foreign key. I'm inferring this from the naming because it isn't a universal standard, so check your data dictionary. Most likely it means "this column holds the hash key of some other table." Same lunch-order idea, except the number written on the sheet is the fingerprint, not the plain ID. You'd join table_a.HK_CUSTOMER_FK = table_b.HK_CUSTOMER, or whatever your names are.

A Snowflake quirk that trips people up: Snowflake lets you declare primary and foreign keys but doesn't enforce them. Only NOT NULL is enforced. Snowflake won't stop a duplicate "primary key" from getting in. The declarations are documentation, not guardrails. If a join suddenly doubles your row counts, check for duplicates in the key you think is unique:

SELECT hk_customer, COUNT(*)
FROM customers
GROUP BY hk_customer
HAVING COUNT(*) > 1;

If you freeze up when you see a key column, ask yourself whether it's this table's own name tag (primary key, HK) or a pointer to another table's name tag (foreign key, HK_FK). Once you know which, you know what to join it to.

If you paste a couple of table definitions from your directory, with column names only and no data, I can walk through exactly how those keys connect.

1

u/peakpirate007 17d ago

been building https://www.runtime.school/ for learning and practicing sql in one place. lessons, practice, projects and a few tools all use the same datasets, so it feels more connected than jumping between random examples. if you’re learning sql, might be useful.

1

u/nian2326076 17d ago

A primary key is a unique identifier for each row in a table, meaning no two rows can share the same value. You can think of it like a student ID number that uniquely identifies each student. A foreign key links to the primary key of another table, which establishes relationships between different tables. If you want to strengthen your understanding, you can use PracHub to practice with relevant questions and examples that reinforce these concepts.

1

u/Discordbothost 17d ago

Snowflake caveat: standard tables don't enforce PRIMARY KEY or FOREIGN KEY constraints; hybrid tables do. Key labels alone don't guarantee clean data. https://docs.snowflake.com/en/sql-reference/constraints-overview

1

u/Puzzleheaded-Coat333 16d ago

Please feel free to correct me, if I am wrong:
Primary Key = A column of data which doesn’t change and is unique and cannot be empty or null, example : Employee ID in company table.
Foreign Key = Foreign key is a primary key on another “related” table , example: Employee social security number in company_employee_table. It helps visually to JOIN both related tables as one view.
Composite Key (DynamoDB) = It’s a combination of Primary Key + Sort Key.

1

u/m1L35dY50N 13d ago

Think of a database like a school. You have three tables:

1. Students

  • student_id (Primary Key)
  • name

2. Courses

  • course_id (Primary Key)
  • course_name

3. Enrollments

  • enrollment_id (Primary Key)
  • student_id (Foreign Key)
  • course_id (Foreign Key)
  • grade

A Primary Key (PK) uniquely identifies a row. Think of it as a student ID: two students might have the same name, but not the same ID.

A Foreign Key (FK) points to a row in another table. It's how you connect information without duplicating everything.

For example:

  • Student 1 = Alice
  • Course 10 = SQL Basics
  • Enrollment 100 = Student 1, Course 10, Grade A

That enrollment tells you Alice is taking SQL Basics and has an A.

The third table connects the other two. Alice can take multiple courses, and each course can have multiple students.

What about HASH keys?

A Hash Key (HK) is an identifier calculated from existing data using a hash function. Instead of assigning a number like 1, you generate a reproducible value from something like a student number.

HK_FK typically means a foreign key containing such a hash value. These are naming conventions often found in Data Vault architectures, not special SQL keywords.

One Snowflake-specific detail: on standard Snowflake tables, PK and FK constraints are generally informational rather than enforced.

The easiest way to remember it: PK = Who am I? FK = Who am I connected to? HK = An ID calculated from data.

(Yes - I know Picture is AI generated but Visualization sometimes help)