Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between REFERENCES with, or without a FOREIGN KEY

In regards to SQLite, What is the difference between REFERENCES with, or without a FOREIGN KEY?

What is the difference between this

CREATE TABLE players_set ( 
    _id            INTEGER PRIMARY KEY AUTOINCREMENT
                           NOT NULL,
    player_id      INTEGER REFERENCES players ( _id ) ON DELETE CASCADE,
    players_set_id INTEGER REFERENCES players_set_names ( _id ) 
);

and this:

CREATE TABLE players_set ( 
    _id            INTEGER PRIMARY KEY AUTOINCREMENT
                           NOT NULL,
    player_id INTEGER,
    players_set_id INTEGER REFERENCES players_set_names ( _id ),
    FOREIGN KEY (player_id) REFERENCES players ( _id ) ON DELETE CASCADE        
);

I found this other question: Difference between using REFERENCES with and without FOREIGN KEY?

I read the documentation, it didn't make it clear for me though.

To be precise, I'm using SQLite on Android (hence the tag). I don't know if that makes any difference, but if it has its own quirks, it would be very useful for me to find out about.

like image 733
Konrad Morawski Avatar asked Feb 08 '14 15:02

Konrad Morawski


People also ask

What is difference between foreign key and reference?

The Reference Key is the primary key that is referenced in the other table. On the other hand, Foreign Key is how you link the second table to the primary tables Primary Key (or Reference Key).

Should I use foreign keys or not?

Yes, you should. Foreign keys are just constrains which helps you to make relationships and be sure that you have correct information in your database. You should use them to prevent incorrect data entry from whatsoever.

Is reference key foreign key?

A foreign key is a key used to link two tables together. This is sometimes also called as a referencing key. A Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table.

Can we create foreign key without reference?

Without a foreign key on D, records in E have no way of knowing, which record is referenced. D must have a primary key or unique column, every foreign key references a column that exists in another table, so E has the foreign key actually.


1 Answers

The FOREIGN KEY syntax is more flexible than defining it inline in the column definition (e.g., it allows you to define a composite foreign key, where the combination of two or more fields should exist in the referencing columns).

In your case, there is no difference between the two DDL statements. One could say that the inline definition of foreign keys is nothing more than syntactic sugaring.

like image 126
Mureinik Avatar answered Sep 20 '22 13:09

Mureinik