Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/SQL/What are primary keys and foreign keys? Why are they important?

What are primary keys and foreign keys? Why are they important?

SQLmedium2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-03-24

Primary keys (PKs) uniquely identify each record within a table, ensuring entity integrity, while foreign keys (FKs) establish and enforce relationships between tables by referencing primary keys,…

🤖 Analyze Your Answer
Frequency
Low
Asked at 2 companies
Category
487
questions in SQL
Difficulty Split
130E|271M|86H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
PresidioSwiggy
Key Concepts Tested
join

Why This Question Matters

This medium-level SQL question appears frequently in data engineering interviews at companies like Presidio, Swiggy. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (join) will help you answer variations of this question confidently.

How to Approach This

Break this problem into components. Identify the core trade-offs involved, then walk the interviewer through your reasoning step by step. Demonstrate awareness of edge cases and production considerations - this is what separates good answers from great ones. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
396 wordsIncludes code

Primary keys (PKs) uniquely identify each record within a table, ensuring entity integrity, while foreign keys (FKs) establish and enforce relationships between tables by referencing primary keys, maintaining referential integrity.

Mechanics and Importance

Primary Keys are a column or set of columns that uniquely identify each row in a table. They must be UNIQUE and NOT NULL. This absolute uniqueness is critical for data integrity, preventing duplicate records (e.g., two distinct customers sharing the same ID). PKs are often implemented with a clustered index, which physically orders the data rows on disk according to the key. This significantly improves read performance for specific lookups and range queries, reducing disk I/O, and profoundly optimizes join operations by co-locating related data. PKs are also fundamental for change data capture (CDC) and data replication, as they provide a stable, immutable identifier for tracking row-level changes across systems.

Foreign Keys are columns in one table that refer to the primary key in another table, establishing a parent-child relationship. They enforce referential integrity, meaning you cannot create "orphan" child records without a valid parent, nor delete a parent record if dependent child records exist (unless cascading actions like ON DELETE CASCADE are explicitly defined). This ensures data consistency across related tables, accurately models real-world relationships, and prevents erroneous data states.

Trade-offs and Real-world Applications

While essential for data integrity, enforcing PK and FK constraints adds overhead. In OLTP systems, enforced constraints are common to guarantee transactional consistency and prevent data corruption. However, in data warehouses or data lakes (e.g., Snowflake, Delta Lake), FKs are often logical (declared but not enforced by the database engine) to prioritize ingestion performance. Enforcing constraints during large-scale ETL/ELT operations would incur significant validation costs on INSERT/UPDATE statements, slowing down pipelines. Instead, data integrity is managed upstream through robust ETL/ELT logic, data quality checks, and tools like dbt for schema validation and testing. PKs, however, remain crucial for efficient joins and data partitioning strategies in analytical systems, directly impacting query performance (e.g., optimizing Spark shuffle operations or Snowflake micro-partition pruning).

CREATE TABLE Customers (
    customer_id INT PRIMARY KEY,
    name VARCHAR(255) NOT NULL
);

CREATE TABLE Orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);

In the interview, also mention how these concepts guide data modeling, impact query optimizers, and are crucial for data lineage and governance.

⚡
Pro Tip

Red Flag: Claiming 'we always enforce FKs in the warehouse'—often not true for batch loads. Pro-Move: 'We use logical PKs/FKs for documentation; enforce in application layer. Warehouse loads bypass FK checks for throughput.'

Want all answers as a PDF for offline study?
Seven focused volumes with 750+ in-depth answers — Answer Vault →

Related SQL Questions

mediumWrite an SQL query to find the second-highest salary from an employee table.FreemediumDemonstrate the difference between DENSE_RANK() and RANK()FreemediumDiscuss differences between ROW_NUMBER(), RANK(), and DENSE_RANK(), and provide examples from your projects.FreemediumExplain the differences between Data Warehouse, Data Lake, and Delta LakeFreemediumExplain the differences between Repartition and Coalesce. When would you use each?Free

Level up your prep

Recommended
Educative
Educative Unlimited

800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

Start learning →

Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

According to DataEngPrep.tech, this is one of the most frequently asked SQL interview questions, reported at 2 companies. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore SQL questions →
Categories
All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
By Company
AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
Interview Guides
All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
Products
AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer