SQL FOREIGN KEY

Dive into the world of SQL FOREIGN KEY and enhance your understanding of this crucial element in database management. This comprehensive guide will walk you through various aspects of SQL FOREIGN KEY concepts and their implementation in databases, along with practical examples and best practices for utilising them in your queries. Begin by learning the basics, such as differentiating between primary key and SQL FOREIGN KEY, then move on to mastering the art of implementing FOREIGN KEY constraints in your database tables. Finally, explore how to effectively use SQL FOREIGN KEY in your queries to optimise data retrieval and maximise productivity. Embrace the power of SQL FOREIGN KEY and elevate your skills in database management.

Get started

Millions of flashcards designed to help you ace your studies

Sign up for free

Achieve better grades quicker with Premium

PREMIUM
Karteikarten Spaced Repetition Lernsets AI-Tools Probeklausuren Lernplan Erklärungen Karteikarten Spaced Repetition Lernsets AI-Tools Probeklausuren Lernplan Erklärungen
Kostenlos testen

Geld-zurück-Garantie, wenn du durch die Prüfung fällst

Review generated flashcards

Sign up for free
You have reached the daily AI limit

Start learning or create your own AI flashcards

StudySmarter Editorial Team

Team SQL FOREIGN KEY Teachers

  • 14 minutes reading time
  • Checked by StudySmarter Editorial Team
Save Article Save Article
Contents
Contents

Jump to a key chapter

    SQL FOREIGN KEY Explained

    SQL stands for Structured Query Language, which is a standardized language used for managing relational database systems. An essential part of designing and building a relational database is specifying constraints to ensure the data integrity. One of these constraints is the FOREIGN KEY.

    A FOREIGN KEY is a column (or a set of columns) in a table that is used to establish a link between two or more tables in a relational database. These keys help maintain data consistency and integrity by enforcing referential integrity between the tables.

    When a FOREIGN KEY constraint is created, it ensures that the values entered into the referencing table must exist in the referenced table. In simpler terms, it prevents invalid data from being inserted into the FOREIGN KEY column(s) of a table that has no corresponding value in the primary key column of the referenced table.

    Referential Integrity is a concept wherein the relationships between tables in a database must always remain consistent. That is, when using FOREIGN KEYs, any modification to the data within the tables must not lead to any data inaccuracies or inconsistencies.

    There are four types of actions that can be specified with FOREIGN KEY constraints when data is modified:

    • NO ACTION: This is the default action. It prevents the modification if it would violate the referential integrity.
    • CASCADE: If the primary key reference is deleted or updated, CASCADE will automatically delete or update the rows in the referencing table.
    • SET NULL: If the primary key reference is deleted or updated, SET NULL will set the FOREIGN KEY value to NULL in the referencing table.
    • SET DEFAULT: If the primary key reference is deleted or updated, SET DEFAULT will set the FOREIGN KEY value to its default value in the referencing table.

    Primary Key vs SQL FOREIGN KEY

    In relational databases, Primary Key and FOREIGN KEY concepts play a crucial role in defining the structure and relationships between tables. Understanding the difference between the two will help you efficiently design and manage your database.

    Primary KeyFOREIGN KEY
    Unique identifier for each row in a table.Column(s) in a table used to establish a link between two or more tables.
    Each table can have only one primary key.A table can have multiple FOREIGN KEYs, each referencing a different table.
    Enforces data integrity within a single table.Enforces referential integrity between related tables.
    Cannot contain NULL values.Can contain NULL values unless additional constraints are specified.

    To sum up, a Primary Key is a unique identifier for rows within a table, whereas a FOREIGN KEY is used to reference values in another table, maintaining consistency and data integrity between related tables. Both Primary Key and FOREIGN KEY constraints are essential tools to ensure the coherent organization of your database as you engage in query operations, updates, and modifications.

    Implementing SQL FOREIGN KEY in Databases and Tables

    Adding a FOREIGN KEY to your tables in a database is an essential step during the creation and maintenance of a relational database. Establishing these relationships between tables ensures referential integrity and prevents invalid data from being entered in your database. There are two primary methods to add a FOREIGN KEY to your tables: during table creation or after table creation.

    Adding FOREIGN KEY During Table Creation:

    If you're creating a new table and wish to add a FOREIGN KEY immediately, you can use the CREATE TABLE statement and specify the FOREIGN KEY constraint along with any other required columns. Here's an example:

    CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT, order_date DATE, FOREIGN KEY (customer_id) REFERENCES customers(customer_id) );

    In the example above, the 'customer_id' column in the 'orders' table refers to the 'customer_id' column in the 'customers' table, enforcing referential integrity. It means that any 'customer_id' value entered in the 'orders' table must exist in the 'customers' table.

    Adding FOREIGN KEY After Table Creation:

    If you have an existing table and want to add a FOREIGN KEY, you can use the ALTER TABLE statement combined with the ADD CONSTRAINT clause. Here's an example:

    ALTER TABLE orders ADD CONSTRAINT fk_customer_id FOREIGN KEY (customer_id) REFERENCES customers(customer_id);

    In this example, the FOREIGN KEY constraint named 'fk_customer_id' is added to the 'orders' table. The 'customer_id' column in the 'orders' table refers to the 'customer_id' column in the 'customers' table, ensuring referential integrity between the tables.

    Optional Foreign Key SQL

    When creating FOREIGN KEY constraints, you have the option to specify additional actions to be taken when data modification occurs in referenced tables. These optional actions are sometimes necessary, depending on your database design and requirements. In this section, we will discuss the following FOREIGN KEY optional actions:

    • ON DELETE
    • ON UPDATE
    • Hybrid ON DELETE and ON UPDATE

    Please recall the four types of actions you can specify when creating FOREIGN KEY constraints from our previously discussed referential actions: NO ACTION, CASCADE, SET NULL, and SET DEFAULT.

    Using ON DELETE:

    This allows you to define the referential action that will occur when a DELETE operation is performed on rows in the referenced table. Here's an example:

    CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT, order_date DATE, FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE CASCADE );

    The example demonstrates the use of the ON DELETE CASCADE action. It means that if any row in the 'customers' table is deleted, all corresponding rows in the 'orders' table with the affected 'customer_id' values will be automatically deleted to maintain referential integrity.

    Using ON UPDATE:

    This allows you to define the referential action that will occur when an UPDATE operation is performed on rows in the referenced table. Here's an example:

    CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT, order_date DATE, FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON UPDATE CASCADE );

    The example demonstrates the use of the ON UPDATE CASCADE action. If any row in the 'customers' table has a change in its 'customer_id' column value, all corresponding rows in the 'orders' table will be updated with the new value to preserve referential integrity.

    Hybrid ON DELETE and ON UPDATE:

    You can combine ON DELETE and ON UPDATE actions to handle both situations simultaneously. Here's an example:

    CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT, order_date DATE, FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE SET NULL ON UPDATE CASCADE );

    In this example, if a row in the 'customers' table is deleted, corresponding rows in the 'orders' table will have their 'customer_id' set to NULL. Meanwhile, if a 'customer_id' value is updated in the 'customers' table, the corresponding rows in the 'orders' table will be updated with the new value, thus preserving referential integrity.

    SQL Add Multiple Foreign Keys Efficiently

    When creating tables with multiple FOREIGN KEYs, it is essential to define the constraints efficiently to avoid complications and reduce workload during subsequent updates or modifications. There are two primary ways to add multiple FOREIGN KEY constraints to your table:

    Adding Multiple FOREIGN KEYs during table creation:

    You can define multiple FOREIGN KEY constraints while creating a table by including the constraints in the CREATE TABLE statement. Here's an example:

    CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT, product_id INT, order_date DATE, FOREIGN KEY (customer_id) REFERENCES customers(customer_id), FOREIGN KEY (product_id) REFERENCES products(product_id) );

    In the example above, we have added two FOREIGN KEY constraints to the 'orders' table: 'customer_id' references the 'customer_id' column in the 'customers' table, and 'product_id' references the 'product_id' column in the 'products' table.

    Adding Multiple FOREIGN KEYs after table creation:

    If you have an existing table and want to add multiple FOREIGN KEY constraints, you can use the ALTER TABLE statement in combination with multiple ADD CONSTRAINT clauses. Here's an example:

    ALTER TABLE orders ADD CONSTRAINT fk_customer_id FOREIGN KEY (customer_id) REFERENCES customers(customer_id), ADD CONSTRAINT fk_product_id FOREIGN KEY (product_id) REFERENCES products(product_id);

    As shown in the example, we have added two FOREIGN KEY constraints to the 'orders' table using the ALTER TABLE statement. The constraints named 'fk_customer_id' and 'fk_product_id' reference the 'customer_id' column in the 'customers' table and the 'product_id' column in the 'products' table, respectively.

    Adding multiple FOREIGN KEY constraints efficiently can help maintain referential integrity and optimize database operations for better performance. By following the principles outlined in this section, you can create robust and scalable relational databases to meet your data management needs.

    Using SQL FOREIGN KEY in Queries

    SQL FOREIGN KEYs play a crucial role in query operations, enabling you to establish relationships between tables and retrieve data efficiently. In this section, we will explore the various ways FOREIGN KEYs can be used in SQL queries, including data retrieval and combining with other SQL commands.

    SQL Query Using Foreign Key for Data Retrieval

    When you need to retrieve data from multiple related tables, FOREIGN KEYs enable you to perform JOIN operations to combine the results into a single result set seamlessly. The most common type of JOIN operation is INNER JOIN, but there are other types, such as LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN.

    INNER JOIN:

    INNER JOIN returns rows from both tables when there is a match between the values in the FOREIGN KEY column(s) of one table and the primary key or unique column(s) of another table. Let's illustrate this with an example:

    SELECT customers.customer_name, orders.order_date FROM customers INNER JOIN orders ON customers.customer_id = orders.customer_id;

    In the above example, we retrieve 'customer_name' from the 'customers' table and 'order_date' from the 'orders' table. The INNER JOIN is performed using the 'customer_id' FOREIGN KEY in the 'orders' table that references the 'customer_id' primary key in the 'customers' table. Only the rows with matching 'customer_id' values in both tables are returned in the result set.

    LEFT JOIN:

    LEFT JOIN (or LEFT OUTER JOIN) returns all rows from the left table (the table that appears first in the query) and the matched rows from the right table (the table that appears later in the query). If no match is found, NULL values are returned for the right table's columns. Here's an example:

    SELECT customers.customer_name, orders.order_date FROM customers LEFT JOIN orders ON customers.customer_id = orders.customer_id;

    In this case, all rows from the 'customers' table are displayed, and whenever a match is found in the 'orders' table based on the 'customer_id', the 'order_date' column is also displayed. If there's no corresponding 'order_date' value, NULL is displayed for that row.

    RIGHT JOIN and FULL OUTER JOIN:

    While RIGHT JOIN (or RIGHT OUTER JOIN) returns all rows from the right table and the matched rows from the left table, FULL OUTER JOIN returns all rows when there is a match in either the left or right table. In both cases, NULL values are displayed for the unmatched rows' columns.

    However, it's worth noting that some relational databases, such as MySQL, do not support RIGHT JOIN and FULL OUTER JOIN. In such cases, you can use LEFT JOIN and additional SQL commands to achieve similar results.

    Combining SQL FOREIGN KEY with Other SQL Commands

    FOREIGN KEYs can be used in combination with other SQL commands to efficiently perform various operations on your database. Below, we will explore some key SQL commands that can be used in conjunction with FOREIGN KEYs:

    WHERE Clause:

    You can use the WHERE clause along with FOREIGN KEYs to filter the results based on specific conditions. Here's an example:

    SELECT customers.customer_name, orders.order_date FROM customers INNER JOIN orders ON customers.customer_id = orders.customer_id WHERE orders.order_date > '2021-01-01';

    In this example, we apply the WHERE clause to filter the results to display only orders placed after '2021-01-01'.

    GROUP BY Clause:

    The GROUP BY clause can be used with FOREIGN KEYs to create aggregated results and group them based on shared attributes between tables. For example:

    SELECT customers.customer_name, COUNT(orders.order_id) AS total_orders FROM customers INNER JOIN orders ON customers.customer_id = orders.customer_id GROUP BY customers.customer_id;

    This query fetches the total number of orders for each customer by grouping the result set according to the 'customer_id' attribute.

    ORDER BY Clause:

    You can use the ORDER BY clause with FOREIGN KEYs to sort the query results based on specific columns from related tables. Let's see an example:

    SELECT customers.customer_name, orders.order_date FROM customers INNER JOIN orders ON customers.customer_id = orders.customer_id ORDER BY orders.order_date DESC;

    In this example, the query results are sorted in descending order according to the 'order_date' column from the 'orders' table.

    When working with complex queries and multiple related tables, combining SQL FOREIGN KEYs with various SQL commands allows you to optimize your data retrieval and manipulation while maintaining data integrity and consistency within your relational database.

    SQL FOREIGN KEY - Key takeaways

    • SQL FOREIGN KEY: A column or set of columns in a table used to establish a link between two or more tables in a relational database to enforce referential integrity.

    • Primary Key vs SQL FOREIGN KEY: Primary keys uniquely identify rows within a single table, while FOREIGN KEYs reference values in other tables, maintaining consistency, and data integrity between related tables.

    • SQL Add Foreign Key: FOREIGN KEY constraints can be added during table creation using CREATE TABLE statements or after table creation using ALTER TABLE statements with ADD CONSTRAINT clauses.

    • Optional Foreign Key SQL: ON DELETE and ON UPDATE actions can be specified when creating FOREIGN KEYs, allowing additional actions like CASCADE, SET NULL, or SET DEFAULT to be taken during data modifications.

    • SQL Query Using Foreign Key: FOREIGN KEYs can be used in SQL queries to perform JOIN operations, retrieve data efficiently, and combine results from multiple related tables.

    Frequently Asked Questions about SQL FOREIGN KEY
    What is a foreign key in SQL?
    A foreign key in SQL is a column or a set of columns in a table that establishes a connection between two tables by referencing the primary key in another table. It ensures that the data in one table corresponds to a valid record in the linked table, maintaining referential integrity and enforcing rules for data consistency across multiple tables.
    How can I add a foreign key in SQL?
    To add a foreign key in SQL, use the ALTER TABLE statement followed by the ADD CONSTRAINT clause. Specify the foreign key constraint's name and reference the foreign key column with REFERENCES keyword, followed by the referenced primary key table and its column. For example: ```sql ALTER TABLE child_table ADD CONSTRAINT fk_name FOREIGN KEY (foreign_key_column) REFERENCES parent_table (primary_key_column); ```
    How can one assign a foreign key in SQL?
    To assign a foreign key in SQL, you need to use the ALTER TABLE statement, referencing the column in the table and specifying the foreign key constraint. Here's a basic example: ```sql ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY (column_name) REFERENCES reference_table(reference_column); ``` Remember to replace table_name, constraint_name, column_name, reference_table, and reference_column with your actual table and column names.
    How can I check the foreign key constraint in SQL?
    To check foreign key constraints in SQL, you can query the database information schema. Use the following SELECT statement: ``` SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME IS NOT NULL; ``` This query will return a list of all foreign key constraints along with their column names, constraint names, and the referenced table and column names.
    How can I connect two tables in SQL using a foreign key?
    To connect two tables in SQL using a foreign key, you first create a primary key in the parent table, and then create a foreign key in the child table that references the primary key in the parent table. This is done using a CREATE TABLE or ALTER TABLE statement, ensuring the data types match in both columns, such as: ``` CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT, FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ); ```
    Save Article

    Test your knowledge with multiple choice flashcards

    What is a FOREIGN KEY in SQL?

    What is the purpose of using a WHERE clause with FOREIGN KEYs?

    What statement and clause can be used to add a FOREIGN KEY constraint to an existing table?

    Next

    Discover learning materials with the free StudySmarter app

    Sign up for free
    1
    About StudySmarter

    StudySmarter is a globally recognized educational technology company, offering a holistic learning platform designed for students of all ages and educational levels. Our platform provides learning support for a wide range of subjects, including STEM, Social Sciences, and Languages and also helps students to successfully master various tests and exams worldwide, such as GCSE, A Level, SAT, ACT, Abitur, and more. We offer an extensive library of learning materials, including interactive flashcards, comprehensive textbook solutions, and detailed explanations. The cutting-edge technology and tools we provide help students create their own learning materials. StudySmarter’s content is not only expert-verified but also regularly updated to ensure accuracy and relevance.

    Learn more
    StudySmarter Editorial Team

    Team Computer Science Teachers

    • 14 minutes reading time
    • Checked by StudySmarter Editorial Team
    Save Explanation Save Explanation

    Study anywhere. Anytime.Across all devices.

    Sign-up for free

    Sign up to highlight and take notes. It’s 100% free.

    Join over 22 million students in learning with our StudySmarter App

    The first learning app that truly has everything you need to ace your exams in one place

    • Flashcards & Quizzes
    • AI Study Assistant
    • Study Planner
    • Mock-Exams
    • Smart Note-Taking
    Join over 22 million students in learning with our StudySmarter App
    Sign up with Email