SQL / SQL Data Definition

Using Primary and Foreign Keys

This tutorial will guide you through the use of primary and foreign keys in SQL. These keys are essential for creating relationships between tables in a database.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers creating, modifying, and deleting database structures.

1. Introduction

Goal of the Tutorial

In this tutorial, we will explore how to use primary and foreign keys in SQL. These keys are fundamental for establishing relationships between tables in a database, ensuring data integrity and enabling efficient data lookup.

Learning Outcomes

By the end of this tutorial, you will be able to:
- Understand what primary keys and foreign keys are in SQL
- Create tables with primary keys and foreign keys
- Use these keys to associate records across tables

Prerequisites

You should have a basic understanding of SQL and how to create tables and insert data into them.

2. Step-by-Step Guide

Primary Keys

A primary key is a column or a set of columns that uniquely identifies each row in a table. It must contain unique values and cannot contain NULL values.

Here's how you create a table with a primary key:

CREATE TABLE Customers (
    ID int NOT NULL,
    Name varchar(255) NOT NULL,
    PRIMARY KEY (ID)
);

In this example, 'ID' is the primary key for the 'Customers' table.

Foreign Keys

A foreign key is a column or a set of columns used to establish a link between the data in two tables. The foreign key in one table points to the primary key in another table.

Here's how you create a table with a foreign key:

CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    CustomerID int,
    PRIMARY KEY (OrderID),
    FOREIGN KEY (CustomerID) REFERENCES Customers(ID)
);

In this example, 'CustomerID' is the foreign key that links the 'Orders' table to the 'Customers' table.

3. Code Examples

Example 1: Creating Tables with Primary and Foreign Keys

-- Create the 'Customers' table with 'ID' as the primary key
CREATE TABLE Customers (
    ID int NOT NULL,
    Name varchar(255) NOT NULL,
    PRIMARY KEY (ID)
);

-- Create the 'Orders' table with 'OrderID' as the primary key and 'CustomerID' as the foreign key
CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    CustomerID int,
    PRIMARY KEY (OrderID),
    FOREIGN KEY (CustomerID) REFERENCES Customers(ID)
);

Example 2: Inserting Data Into Tables

-- Insert data into the 'Customers' table
INSERT INTO Customers (ID, Name) VALUES (1, 'John Doe');

-- Insert data into the 'Orders' table
INSERT INTO Orders (OrderID, OrderNumber, CustomerID) VALUES (1, 12345, 1);

4. Summary

In this tutorial, you've learned about primary and foreign keys in SQL. You've seen how to create tables with these keys and how to use them to associate data across tables. Continue practicing to get more comfortable with these concepts.

5. Practice Exercises

Exercise 1

Create a 'Products' table with 'ProductID' as the primary key and a 'Sales' table with 'SaleID' as the primary key and 'ProductID' as the foreign key.

Exercise 2

Insert data into the 'Products' and 'Sales' tables.

Solutions

-- Solution for Exercise 1
CREATE TABLE Products (
    ProductID int NOT NULL,
    ProductName varchar(255) NOT NULL,
    PRIMARY KEY (ProductID)
);

CREATE TABLE Sales (
    SaleID int NOT NULL,
    SaleAmount decimal NOT NULL,
    ProductID int,
    PRIMARY KEY (SaleID),
    FOREIGN KEY (ProductID) REFERENCES Products(ProductID)
);

-- Solution for Exercise 2
INSERT INTO Products (ProductID, ProductName) VALUES (1, 'Product 1');
INSERT INTO Sales (SaleID, SaleAmount, ProductID) VALUES (1, 100.00, 1);

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help