Learning MySQL - FOREIGN KEY CONSTRAINTS

Поділитися
Вставка
  • Опубліковано 1 чер 2019
  • This tutorial covers what Foreign Keys are, what Constraints are, how to create foreign keys, constraints and how to implement actions based on the constraints.
    MySQL Playlist:
    MySQL Foreign Key Constraint Reference:
    CODE SAMPLE:
    ALTER TABLE characters DROP FOREIGN KEY `fk_character_race`;
    DROP TABLE IF EXISTS races;
    DROP TABLE IF EXISTS characters;
    CREATE TABLE races (
    race_id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    race_name VARCHAR(30) NOT NULL
    )ENGINE=INNODB;
    CREATE TABLE characters(
    character_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY Key,
    character_name VARCHAR(50) NOT NULL,
    race_id TINYINT UNSIGNED NOT NULL,
    INDEX `idx_race`(race_id),
    CONSTRAINT `fk_character_race`
    FOREIGN KEY (race_id)
    REFERENCES races(race_id) ON UPDATE CASCADE ON DELETE RESTRICT
    )ENGINE=INNODB;

КОМЕНТАРІ • 73

  • @Lizini
    @Lizini Рік тому +5

    3 years later and its still useful, love these timeless education videos.
    Thank you for putting the effort and time to make these!

  • @jacksurtees8577
    @jacksurtees8577 5 років тому +18

    Gimli to Legolas: I never thought I’d end up in the same database as an elf!

  • @twotentsdown
    @twotentsdown 2 роки тому +5

    Thank you, thank you! This video helped me with several syntax errors I had. You also explained foreign key constraints in a way that finally made sense to me!

  • @ravenkavoori
    @ravenkavoori 5 років тому +1

    I've been using MySQL for a couple of years but never created foreign keys despite the advice of fellow developers because i dont have clear understanding about it until now thank you.

  • @jamesarvinrozul8293
    @jamesarvinrozul8293 4 роки тому +3

    Thanks a lot. I'm having trouble in creating relationships in MySQL and this really helped me.

  • @niek1899
    @niek1899 3 роки тому +1

    Explained the right way, easy to follow. Great video!

  • @ultimatebot900
    @ultimatebot900 2 роки тому +1

    Very good video! Been trying to figure out how to do this for a long time. Specifying on update and on delete helped me out very much!

  • @kalkalasch
    @kalkalasch 4 роки тому +1

    5:10 is when he writes the actual query to make the link between the tables. Thanks alot for the videos, they're very high quality!

  • @simplejuan
    @simplejuan 2 роки тому

    Thank you Steve! You don't know how happy I am (new to MySQL) to find your video. This is really helpful. Very clear explanation on Foreign Key! I salute you!

  • @victornwulu6095
    @victornwulu6095 8 місяців тому

    Thank you Steve, keep doing what you do!!

  • @mohammedakel520
    @mohammedakel520 4 роки тому +3

    Whether it's for school or work, Steve's videos will always save your ass👌

  • @azuredominus5739
    @azuredominus5739 3 роки тому +1

    Really well done lesson! You earned a subscriber!

  • @ignaciodamiang
    @ignaciodamiang 3 роки тому +1

    Thank you very much! from Buenos Aires, Argentina.

  • @jogarule
    @jogarule Рік тому

    Thank you so much! Great presentation and clear understanding.

  • @Rohan122
    @Rohan122 3 роки тому +2

    This is awesome!Thank you so much

  • @MonisKhan
    @MonisKhan 4 роки тому +1

    Great explanation.
    Absolutely loved it ♥️

  • @olivierkrull3074
    @olivierkrull3074 4 роки тому +2

    Very clear and understandable. Thank you

  • @SLCODEGEN
    @SLCODEGEN Рік тому

    Very bright Explanation! Thank a Lot

  • @jorgedavalos5663
    @jorgedavalos5663 2 роки тому

    thanks for the tutorial! really good

  • @ZizoAhmed
    @ZizoAhmed 3 роки тому +1

    you're great sir , you made me love it though i'm not a specialist , I just have a little job that is related to mysql

  • @madiarification
    @madiarification 3 роки тому

    Thanks! Very nice explanation!

  • @taki-eddinechih5197
    @taki-eddinechih5197 4 місяці тому

    excellent example and explanation!

  • @elmirabelo8996
    @elmirabelo8996 5 років тому +2

    Your videos are so good that one like isn't enough.

  • @JoshuaMusau
    @JoshuaMusau 3 роки тому

    This is awesome!

  • @user-fr5be6gy3u
    @user-fr5be6gy3u 2 роки тому

    Thank you.

  • @CharlesDv
    @CharlesDv 5 років тому +1

    Nice!

  • @chujekwu
    @chujekwu 4 роки тому +2

    Great job Man... Please could you make a video based on table with blob data type ?

  • @darter1990
    @darter1990 5 років тому +2

    Professor, really thank you for these tutorials.
    May I ask you one thing: "when" someone may be classified as an "expert" in SQL? These tutorials, from one to ten, how much do they say about sql skills for a job?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  5 років тому +3

      Well there will be 40 or so videos in this course. If you really understand everything that I cover then you really should be capable of doing most development work with MySQL. I would say that this is a DBA course because I'm not covering management of the database or optimization to a great degree. So I would not expect you to be an expert but competent and capable yes.

    • @darter1990
      @darter1990 5 років тому +3

      ​@@SteveGriffith-Prof3ssorSt3v3 I appreciate your answer Professor; I'm studing for becoming an etichal hacker by using open source tecnologies like Kaly Linux, and since it run a PostgreSQL DB, your course is a great boost to my studies; for now i'll use my LAMP Xubuntu for training.Thanks again.

  • @FlyMoe69
    @FlyMoe69 Рік тому

    Great video, but what if I wanted to delete Men out of the Races table? Would I have to remove all instances of Men from the Characters table first?

  • @sythous1313
    @sythous1313 2 роки тому

    You mentioned what when you have a foreign key, that you should add an index to it. What is that? And could you maybe explain what the index does? (3:32)

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  2 роки тому +1

      If you don't create the index on the foreign key it will be automatically created for you.
      Indexes are to improve search performance on tables - ua-cam.com/video/yWj320oEQEo/v-deo.html

  • @KonohaNoSai2008
    @KonohaNoSai2008 2 роки тому

    Hi, first of all, many thanks for your tutos... they are super clear !
    I've got a question:
    At minutes 8:00, when you click on the dropdown list, you've got the "id" and the "race" value.
    When I try this on my computer, i've got the "id", but, in my case I would have the "customer_name", instead i've got the "city" of my customer.
    I've checked my FK twice, and it seems to be correct.
    Any idea?
    Thanks for your help

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  2 роки тому

      If you had previous foreign keys with the same name or on the same columns then it could just be phpMyAdmin using a saved cached reference value.

    • @KonohaNoSai2008
      @KonohaNoSai2008 2 роки тому

      @@SteveGriffith-Prof3ssorSt3v3 I don't think, but I forgot to mention that I've imported the tables from an SQLite DB.
      Anyway, I will try to clear the cache.
      Thanks for your help💪🙏

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  2 роки тому +1

      @@KonohaNoSai2008 yeah. Without seeing exactly what was imported and set up it's hard for me to say.

  • @superfreiheit1
    @superfreiheit1 4 роки тому

    09:43 Is it possible to delete rows at the character table? Probably yes because their primary key does not used in other tables?

  • @user-cx5no9oi2w
    @user-cx5no9oi2w 3 роки тому

    Great video thanks so much!!! I have a question. What if say Soren killed all humans. I want it instead of preventing the delete to delete all the human entries and delete the race entry?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  3 роки тому

      You would want to use ON DELETE CASCADE as the trigger. to remove all entries where the race_id matched the value in the RACES table that you delete. Deleting the value in the RACES table is the starting point.

    • @user-cx5no9oi2w
      @user-cx5no9oi2w 3 роки тому +1

      @@SteveGriffith-Prof3ssorSt3v3 Thank you! :)

  • @Maccelerate
    @Maccelerate 5 років тому +3

    Do you sleep? Great video!

  • @yashito8150
    @yashito8150 3 роки тому

    I set up a couple of tables with foreign key constraints similar to your clip. I had already created the two tables, so I designated constraints using the Relation View. When I tried to insert or update the id field, it only shows the number ("2" instead of "2-Man" in your example). This makes inputting the data much more inefficient. Do you know how I may be able to fix this problem?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  3 роки тому

      Sounds like you are missing the index that I created on the second table, when creating my foreign key.

    • @yashito8150
      @yashito8150 3 роки тому +1

      @@SteveGriffith-Prof3ssorSt3v3 Thank you for your prompt comment. I thought I did but I may be wrong. I will try your example using SQL to see what I am doing differently.

    • @yashito8150
      @yashito8150 3 роки тому

      @@SteveGriffith-Prof3ssorSt3v3 The result was the same with SQL. I only got the number. Perhaps it is the phpMyAdmin available from the rental server. It's version is 4.4.15.8.

    • @yashito8150
      @yashito8150 3 роки тому +1

      @@SteveGriffith-Prof3ssorSt3v3 I tried the latest phpMyAdmin ver. 4.9.7 from MAMP and it worked the same way as your example. Thank you!!

  • @juanyang838
    @juanyang838 4 роки тому

    W/o any of offensives, It's really bad idea having same name 'race_id' in 2 different tables in my opinion. It makes hard to figure out which race_id is in race table or character table.

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  4 роки тому +3

      If the field is the primary key in one table and the foreign key in another then they are the same number regardless of the table. In your queries you should always include the table name or alias. It is actually a best practice to give them the same name. That way you can tell at a glance that they are related keys.
      If the fields are not related, or not the same values, then you shouldn't give them the same name.

  • @EduardoDiNapoli66
    @EduardoDiNapoli66 2 місяці тому

    Hi, great tutorial. Never used Foreign key in my web applications. Appreciate this tutorial, It's great but how make "characters.race_id" follow "races.race_id" while inserting new records in "races" table and "characters" table ? Do they must have the same "Autoincrement" value when start populating them ? Or/and...what if I make "insert" queries only into one of them ? Except for the reasonable motife to avoid the accidental corruption of data, I can't really see why "Foreign Key" must be used....Please convince me that I'm wrong. Thanks in advance.

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  2 місяці тому

      Inserting into two tables is two steps, two separate queries.
      The auto increment value is only used for a primary key. When you insert into two tables, do the one with the auto increment value first. Then that number gets used as the foreign key in the other table.
      Constraints control what happens when a foreign key value doesn't match the primary key in the related table, or if you are deleting a record whose primary key is a foreign key in another table. Do you want to delete the related records? stop the delete happening? or go ahead and let the record have a null foreign key value.
      Marking a primary key column as being a foreign key means that you are clearly explaining the relationship between two tables. Eg:
      Users
      user_id int (auto increment primary key)
      username varchar
      user_type int (foreign key here defines the connection to the UserTypes table)
      UserTypes
      type_id int (auto increment, primary key) this is used as a foreign key
      type_name varchar

    • @EduardoDiNapoli66
      @EduardoDiNapoli66 2 місяці тому

      @@SteveGriffith-Prof3ssorSt3v3 Suppose that I have
      1) "Products" table with prod_id Auto_increment, and...
      + - - - -+ - - - - - - +
      | prod_id | name |
      + - - - -+ - - - - - - +
      | 1 | prodOne |
      | 2 | prodtwo |
      + - - - -+ - - - - - - +
      2) "images" table with id_image in Auto_Increment
      + - - - - + - - - - + - - - - +
      | id_image | filename | id_prod |
      + - - - - + - - - - +- - - - +
      | 55 | one.jpg | 1 |
      | 68 | two.png | 1 |
      | 76 | tree.jpg | 2 |
      | 76 | four.jpg | 1 |
      | 76 | five.jpg | 2 |
      | 76 | six.jpg | 1 |
      | 76 | seven.jpg | 2 |
      + - - - - | - - - - | - - - - +
      What i'm suppose to do for automatically store the "prod_id" of a new product just inserted into the "id_prod" column of images table without to recour the special native functions like mysqli_insert_id($conn) or similar stuff, but with a foreign key constraint instead ?

  • @aadil4236
    @aadil4236 4 роки тому

    Does a foriegn key has to point to primary column...?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  4 роки тому

      Yes. That is what makes it a foreign key.

    • @aadil4236
      @aadil4236 4 роки тому +1

      @@SteveGriffith-Prof3ssorSt3v3 you're the best teacher ever, thanks for the answer.

  • @yinkagiwa415
    @yinkagiwa415 4 роки тому +1

    what is the use of the constraints name please?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  4 роки тому

      A constraint is a type of restriction that you are putting on the table. You are adding restrictions on what data is allowed to be added to the table (or updated or deleted) dev.mysql.com/doc/refman/5.7/en/constraints.html

    • @yinkagiwa415
      @yinkagiwa415 4 роки тому +1

      Thanks alot for the response. I understand what the constraint is for . I just don't understand why it had to be named since the name wasnt referenced anywhere else in the query .

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  4 роки тому +2

      You will almost never reference a constraint by name. It does its work behind the scenes. It is making sure that you other queries don't do things that you don't want to have happen.

    • @yinkagiwa415
      @yinkagiwa415 4 роки тому +1

      @@SteveGriffith-Prof3ssorSt3v3 Alright, i see. Thank you.

  • @rohith6313
    @rohith6313 3 роки тому

    can foreign key be null?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  3 роки тому +1

      If you allow null as a value for the column yes. But then it's not connected to the other table.

  • @AfricaTake2
    @AfricaTake2 2 роки тому

    might you have deleted the links you said you would post?

  • @V99.2
    @V99.2 2 роки тому

    Why do you need that many browsers??? 🤔🤔

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  2 роки тому +1

      As a web developer I need to be able to test features across all the platforms. Lots of browsers, different versions and I have other OS with the browsers too.

    • @V99.2
      @V99.2 2 роки тому

      @@SteveGriffith-Prof3ssorSt3v3 👌

  • @Chaosman88
    @Chaosman88 4 роки тому +1

    That example is so racist :D

  • @tahakhan88
    @tahakhan88 Рік тому

    fk_character_race ! IYKYK