Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a foreign key in SQLite database browser

Tags:

sqlite

Sorry for novice question.

I have created my tables using SQLite database browser, but:

  1. I do not know how can I specify my foreign keys using the application?

  2. How can I create a relationship diagram between tables?

like image 757
Jeff Avatar asked May 14 '13 07:05

Jeff


People also ask

Does SQLite have foreign keys?

What is a Foreign Key in SQLite? A foreign key is a way to enforce referential integrity within your SQLite database. A foreign key means that values in one table must also appear in another table. The referenced table is called the parent table while the table with the foreign key is called the child table.

How do I create a database in DB Browser SQLite?

To create a new database using DB Browser, simply click New Database to create a database for your data, give the database an appropriate name, and put it in the folder that you're using for your work on the project. You are then able to import data, create tables or indices as required.


2 Answers

I know this question has been asked long ago but I found it. Its built right into GUI. You just need to drag and make those Name, Type tabs little bit small to make space for the Foreign Key tab. Place your mouse pointer at the end and drag the header.

My version of SQLite Browser is Version 3.7.0.

enter image description here

like image 75
Chintan Desai Avatar answered Sep 21 '22 11:09

Chintan Desai


I couldn't find a way of defining foreign key constraints using the "Database Structure" tab. I'd strongly recommend defining table definitions and constraints using a script rather than building them using the graphical editor - it makes it much easier to create new databases and to track changes to the schema.

By way of an example, assume we have two tables: one defining file names and one specifying the method used for compression, we can add a foreign key constraint to the file_definition table when defining it.

CREATE TABLE [compression_state] (     [compression_state_id] INTEGER  PRIMARY KEY NOT NULL,     [value] TEXT  NOT NULL );  CREATE TABLE [file_definition] (     [file_id] INTEGER  NOT NULL  PRIMARY KEY AUTOINCREMENT,     [compression_state_id] INTEGER  NOT NULL,     [name] TEXT NOT NULL,     FOREIGN KEY(compression_state_id) REFERENCES compression_state(compression_state_id) ); 

However, by default, SQLite will not enforce the constraint, therefore every time you connect to the database, you must issue the following command to enable constraint checking.

PRAGMA foreign_keys = ON; 

Further details in the documentation.

If the tables already exist and you don't want to build a complete script then you're out of luck, SQLite doesn't support adding foreign keys once the table has been generated, see here: SQL Features That SQLite Does Not Implement

like image 33
phil_rawlings Avatar answered Sep 21 '22 11:09

phil_rawlings