Create a foreign key in SQLite database browser - sqlite

Sorry for novice question.
I have created my tables using SQLite database browser, but:
I do not know how can I specify my foreign keys using the application?
How can I create a relationship diagram between tables?

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.

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

Go to edit table definition window
Click on Add field
Name it with Type : Integer
Scroll right and find Foreign Key column
Double click under Foreign Key column in new row
Select master table and its id field
Click OK
Click Write Changes

From the SQLite Documentation :
CREATE TABLE artist(
artistid INTEGER PRIMARY KEY,
artistname TEXT
);
CREATE TABLE track(
trackid INTEGER,
trackname TEXT,
trackartist INTEGER -- Must map to an artist.artistid!
);
and in the end :
CREATE TABLE track(
trackid INTEGER,
trackname TEXT,
trackartist INTEGER,
FOREIGN KEY(trackartist) REFERENCES artist(artistid)
);
In the DB Browser for SQLite Environment (v 3.8.0 - Sqlite v 3.9.2) when you add the DB fields for the track table along with
the PK ,AI and other columns you can find a Foreign Key Column.
In there , and for this example, you just add artist(artistid) in the trackartist row.
Then the foreign key constraint is created.

In DB Browser, in the Edit Table Definition window, you can double click the blank area of Foreign Key and a text box will activate. You can add your Foreign Key there.

it's really very easy , just do this
Go to edit table definition window
Right click on the table that you want to relate ( foreign table )
choose modify table
on Constraints tab select add constraints button and choose foreign key
you can relate tables here and then back to fields tab and do
Name it with Type : Integer
Scroll right and find Foreign Key column
Double click under Foreign Key column in new row
Select master table and its id field
Click OK
Click Write Changes

Triggers in SQLite3 enforces foreign key constraints. Link https://www.sqlite.org/cvstrac/wiki?p=ForeignKeyTriggers would help you out to solve your first question.

I am not sure whether this is entirely right but here's what I did:
I added the variable "UserID" in the fields tab an checked the box "primary key"
The I went to the constraints tab and added a foreign key Type constraint on the "UserID"
Then I went back to fields tab and double clicked on the foreign key field that opened and added the name of the table where that key is and the name of the variable

Related

How to get the names of foreign key constraints in SQLite?

Does SQLite indeed have a limitation that it is not possible to retrieve the name of a foreign key? I am asking because I couldn't find this limitation mentioned anywhere in their documentation.
For example, I run the following script:
CREATE TABLE
users (
id INTEGER NOT NULL PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL
) ;
CREATE TABLE
orders (
id INTEGER NOT NULL PRIMARY KEY,
user_id INTEGER NOT NULL,
CONSTRAINT fk_users FOREIGN KEY (user_id) REFERENCES users(id)
) ;
Now I would like to check that the key "fk_users" was created indeed, so I run the following PRAGMA:
PRAGMA foreign_key_list(orders);
I would expect to see the name of my foreign key in the first column, but I am seeing some "0" value instead. Moreover, if I create multiple foreign keys with custom names, they are all called either "0" or "1".
Is this indeed a limitation of SQLite, or am I missing something?
There is no mechanism to extract the constraint name.
The table sqlite_master stores a CREATE command in the column "sql". You could query that command and do some parsing to extract the name of the foreign key. An example for a combined foreign key that works for me:
SELECT sql FROM sqlite_master WHERE name = 'song'
yields
CREATE TABLE "song" (
"songid" INTEGER,
"songartist" TEXT,
"songalbum" TEXT,
"songname" TEXT,
CONSTRAINT "fk__song_album" FOREIGN KEY ("songartist", "songalbum") REFERENCES "album" ("albumartist", "albumname")
)
and contains the name "fk__song_album" of the foreign key.
If one alters the foreign key with a query, the content of the sql column is modified/updated:
The text in the sqlite_master.sql column is a copy of the original CREATE statement text that created the object, except normalized as described above and as modified by subsequent ALTER TABLE statements. The sqlite_master.sql is NULL for the internal indexes that are automatically created by UNIQUE or PRIMARY KEY constraints.
https://www.sqlite.org/fileformat2.html
Extra tip:
In order to see the foreign key information in Navicat (Lite) ... right click on a table and choose "Design table". Then select the foreign keys tab.

SQLite Syntax for Creating Table with Foreign Key

I'm creating a table with foreign key references. I'm wondering about the required syntax. Mostly I've seen the following (from http://www.sqlite.org/foreignkeys.html#fk_basics):
CREATE TABLE artist(
artistid INTEGER PRIMARY KEY,
artistname TEXT
);
CREATE TABLE track(
trackid INTEGER,
trackname TEXT,
trackartist INTEGER,
FOREIGN KEY(trackartist) REFERENCES artist(artistid)
);
However, from the same site (http://www.sqlite.org/foreignkeys.html#fk_actions) I see this:
CREATE TABLE artist(
artistid INTEGER PRIMARY KEY,
artistname TEXT
);
CREATE TABLE track(
trackid INTEGER,
trackname TEXT,
trackartist INTEGER REFERENCES artist(artistid) ON UPDATE CASCADE
);
The latter syntax is a little more concise, but I want to know if the result is somehow different (aside from the ON UPDATE CASCADE, which of course has an effect; I only included it because I copied the code exactly from the referenced site, and because I don't know that the above syntax doesn't apply only when making such a specification). I am working in Android, in case that matters.
This answer might not be related to yours but i thought it should be helpful for others who are working with android database.
IN SQLite Foreign key constraints are disabled by default (for backwards compatibility). You have to enable it explicitly using
PRAGMA foreign_keys = 1
after you establishing your connection with the database.
Here's the link to the official docs that explains it in more depth.
http://sqlite.org/foreignkeys.html
Please navigate to enabling foreign key support in the above link.
See the syntax diagrams.
The first syntax is a table constraint, while the second syntax is a column constraint.
In these examples, they behave the same.
You would need a table constraint for a key over multiple columns (where you do not have a single column you could attach it to).

Innodb foreign key constraints

I am trying to change the type in two tables of an innoDB. The problem is that the values are a key and a foreign key. When I try to make the change I get the following error
#1025 error on rename
Do I need to drop the foreign keys and then make the changes and then reapply the foreign key?
Since u can use the name to drop the foreign key first and the column then:
ALTER TABLE categories DROP FOREIGN KEY categories_ibfk_1;
ALTER TABLE categories DROP COLUMN assets_id;
To find out which table caused the error you can run
SHOW ENGINE INNODB STATUS\G
and then look at the "LATEST FOREIGN KEY ERROR" section.
Yeah, you have to drop the foreign key. Try SHOW INNODB STATUS to see if there's a more elaborated explanation of what's going on.

SQLITE: Unable to remove an unnamed primary key

I have a sqlite table that was originally created with:
PRIMARY KEY (`column`);
I now need to remove that primary key and create a new one. Creating a new one is easy, but removing the original seems to be the hard part. If I do
.indices tablename
I don't get the primary key. Some programs show the primary key as
Indexes: 1
[] PRIMARY
The index name is typically in the [].
Any ideas?
You can't.
PRAGMA INDEX_LIST('MyTable');
will give you a list of indices. This will include the automatically generated index for the primary key which will be called something like 'sqlite_autoindex_MyTable_1'.
But unfortunately you cannot drop this index...
sqlite> drop index sqlite_autoindex_MyTable_1;
SQL error: index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped
All you can do is re-create the table without the primary key.
I the database glossary; a primary-key is a type of index where the index order is typically results in the physical ordering of the raw database records. That said any database engine that allows the primary key to be changed is likely reordering the database... so most do not and the operation is up to the programmer to create a script to rename the table and create a new one. So if you want to change the PK there is no magic SQL.
select * from sqlite_master;
table|x|x|2|CREATE TABLE x (a text, b text, primary key (`a`))
index|sqlite_autoindex_x_1|x|3|
You'll see that the second row returned from my quick hack has the index name in the second column, and the table name in the third. Try seeing if that name is anything useful.

Can I alter a column in an sqlite table to AUTOINCREMENT after creation?

Can I make a field AUTOINCREMENT after made a table? For example, if you create a table like this:
create table person(id integer primary key, name text);
Then later on realise it needs to auto increment. How do I fix it, ie in MySQL you can do:
alter table person modify column id integer auto_increment
Is table creation the only opportunity to make a column AUTOINCREMENT?
You can dump the content to a new table:
CREATE TABLE failed_banks_id (id integer primary key autoincrement, name text, city text, state text, zip integer, acquired_by text, close_date date, updated_date date);
INSERT INTO failed_banks_id(name, city, state, zip, acquired_by,close_date, updated_date)
SELECT name, city, state, zip, acquired_by,close_date, updated_date
FROM failed_banks;
And rename the table:
DROP TABLE failed_banks;
ALTER TABLE failed_banks_id RENAME TO failed_banks;
Background:
The new key will be unique over all
keys currently in the table, but it
might overlap with keys that have been
previously deleted from the table. To
create keys that are unique over the
lifetime of the table, add the
AUTOINCREMENT keyword to the INTEGER
PRIMARY KEY declaration.
http://www.sqlite.org/faq.html#q1
SQLite limitations:
SQLite supports a limited subset of
ALTER TABLE. The ALTER TABLE command
in SQLite allows the user to rename a
table or to add a new column to an
existing table. It is not possible to
rename a column, remove a column, or
add or remove constraints from a
table.
http://www.sqlite.org/lang_altertable.html
Hack seems to exist:
It appears that you can set
PRAGMA writable_schema=ON;
Then do a manual UPDATE of the
sqlite_master table to insert an "id
INTEGER PRIMARY KEY" into the SQL for
the table definition. I tried it and
it seems to work. But it is
dangerous. If you mess up, you
corrupt the database file.
http://www.mail-archive.com/sqlite-users#sqlite.org/msg26987.html
From the SQLite Faq
Short answer: A column declared INTEGER PRIMARY KEY will autoincrement
So when you create the table, declare the column as INTEGER PRIMARY KEY and the column will autoincrement with each new insert.
Or you use the SQL statment ALTER to change the column type to an INTEGER PRIMARY KEY after the fact, but if your creating the tables yourself, it's best to do it in the initial creation statement.
Simplest way — Just export and re-import
It is possible, and relatively easy. Export the database as an sql file. Alter the SQL file and re-import:
sqlite3 mydata.db .dump > /tmp/backup.sql
vi /tmp/backup.sql
mv mydata.db mydata.db.old
sqlite3 mydata.db
sqlite>.read /tmp/backup.sql
You can do it with SQLite Expert Personal 4:
1) Select the table and then go to "Design" tab > "Columns" tab.
2) Click "Add" and select the new column name, and type INTEGER and Not Null > Ok.
3) Go to "Primary Key" tab in "Desgin tab". Click "Add" and select the column you just created. Check the "Autoincrement" box.
4) Click "Apply" on the right bottom part of the window.
If you go back to the "Data" tab, you will see your new column with the autogenerated numbers in it.
While the Sqlite site gives you an example how to do it with a table with only a three fields, it gets nasty with one of 30 fields. Given you have a table called OldTable with many fields, the first of which is "ID" filled with integers.
Make a copy of your database for backup.
Using the command program dot commands,
.output Oldtable.txt
.dump Oldtable
Drop Table Oldtable;
Open Oldtable.txt in Microsoft Word or a grep like text editor. Find and Replace your Integer field elements with NULL.(You may need to adjust this to fit your fields). Edit the Create Table line so the field that was defined as Integer is now INTEGER PRIMARY KEY AUTOINCREMENT.
Save as NewTable.txt
Back in the command program dot
.read NewTable.txt
Done.
ID is now autoincrement.
Yes
Do you have phpmyadmin installed? I believe if you go to the 'structure' tab and look along the right columnn (where the field types are listed) - I think you can change a setting there to make it autoincrement. There is also a SQL query that will do the same thing.
You cannot alter columns on a SQLite table after it has been created. You also cannot alter a table to add an integer primary key to it.
You have to add the integer primary key when you create the table.
Yes, you can make a column which is autoincrement. Modify the table and add a column. Keep in mind that it is of type INTEGER Primary Key.
you can alter the table, altering the column definition
Simple Answer is as below,
CREATE TABLE [TEST] (
[ID] INTEGER PRIMARY KEY AUTOINCREMENT,
[NAME] VARCHAR(100));
and you are done.

Resources