How to Create A Foreign Key In SQLite Android?

8 minutes read

To create a foreign key in SQLite for Android, you need to follow these steps:

  1. First, make sure that you have a table with a primary key defined. A foreign key is used to establish a link between two tables, where the primary key of one table serves as a foreign key in another.
  2. To create a foreign key, you need to modify the table structure using SQL statements. You can do this by using the ALTER TABLE statement.
  3. Use the following syntax to create a foreign key: ALTER TABLE tableName ADD CONSTRAINT fkName FOREIGN KEY (columnName) REFERENCES referencedTableName(referencedColumnName); tableName: The name of the table where the foreign key is being added. fkName: The name you assign to the foreign key constraint. It should be unique within the table. columnName: The name of the column in the current table that will be the foreign key. referencedTableName: The name of the table that the foreign key references. referencedColumnName: The name of the column in the referenced table that is referenced by the foreign key.
  4. Execute the SQL statement using the execSQL() method on the SQLite database object.


Here's an example of creating a foreign key to link two tables named Students and Courses. Let's say we want to link the courseId column in the Students table to the ID column in the Courses table:

1
2
3
4
5
6
7
String sql = "ALTER TABLE Students " +
             "ADD CONSTRAINT fk_Students_Courses " +
             "FOREIGN KEY (courseId) " +
             "REFERENCES Courses(ID);";
             
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.execSQL(sql);


By executing the above code, you're creating a foreign key constraint named fk_Students_Courses in the Students table, linking the courseId column to the ID column in the Courses table.

Best SQLite Books to Read in 2024

1
The Definitive Guide to SQLite (Expert's Voice in Open Source)

Rating is 5 out of 5

The Definitive Guide to SQLite (Expert's Voice in Open Source)

2
The Definitive Guide to SQLite

Rating is 4.9 out of 5

The Definitive Guide to SQLite

3
Using SQLite: Small. Fast. Reliable. Choose Any Three.

Rating is 4.8 out of 5

Using SQLite: Small. Fast. Reliable. Choose Any Three.

4
Creating SQL Queries Using SQLite Made Easy (SQL Series)

Rating is 4.7 out of 5

Creating SQL Queries Using SQLite Made Easy (SQL Series)

5
SQLite For Beginners: Learn Fundamentals of Queries and Implement PyQt-Based Projects Easily

Rating is 4.6 out of 5

SQLite For Beginners: Learn Fundamentals of Queries and Implement PyQt-Based Projects Easily

6
SQL Pocket Guide: A Guide to SQL Usage

Rating is 4.5 out of 5

SQL Pocket Guide: A Guide to SQL Usage


How do you specify cascading actions for foreign key constraints in SQLite?

In SQLite, you can specify cascading actions for foreign key constraints using the ON DELETE and ON UPDATE clauses. These clauses allow you to define what actions should be taken when a referenced row is deleted or updated.


Here are the available options for cascading actions:

  1. CASCADE: If a referenced row is deleted or updated, all rows that have a foreign key referencing the deleted/updated row will also be deleted/updated.
  2. SET NULL: If a referenced row is deleted or updated, the foreign key value in all rows that reference the deleted/updated row will be set to NULL.
  3. SET DEFAULT: If a referenced row is deleted or updated, the foreign key value in all rows that reference the deleted/updated row will be set to their default value specified during table creation.
  4. RESTRICT: Prevents the deletion or update of a referenced row if there are any rows that reference it.


To specify cascading actions for foreign key constraints when creating a table in SQLite, you can use the following syntax:

1
2
3
4
5
6
7
CREATE TABLE table_name (
    column_name data_type,
    ...
    FOREIGN KEY (foreign_key_column_name) REFERENCES referenced_table_name(referenced_column_name)
        ON DELETE action
        ON UPDATE action
);


Replace table_name with the name of the table you are creating, column_name with the name of the column containing the foreign key, foreign_key_column_name with the name of the foreign key column, referenced_table_name with the name of the referenced table, referenced_column_name with the name of the referenced column, and action with the desired cascading action.


For example, to cascade the deletion of a referenced row and also update the foreign key value in other rows when a referenced row is updated, you can use the following syntax:

1
2
3
4
5
6
7
8
CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY,
    customer_id INTEGER,
    order_date TEXT,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);


In this example, when a customer is deleted or updated, all corresponding orders with the matching customer_id will also be deleted or updated accordingly.


Can a foreign key have a different name than the referenced column in SQLite?

Yes, a foreign key in SQLite can have a different name than the referenced column. In SQLite, the foreign key constraint is defined in the CREATE TABLE statement using the FOREIGN KEY clause, where you can specify the name of the foreign key constraint along with the referenced column.


Here is an example of how you can specify a foreign key constraint with a different name than the referenced column in SQLite:

1
2
3
4
5
CREATE TABLE table1 (
    id INTEGER PRIMARY KEY,
    column1 INTEGER,
    FOREIGN KEY (column1) REFERENCES table2(referenced_column) -- foreign key constraint with name different than referenced column
);


In the above example, the foreign key constraint is defined on "column1" of "table1" and it references "referenced_column" of "table2". The foreign key constraint has a different name than the referenced column.


Can a foreign key reference a primary key column from a different database table in SQLite?

No, in SQLite, a foreign key can only reference a primary key column from another table within the same database. It cannot reference a primary key column from a different database table.


Can you create a foreign key constraint on a virtual table in SQLite?

No, you cannot create a foreign key constraint on a virtual table in SQLite. SQLite only supports foreign key constraints on regular (non-virtual) tables.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To add a foreign key in SQLite, you need to follow these steps:Ensure you are using SQLite version 3.6.19 or higher, as foreign key support was added in this version. Create the main table (referred to as the parent table) using the CREATE TABLE statement. Def...
Adding a primary key in SQLite involves using the SQLite CREATE TABLE statement. Here's how you can add a primary key in SQLite:Open your SQLite database using a SQLite client or command-line tool. Create a new table or alter an existing table using the CR...
To open an encrypted SQLite database file, follow these steps:Download and install an SQLite database management tool like DB Browser for SQLite or SQLiteStudio.Launch the SQLite database management tool.Locate the encrypted SQLite database file on your comput...