CREATE TABLE Customers (
CustomerId INT PRIMARY KEY,
Name VARCHAR(100)
);
Topics
43
Aggregate Functions & GROUP BY
Always On Availability Groups
Backup & Recovery
Change Data Capture (CDC)
Columnstore Indexes
Common Table Expressions (CTEs)
Constraints (Primary Key, Foreign Key, Check & Unique)
Cursors
Data Types & Schema Design
Deadlocks
Dynamic Data Masking
Dynamic SQL
Error Handling with TRY CATCH
Full Text Search
Hash Indexes & Hash Join Operations
Indexes
In-Memory OLTP (Memory-Optimized Tables)
Isolation & Locking
Joins
JSON Support in SQL Server
Linked Servers
Merge Statement (Upsert)
Normalization
Partitioning
Pivoting & Unpivoting Data
Query Optimization & Plans
Query Store
Replication
SQL Server Agent & Job Scheduling
SQL Server Architecture & Editions
SQL Server Profiler & Extended Events
SQL Server Security & Permissions
Stored Procedures & Functions
Subqueries
Temporary Tables & Table Variables
Transactions & ACID
Transparent Data Encryption
Triggers
T-SQL Fundamentals & Syntax
User Defined Functions
Views
Window Functions
XML Data Type & Querying
Constraints (Primary Key, Foreign Key, Check & Unique)
7 questions found
A primary key constraint uniquely identifies each row in a table, ensuring no two rows can have the same value in that column, and it also automatically prevents that column from containing NULL values, making it the reliable way other tables can reference a specific row.
Real-world example
An online store uses CustomerId as the primary key for its customers table, guaranteeing that every customer record can always be uniquely identified and referenced by other tables like orders.
Data Types & Schema Design;Normalization
What is a foreign key constraint, and how does it help maintain data integrity between two related tables?
BeginnerA foreign key constraint links a column in one table to the primary key of another table, ensuring that any value entered in that column must already exist in the referenced table, which prevents situations like an order being created for a customer id that does not actually exist.
CREATE TABLE Orders (
OrderId INT PRIMARY KEY,
CustomerId INT,
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)
);
Real-world example
An order management system uses a foreign key to guarantee every order is linked to a valid, existing customer, preventing orphaned orders that reference customers who were never actually added to the system.
Normalization;Joins
What is a check constraint, and how do you use one to enforce a specific business rule at the database level?
IntermediateA check constraint defines a condition that every value in a column, or combination of columns, must satisfy before a row can be inserted or updated, letting you enforce business rules like requiring a price to always be positive directly in the database, rather than relying solely on application code to catch invalid data.
CREATE TABLE Products (
ProductId INT PRIMARY KEY,
Price DECIMAL(10,2) CHECK (Price > 0)
);
Real-world example
A product catalog enforces that every product's price must always be greater than zero directly at the database level, preventing accidental negative pricing even if a bug exists somewhere in the application code.
Data Types & Schema Design;Error Handling with TRY CATCH
How is a unique constraint different from a primary key constraint, and when would you use one instead of the other?
IntermediateA unique constraint, like a primary key, ensures every value in a column is distinct, but unlike a primary key it does allow a single NULL value and a table can have multiple unique constraints, making it useful for enforcing uniqueness on columns like an email address that are not the table's main identifying key.
CREATE TABLE Customers (
CustomerId INT PRIMARY KEY,
Email VARCHAR(255) UNIQUE
);
Real-world example
A customer database uses a unique constraint on the email column to prevent duplicate customer accounts from being created with the same email address, while still using CustomerId as the actual primary key.
Data Types & Schema Design;Indexes
How do cascading actions work with foreign key constraints, such as ON DELETE CASCADE, and what risks come with using them?
AdvancedCascading actions automatically apply a related change to child rows when the parent row is modified or deleted, such as automatically deleting all of a customer's orders when that customer is deleted, which can be convenient but also risky, since a single delete statement could unexpectedly remove far more data than intended if not carefully planned.
CREATE TABLE Orders (
OrderId INT PRIMARY KEY,
CustomerId INT,
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId) ON DELETE CASCADE
);
Real-world example
A team enables ON DELETE CASCADE between customers and orders so that removing a test customer account automatically cleans up all of their related test orders without requiring several separate delete statements.
Normalization;Transactions & ACID
How would you add a new constraint to an existing table that already contains data, especially if some existing rows might violate that constraint?
AdvancedYou first identify and fix any existing data that would violate the new constraint, then add the constraint using an ALTER TABLE statement, optionally using WITH NOCHECK if you need to add it without validating existing data immediately, though this leaves the constraint untrusted until it is explicitly checked later.
-- First, identify violating rows
SELECT * FROM Products WHERE Price <= 0;
-- Then add the constraint after cleaning up the data
ALTER TABLE Products
ADD CONSTRAINT CK_Price CHECK (Price > 0);
Real-world example
A team cleans up a handful of products with incorrect zero dollar prices before successfully adding a check constraint that prevents this type of pricing error from happening again in the future.
Data Types & Schema Design;Error Handling with TRY CATCH
How do you temporarily disable a constraint to perform a bulk data load, and how do you safely re-enable it afterward?
IntermediateYou use ALTER TABLE with the NOCHECK CONSTRAINT option to temporarily disable a specific constraint, perform your bulk data operation, and then re-enable it using CHECK CONSTRAINT, ideally with the WITH CHECK option to also validate that all the newly loaded data actually satisfies the constraint.
ALTER TABLE Orders NOCHECK CONSTRAINT FK_Orders_Customers;
-- Perform bulk insert here
ALTER TABLE Orders WITH CHECK CHECK CONSTRAINT FK_Orders_Customers;
Real-world example
A data migration team temporarily disables a foreign key constraint to quickly bulk load historical order data, then re-enables and validates the constraint afterward to confirm all the loaded data is actually consistent.
Query Optimization & Plans;Data Types & Schema Design