Author: alien

  • Khóa học miễn phí MySQL – After Insert Trigger nhận dự án làm có lương

    MySQL – After Insert Trigger



    A Trigger is simply defined as a response to an event. In MySQL, a trigger is a special stored procedure that resides in the system catalogue, that is executed whenever an event is performed. These events include SQL statements like INSERT, UPDATE and DELETE etc.

    It is called a special stored procedure as it does not require to be invoked explicitly like other stored procedures. The trigger acts automatically whenever the desired event is fired.

    MySQL After Insert Trigger

    The After Insert Trigger is a row-level trigger supported by the MySQL database. As its name suggests, the After Insert Trigger is executed right after a value is inserted into a database table.

    A row-level trigger is a type of trigger that goes off every time a row is modified. Simply, for every single transaction made in a table (like insertion, deletion, update), one trigger acts automatically.

    To elaborate, whenever an INSERT statement is executed in the database, the value is inserted into the table first followed by the trigger execution. Hence, one cannot update a newly inserted row using the AFTER INSERT trigger.

    Syntax

    Following is the syntax to create the AFTER INSERT trigger in MySQL −

    CREATE TRIGGER trigger_name
    AFTER INSERT ON table_name FOR EACH ROW
    BEGIN
       -- trigger body
    END;
    

    Example

    Let us see an example demonstrating the AFTER INSERT trigger. In here, we are creating a new table named USERS, which contains the details of users of an application, using the following query −

    CREATE TABLE USERS(
       ID INT AUTO_INCREMENT,
       NAME VARCHAR(100) NOT NULL,
       AGE INT NOT NULL,
       BIRTH_DATE VARCHAR(100),
       PRIMARY KEY(ID)
    );
    

    Now, let us create another table ”PUSH_NOTIFICATIONS” that is used to store messages to send as push notifications to the users on their birthdays −

    CREATE TABLE PUSH_NOTIFICATIONS(
       ID INT AUTO_INCREMENT,
       BIRTH_DATE VARCHAR(100),
       NOTIFICATIONS VARCHAR(255) NOT NULL,
       PRIMARY KEY(ID)
    );
    

    Using the following CREATE TRIGGER statement, create a new trigger after_trigger on the USERS table to insert values into the PUSH_NOTIFICATIONS table −

    DELIMITER //
    CREATE TRIGGER after_trigger AFTER INSERT ON USERS FOR EACH ROW
    BEGIN
       IF NEW.BIRTH_DATE IS NOT NULL THEN
       INSERT INTO PUSH_NOTIFICATIONS VALUES
       (new.ID, new.BIRTH_DATE, CONCAT(''Happy Birthday, '', NEW.NAME, ''!''));
    END IF;
    END //
    DELIMITER ;
    

    Insert values into the USERS table using the regular INSERT statement as shown below −

    INSERT INTO USERS (NAME, AGE, BIRTH_DATE) VALUES
    (''Sasha'', 23, ''24/06/1999'');
    (''Alex'', 21, ''12/01/2001'');
    

    Verification

    To verify if the trigger has been executed, display the PUSH_NOTIFICATIONS table using the SELECT statement −

    ID BIRTH_DATE NOTIFICATIONS
    1 24/06/1999 Happy Birthday, Sasha!
    2 12/01/2001 Happy Birthday, Alex!

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Drop Trigger nhận dự án làm có lương

    MySQL – DROP TRIGGER

    Table of content


    Triggers in MySQL are stored programs similar to procedures. These can be created on a table, schema, view and database that are associated with an event and whenever an event occurs the respective trigger is invoked.

    Triggers are, in fact, written to be executed in response to any of the following events −

    • A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
    • A database definition (DDL) statement (CREATE, ALTER, or DROP).
    • A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).

    You can delete a trigger using the DROP TRIGGER Statement.

    Dropping Trigger in MySQL

    The DROP TRIGGER statement in MySQL will drop a trigger from a database, and all its information.

    Syntax

    Following is the syntax of the MySQL DELETE TRIGGER Statement.

    DROP TRIGGER [IF EXISTS] trigger_name
    

    Where, trigger_name is the name of the trigger you need to delete.

    Example

    Assume we have created a table with name student as shown below −

    CREATE TABLE STUDENT(
       Name varchar(35),
       Age INT,
       Score INT
    );
    

    Following query creates a trigger named sample_trigger on this table. This trigger will set the score value 0 if you enter a value that is less than 0 as score.

    DELIMITER //
    CREATE TRIGGER sample_trigger
    BEFORE INSERT ON STUDENT
    FOR EACH ROW
    BEGIN
       IF NEW.score < 0 THEN SET NEW.score = 0;
    END IF;
    END //
    DELIMITER ;
    

    Now, let us use the following query to drop the trigger we created in the previous step −

    DROP TRIGGER sample_trigger;
    

    Verification

    To verify if the trigger has been dropped, let us display the trigger information using the following query −

    SHOW TRIGGERSG
    

    Since have deleted the trigger created, we get an empty set −

    Empty set (0.11 sec)
    

    With IF EXISTS clause

    If you try to drop a trigger that doesn”t exist an error will be generated as shown below −

    DROP TRIGGER demo;
    

    Following is the output −

    ERROR 1360 (HY000): Trigger does not exist
    

    If you use the IF EXISTS clause along with the DROP TRIGEGR statement as shown below, the specified trigger will be dropped and if a trigger with the given name, doesn”t exist the query will be ignored.

    DROP TRIGGER IF EXISTS demo;
    

    Dropping Trigger Using a Client Program

    In addition to create or show a trigger, we can also drop a trigger using a client program.

    Syntax

    To drop a trigger through a PHP program, we need to execute the DROP TRIGGER statement using the mysqli function query() as follows −

    $sql = "Drop TRIGGER testTrigger";
    $mysqli->query($sql);
    

    To drop a trigger through a JavaScript program, we need to execute the DROP TRIGGER statement using the query() function of mysql2 library as follows −

    sql = "DROP TRIGGER testTrigger";
    con.query(sql);
    

    To drop a trigger through a Java program, we need to execute the DROP TRIGGER statement using the JDBC function execute() as follows −

    String sql = "DROP TRIGGER sample_trigger";
    statement.execute(sql);
    

    To drop a trigger through a python program, we need to execute the DROP TRIGGER statement using the execute() function of the MySQL Connector/Python as follows −

    drop_trigger_query = "DROP TRIGGER sample_trigger"
    cursorObj.execute(drop_trigger_query)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $db = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
    if($mysqli->connect_errno ) {
       printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
    ''); $sql = "DROP TRIGGER testTrigger"; if($mysqli->query($sql)){ printf("Trigger dropped successfully...!"); } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Trigger dropped successfully...!
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
    host:"localhost",
    user:"root",
    password:"password"
    });
    
     //Connecting to MySQL
     con.connect(function(err) {
     if (err) throw err;
      //console.log("Connected successfully...!");
      //console.log("--------------------------");
     sql = "USE TUTORIALS";
     con.query(sql);
     sql = "DROP TRIGGER testTrigger";
     con.query(sql);
     console.log("Drop trigger query executed successfully..!");
     console.log("Triggers: ");
     sql = "SHOW TRIGGERS";
     con.query(sql, function(err, result){
     if (err) throw err;
     console.log(result);
     });
    });
    

    Output

    The output produced is as follows −

    Drop trigger query executed successfully..!
    Triggers:
    []
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class DropTrigger {
       public static void main(String[] args) {
          String url = "jdbc:mysql://localhost:3306/TUTORIALS";
          String user = "root";
          String password = "password";
          ResultSet rs;
          try {
             Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, user, password);
                Statement st = con.createStatement();
                //System.out.println("Database connected successfully...!");
                String sql = "DROP TRIGGER sample_trigger";
                st.execute(sql);
                System.out.print("Triggerd dropped successfully...!");
          }catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    Output

    The output obtained is as shown below −

       Triggerd dropped successfully...!
    
    import mysql.connector
    # Establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    table_name = ''Student''
    trigger_name = ''sample_trigger''
    # Creating a cursor object
    cursorObj = connection.cursor()
    # drop trigger
    drop_trigger_query = "DROP TRIGGER sample_trigger"
    cursorObj.execute(drop_trigger_query)
    print("Trigger is dropped successfully")
    connection.commit()
    # close the cursor and connection
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Trigger is dropped successfully
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Show Trigger nhận dự án làm có lương

    MySQL – SHOW TRIGGERS

    Table of content


    Triggers in MySQL are stored programs similar to procedures. These can be created on a table, schema, view and database that are associated with an event and whenever an event occurs the respective trigger is invoked.

    MySQL provides a statement to list out all the existing triggers present in a database. Knowing the trigger information can be useful while creating new triggers, so that a user wouldn”t use the same name for multiple triggers.

    Show Triggers in MySQL

    The SHOW TRIGGERS Statement is used in MySQL to display information about all the triggers defined in the current database.

    Syntax

    Following is the syntax of the MySQL SHOW TRIGGERS Statement −

    SHOW TRIGGERS
    [{FROM | IN} db_name]
    [LIKE ''pattern'' | WHERE expr]
    

    Example

    In this example, we are creating a table named STUDENT using the query below −

    CREATE TABLE STUDENT(
       Name varchar(35),
       Age INT,
       Score INT
    );
    

    Following query creates a trigger sample_trigger which will set the score value to 0 if you enter a negative score value into the table.

    DELIMITER //
    CREATE TRIGGER sample_trigger
    BEFORE INSERT ON STUDENT
    FOR EACH ROW
    BEGIN
     IF NEW.score < 0 THEN SET NEW.score = 0;
    END IF;
    END //
    DELIMITER ;
    

    Assume we have created another trigger using the AFTER clause −

    DELIMITER //
    CREATE TRIGGER testTrigger
    AFTER UPDATE ON Student
    FOR EACH ROW
    BEGIN
     INSERT INTO Student
     SET action = ''update'',
     Name = OLD.Name,
     Age = OLD.age,
     Score = OLD.score;
    END;
    END //
    
    DELIMITER ;
    

    Following query shows the existing triggers in the current database −

    SHOW TRIGGERS G;
    

    Output

    The list of triggers will be displayed as follows −

    *************************** 1. row ***************************
    Trigger: sample_trigger
    Event: INSERT
    Table: student
    Statement: BEGIN
               IF NEW.score < 0 THEN SET NEW.score = 0;
               END IF;
               END
    Timing: BEFORE
    Created: 2021-05-12 19:08:04.50
    sql_mode: STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
    Definer: root@localhost
    character_set_client: utf8mb4
    collation_connection: utf8mb4_0900_ai_ci
      Database Collation: utf8mb4_0900_ai_ci
    *************************** 2. row ***************************
    Trigger: testTrigger
    Event: UPDATE
    Table: student
    Statement: INSERT INTO Student
               SET Name = OLD.Name,
                   Age = OLD.age,
                   Score = OLD.score
    Timing: AFTER
    Created: 2021-05-12 19:10:44.49
    sql_mode: STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
    Definer: root@localhost
    character_set_client: utf8mb4
    collation_connection: utf8mb4_0900_ai_ci
    Database Collation: utf8mb4_0900_ai_ci
    2 rows in set (0.00 sec)
    

    With FROM or IN Clause

    You can retrieve the information of triggers from a specific database using the FROM clause.

    Example

    Assume that the current database is named demo. Following query shows the triggers present in the database demo

    SHOW TRIGGERS FROM demoG
    

    You can also use the IN clause instead of FROM, to get the same output.

    SHOW TRIGGERS IN demoG
    

    Output

    The existing triggers present in the demo database −

    *************************** 1. row ***************************
                 Trigger: sample_trigger
                   Event: INSERT
                   Table: student
               Statement: BEGIN
     IF NEW.score < 0 THEN SET NEW.score = 0;
    END IF;
    END
                  Timing: BEFORE
                 Created: 2023-09-29 11:42:33.58
                sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
                 Definer: root@localhost
    character_set_client: cp850
    collation_connection: cp850_general_ci
      Database Collation: utf8mb4_0900_ai_ci
    *************************** 2. row ***************************
                 Trigger: testTrigger
                   Event: UPDATE
                   Table: student
               Statement: BEGIN
     INSERT INTO Student
     SET action = ''update'',
     Name = OLD.Name,
     Age = OLD.age,
     Score = OLD.score;
    END
                  Timing: AFTER
                 Created: 2023-09-29 11:43:10.27
                sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
                 Definer: root@localhost
    character_set_client: cp850
    collation_connection: cp850_general_ci
      Database Collation: utf8mb4_0900_ai_ci
    2 rows in set (0.00 sec)
    

    With WHERE Clause

    You can use the WHERE clause of the SHOW TRIGGERS statements to retrieve info about the triggers which match the specified condition.

    Example

    Following query retrieves the triggers in the current database whose event is update −

    SHOW TRIGGERS FROM demo WHERE Event = ''UPDATE'' G;
    

    Output

    The required list of triggers is displayed as follows −

    *************************** 1. row ***************************
                 Trigger: testTrigger
                   Event: UPDATE
                   Table: student
               Statement: BEGIN
     INSERT INTO Student
     SET action = ''update'',
     Name = OLD.Name,
     Age = OLD.age,
     Score = OLD.score;
    END
                  Timing: AFTER
                 Created: 2023-09-29 11:43:10.27
                sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
                 Definer: root@localhost
    character_set_client: cp850
    collation_connection: cp850_general_ci
      Database Collation: utf8mb4_0900_ai_ci
    1 row in set (0.00 sec)
    

    Showing Trigger Using Client Program

    We can also Show a trigger using a client program.

    Syntax

    To show a trigger through a PHP program, we need to execute the SHOW TRIGGERS statement using the mysqli function query() as follows −

    $sql = "Show TRIGGER";
    $mysqli->query($sql);
    

    To show a trigger through a JavaScript program, we need to execute the SHOW TRIGGERS statement using the query() function of mysql2 library as follows −

    sql = "Show TRIGGER";
    con.query(sql);
    

    To show a trigger through a Java program, we need to execute the SHOW TRIGGERS statement using the JDBC function executeQuery() as follows −

    String sql = "Show TRIGGER";
    statement.executeQuery(sql);
    

    To show a trigger through a python program, we need to execute the SHOW TRIGGERS statement using the execute() function of the MySQL Connector/Python as follows −

    Show_trigger_query = ''SHOW TRIGGER''
    cursorObj.execute(Show_trigger_query)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $db = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } printf(''Connected successfully.
    ''); // Create a trigger $sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score"; if ($mysqli->query($sql)) { printf("Trigger created successfully...!
    "); } else { printf("Trigger creation failed: %s
    ", $mysqli->error); } // Show created trigger details $sql = "SHOW TRIGGERS"; $res = $mysqli->query($sql); if ($res) { while ($row = $res->fetch_assoc()) { // Print trigger details foreach ($row as $key => $value) { printf("%s: %s
    ", $key, $value); } printf("
    "); } $res->free(); } else { printf("Failed to retrieve triggers: %s
    ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Connected successfully.
    Trigger created successfully...!
    Trigger: testTrigger
    Event: UPDATE
    Table: student
    Statement: INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score
    Timing: AFTER
    Created: 2023-09-08 12:16:27.54
    sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
    Definer: root@localhost
    character_set_client: utf8mb4
    collation_connection: utf8mb4_0900_ai_ci
    Database Collation: utf8mb4_0900_ai_ci
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
    host:"localhost",
    user:"root",
    password:"password"
    });
    
     //Connecting to MySQL
     con.connect(function(err) {
     if (err) throw err;
      //console.log("Connected successfully...!");
      //console.log("--------------------------");
     sql = "USE TUTORIALS";
     con.query(sql);
     sql = "SHOW TRIGGERS";
     con.query(sql);
     console.log("show trigger query executed successfully..!");
     console.log("Triggers: ");
     sql = "SHOW TRIGGERS";
     con.query(sql, function(err, result){
     if (err) throw err;
     console.log(result);
     });
    });
    

    Output

    The output produced is as follows −

    show trigger query executed successfully..!
    Triggers:
    [
      {
        Trigger: ''testTrigger'',
        Event: ''UPDATE'',
        Table: ''student'',
        Statement: "INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score",
        Timing: ''AFTER'',
        Created: 2023-08-01T05:21:18.540Z,
        sql_mode: ''IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION'',
        Definer: ''root@localhost'',
        character_set_client: ''utf8mb4'',
        collation_connection: ''utf8mb4_unicode_ci'',
        ''Database Collation'': ''utf8mb4_0900_ai_ci''
      }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class ShowTrigger {
       public static void main(String[] args) {
          String url = "jdbc:mysql://localhost:3306/TUTORIALS";
          String user = "root";
          String password = "password";
          ResultSet rs;
          try {
             Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, user, password);
                Statement st = con.createStatement();
                //System.out.println("Database connected successfully...!");
                String sql = "Create Trigger sample_trigger BEFORE INSERT ON student FOR EACH ROW BEGIN IF NEW.score < 0 THEN SET NEW.score = 0; END IF; END";
                st.execute(sql);
                System.out.println("Trigger created successfully...!");
                String sql1 = "SHOW TRIGGERS";
                rs = st.executeQuery(sql1);
                System.out.println("Triggers: ");
                while(rs.next())
                {
                   String triggers = rs.getNString(1);
                   System.out.println(triggers);
                }
    
          }catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Trigger created successfully...!
    Triggers:
    sample_trigger
    testTrigger
    
    import mysql.connector
    # Establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    table_name = ''Student''
    trigger_name = ''sample_trigger''
    # Creating a cursor object
    cursorObj = connection.cursor()
    # show trigger
    show_triggers_query = "SHOW TRIGGERS"
    cursorObj.execute(show_triggers_query)
    result = cursorObj.fetchall()
    print("Triggers in the database:")
    for row in result:
        print(row)
    # close the cursor and connection
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Triggers in the database:
    (''sample_trigger'', ''INSERT'', ''student'', b''BEGINn    IF NEW.Score < 0 THENn        SET NEW.Score = 0;n    END IF;nEND'', ''BEFORE'', datetime.datetime(2023, 7, 31, 11, 38, 5, 880000), {''STRICT_TRANS_TABLES'', ''NO_ENGINE_SUBSTITUTION''}, ''root@localhost'', ''utf8mb4'', ''utf8mb4_0900_ai_ci'', ''utf8mb4_0900_ai_ci'')
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Triggers nhận dự án làm có lương

    MySQL – Triggers

    Table of content


    Generally, a Trigger is defined as a response to an event. In MySQL, a trigger is a special stored procedure that resides in the system catalogue, that is executed automatically (without being called explicitly like regular stored procedures) whenever an event is performed. These events include statements like INSERT, UPDATE and DELETE etc.

    To run a MySQL trigger, the user must have admin/superuser privileges.

    As per the SQL standard, triggers are usually divided into two categories −

    • Row-level Trigger: Triggers that are only executed when each row is either inserted, updated or deleted in a database table. MySQL only supports these type of triggers.

    • Statement-level Trigger: Triggers like these are executed on the transaction level, once, no matter how many rows are modified in a table. MySQL does not support these trype of triggers.

    Types of Triggers in MySQL

    There are six types of row-level triggers in MySQL. They are:

    • Before Insert Trigger

    • After Insert Trigger

    • Before Update Trigger

    • After Update Trigger

    • Before Delete Trigger

    • After Delete Trigger

    Before Insert Trigger

    The Before Insert Trigger is performed before any value is inserted into the table. Whenever an INSERT statement is executed, the Before Insert trigger goes off, followed by the insertion transaction.

    After Insert Trigger

    The After Insert Trigger works opposite to the Before Insert Trigger. As implied by its name, it is performed after any value is inserted into the table. Whenever an INSERT statement is executed, the value is inserted into the table first followed by the execution of the trigger.

    Before Update Trigger

    The Before Update Trigger is performed before any value is updated or modified in the table. Whenever an UPDATE statement is executed, the Before Update trigger goes off, followed by the update transaction.

    After Update Trigger

    The After Update Trigger works opposite to the Before Update Trigger. As implied by its name, it is performed after any value is updated in the table. Whenever an UPDATE statement is executed, the value is updated in the table first followed by the execution of the trigger.

    Before Delete Trigger

    The Before Delete Trigger is performed before any value is deleted from the table. Whenever a DELETE statement is executed, the Before Delete trigger goes off, followed by the deletion transaction.

    After Delete Trigger

    The After Delete Trigger works opposite to the Before Delete Trigger. As implied by its name, it is performed after any value is deleted from the table. Whenever an DELETE statement is executed, the value is deleted from the table first followed by the execution of the trigger.

    Advantages of Triggers

    Triggers hold a lot of advantages in MySQL database. They are listed as follows −

    • Triggers help the database to maintain the integrity of the data stored.

    • Triggers are also a means to handle errors from the database layer itself.

    • As triggers are invoked automatically without being called explicitly, you don”t have to wait for the scheduled events to run.

    • Triggers can be useful to track the data changes made in the tables, by logging the events.

    • MySQL Triggers can also prevent invalid transactions from being executed.

    Disadvantages of Triggers

    However, there are disadvantages of using triggers in a MySQL database. Some of them are listed as follows −

    • Triggers cannot replace all validations, and only provide extended validations. For simple validations, you can use the NOT NULL, UNIQUE, CHECK and FOREIGN KEY constraints.

    • As triggers are invisible to the client application, it is impossible to understand what goes on in the database layer. Hence, making it difficult to troubleshoot.

    • Triggers are not beneficial for use with high-velocity data i.e. the data when a number of events per second are high.

    • Triggers may increase the overhead of the MySQL Server.

    Restrictions on Triggers

    Following are some of the restrictions that apply to MySQL triggers −

    • One trigger for each event − Each table can have only one trigger for each event combination, i.e. you can”t define two same triggers for the same table.

    • RETURN statement is not permitted − As triggers don”t return any values, the RETURN statement is not permitted.

    • Foreign key restriction − Triggers are not activated by foreign key actions.

    • Outdated metadata − Suppose, if a trigger is loaded into cache, it is not automatically reloaded when the table metadata changes. In this case, a trigger can operate using outdated metadata.

    • Cannot use ”CALL” statement − We cannot use the CALL statement in triggers.

    • Cannot create a TEMPORARY table or a view − We cannot create a view for a temporary table or a view.

    • Not activated by changes in INFORMATION_SCHEMA − Actually, triggers are not activated by changes made in INFORMATION_SCHEMA or performance_schema tables. It is because these tables are views and triggers are not permitted on views.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Create Trigger nhận dự án làm có lương

    MySQL – CREATE TRIGGER

    Table of content


    Triggers are generally defined as responses to an event. For instance, when we hover a mouse-pointer on a drop-down menu of a website, a various set of options to navigate through this website are then displayed. Here, the hovering of the mouse-pointer is an event while the display of options in the drop-down menu is a result of trigger execution. This concept is also introduced in MySQL.

    Triggers in MySQL are stored programs similar to procedures. These can be created on a table, schema, view and database that are associated with an event and whenever an event occurs the respective trigger is invoked.

    Triggers are, in fact, written to be executed in response to any of the following events −

    • A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
    • A database definition (DDL) statement (CREATE, ALTER, or DROP).
    • A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).

    Creating Trigger in MySQL

    You can create a trigger using the CREATE TRIGGER Statement.

    Syntax

    Following is the syntax of the MySQL CREATE TRIGGER Statement.

    CREATE TRIGGER trigger_name
    trigger_time trigger_event
    ON table_name FOR EACH ROW
    BEGIN
    ...
    END;
    

    Where,

    • trigger_name is the name of the trigger you need to create
    • trigger_time is the time of trigger activation
    • trigger_event can be INSERT, UPDATE, or DELETE. This event causes the trigger to be invoked.
    • table_name is the name of the table to which the trigger is associated with.

    Example

    Assume we have created a table with name student as shown below −

    CREATE TABLE STUDENT(
       Name varchar(35),
       Age INT,
       Score INT
    );
    

    Following query creates a trigger, this will set the score value 0 if you enter a value that is less than 0 as score.

    DELIMITER //
    CREATE TRIGGER sample_trigger BEFORE INSERT ON STUDENT FOR EACH ROW
    BEGIN
    IF NEW.Score < 0 THEN SET NEW.Score = 0;
    END IF;
    END //
    DELIMITER ;
    

    Verification

    If you try to insert records in the student table and if you use a value that is less than 0 as age it will be automatically set to 0.

    INSERT INTO STUDENT VALUES
    (''Jeevan'', 22, 8),
    (''Raghav'', 26, -3),
    (''Pooja'', 21, -9),
    (''Devi'', 30, 9);
    

    The STUDENT table created will have the following records −

    Name Age Score
    Jeevan 22 8
    Raghav 26 0
    Pooja 21 0
    Devi 30 9

    As we can see, there are no negative values inserted in the table as they are all replaced with zeroes.

    Creating Trigger Using a Client Program

    We can also Create a trigger using a client program.

    Syntax

    To Create a Trigger through a PHP program, we need to execute the CREATE statement using the mysqli function named query() as follows −

    $sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score";
    $mysqli->query($sql);
    

    To Create a Trigger through a JavaScript program, we need to execute the CREATE statement using the query() function of mysql2 library as follows −

    sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score"
    con.query(sql);
    

    To Create a Trigger through a Java program, we need to execute the CREATE statement using the JDBC function execute() as follows −

    String sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score";
    statement.execute(sql);
    

    To Create a Trigger through a python program, we need to execute the CREATE statement using the execute() function of the MySQL Connector/Python as follows −

    create_trigger_query = ''CREATE TRIGGER sample_trigger
    BEFORE INSERT ON students
    FOR EACH ROW
    BEGIN
       IF NEW.Score < 0 THEN
          SET NEW.Score = 0;
       END IF;
    END''
    cursorObj.execute(create_trigger_query)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $db = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
    if($mysqli->connect_errno ) {
       printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
    ''); $sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score"; if($mysqli->query($sql)){ printf("Trigger created successfully...!"); } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Trigger created successfully...!
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
       host:"localhost",
       user:"root",
       password:"password"
    });
    
    //Connecting to MySQL
    con.connect(function(err) {
       if (err) throw err;
       //console.log("Connected successfully...!");
       //console.log("--------------------------");
       sql = "USE TUTORIALS";
       con.query(sql);
       sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score"
       con.query(sql);
       console.log("Trigger created successfully....!");
       sql = "SHOW TRIGGERS";
       con.query(sql, function(err, result){
          if (err) throw err;
          console.log(result);
       });
    });
    

    Output

    The output produced is as follows −

    Trigger created successfully....!
    [
      {
        Trigger: ''testTrigger'',
        Event: ''UPDATE'',
        Table: ''student'',
        Statement: "INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score",
        Timing: ''AFTER'',
        Created: 2023-08-01T05:21:18.540Z,
        sql_mode: ''IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION'',
        Definer: ''root@localhost'',
        character_set_client: ''utf8mb4'',
        collation_connection: ''utf8mb4_unicode_ci'',
        ''Database Collation'': ''utf8mb4_0900_ai_ci''
      }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class CreateTrigger {
       public static void main(String[] args) {
          String url = "jdbc:mysql://localhost:3306/TUTORIALS";
          String user = "root";
          String password = "password";
          ResultSet rs;
          try {
             Class.forName("com.mysql.cj.jdbc.Driver");
             Connection con = DriverManager.getConnection(url, user, password);
             Statement st = con.createStatement();
             //System.out.println("Database connected successfully...!");
             String sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score";
             st.execute(sql);
             System.out.print("Trigger created successfully....!");
    
          }catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Trigger created successfully....!
    
    import mysql.connector
    #Establishing the connection
    connection = mysql.connector.connect(
       host=''localhost'',
       user=''root'',
       password=''password'',
       database=''tut''
    )
    table_name = ''Student''
    trigger_name = ''sample_trigger''
    # Creating a cursor object
    cursorObj = connection.cursor()
    # Create table
    create_table_query = ''''''
    CREATE TABLE Student(
       Name VARCHAR(35),
       age INT,
       Score INT
    )
    ''''''
    cursorObj.execute(create_table_query)
    print("The table is created successfully!")
    # Creating a trigger
    create_trigger_query = f''''''CREATE TRIGGER {trigger_name}
    BEFORE INSERT ON {table_name}
    FOR EACH ROW
    BEGIN
       IF NEW.Score < 0 THEN
          SET NEW.Score = 0;
       END IF;
    END''''''
    cursorObj.execute(create_trigger_query)
    print(f"Trigger ''{trigger_name}'' is created successfully.")
    # Commit the changes and close the cursor and connection
    connection.commit()
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    The table is created successfully!
    Trigger ''sample_trigger'' is created successfully.
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Composite Key nhận dự án làm có lương

    MySQL – Composite Key

    Table of content


    A MySQL Composite Key is a key that consists of two or more columns in a table, used to uniquely identify a record (combination of values in the same table row). It can also be described as a Primary Key created on multiple columns.

    With composite key on multiple columns of a table, a combination of these columns guarantees uniqueness, even though individually these columns may or may not guarantee uniqueness. Therefore, when the database table doesn”t have any column which is individually capable of identifying a unique row (or a record) from the table, then we might need two or more two fields/columns to get a unique record/row from the table.

    Creating MySQL Composite Key

    To create a composite key in a MySQL table, we create a primary key on two or more columns of a table using the PRIMARY KEY keyword in the CREATE TABLE statement. The composite key must have the following features −

    • A Composite Key may or may not be a part of the Foreign key.
    • A Composite Key can not be NULL.
    • A Composite Key also can be created by combining more than one Candidate Key.
    • It is also known as Compound key.
    • All the attributes in a compound keys are foreign keys.

    Syntax

    Following is the syntax to create a Composite Key while creating a table −

    CREATE TABLE table_name(
       column1 datatype, column2 datatype, column3 datatype...,
       CONSTRAINT composite_key_name
       PRIMARY KEY(column_name1, column_name2,..)
    );
    

    Example

    In the following example, we are trying to create a table named CUSTOMERS and add a composite key on ID and NAME columns as shown −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY(ID, NAME)
    );
    

    PRIMARY KEY is added to both ID and NAME columns in the CUSTOMERS table. The combination of values inserted into these columns must be unique, even if the individual column values has duplicates.

    Verification

    To verify if a composite key is created or not, let us display the table definition of a CUSTOMERS table using the DESC query −

    Field Type Null Key Default Extra
    ID int NO PRI NULL
    NAME varchar(20) NO PRI NULL
    AGE int NO NULL
    ADDRESS char(25) YES NULL
    SALARY decimal(18, 2) YES NULL

    Dropping MySQL Composite Key

    We can drop the MySQL Composite Key by using the ALTER TABLE… DROP statement.

    Syntax

    Following is the syntax to drop the Composite key from the column of a table −

    ALTER TABLE table_name DROP PRIMARY KEY;
    

    Example

    Using the following SQL statement, we can drop the Composite key constraint from the table −

    ALTER TABLE CUSTOMERS DROP PRIMARY KEY;
    

    Verification

    To verify if the Composite Key has been dropped or not, we display the CUSTOMERS table using the DESC keyword −

    Field Type Null Key Default Extra
    ID int NO NULL
    NAME varchar(20) NO NULL
    AGE int NO NULL
    ADDRESS char(25) YES NULL
    SALARY decimal(18, 2) YES NULL

    Composite Key Using a Client Program

    We can also apply a Composite Key constraint on Fields to uniquely identified using a client program.

    Syntax

    To apply a Composite key on fields through a PHP program, we need to execute the “Create/Alter” statement using the mysqli function query() as follows −

    $sql = ''ALTER TABLE customers ADD PRIMARY KEY(cust_Id, cust_Name)
    $mysqli->query($sql);
    

    To apply a Composite key on fields through a JavaScript program, we need to execute the “Create/Alter” statement using the query() function of mysql2 library as follows −

    sql = `CREATE TABLE employee(ID Int NOT NULL, emp_Id INT NOT NULL, emp_Name varchar(25), PRIMARY KEY(ID, emp_Id))`;
    con.query(sql);
    

    To apply a Composite key on fields through a Java program, we need to execute the “Create/Alter” statement using the JDBC function execute() as follows −

    String sql = "Alter TABLE customers ADD PRIMARY KEY(cust_Id, cust_Name)";
    statement.execute(sql);
    

    To apply a Composite key on fields through a python program, we need to execute the “Create/Alter” statement using the execute() function of the MySQL Connector/Python as follows −

    composite_key_query = ''CREATE TABLE TEST(ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, MOBILE BIGINT, CONSTRAINT CK_TEST PRIMARY KEY (ID, MOBILE))''
    cursorObj.execute(composite_key_query)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $dbname = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } // printf(''Connected successfully.
    ''); //creating composite key using alter statement. $sql = ''ALTER TABLE customers ADD PRIMARY KEY(cust_Id, cust_Name) if ($mysqli->query($sql)) { echo "composite key column created successfully in customers table n"; } if ($mysqli->errno) { printf("Table could not be created!.
    ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    composite key column created successfully in customers table
    
    var mysql = require("mysql2");
    var con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "password",
    }); //Connecting to MySQL
    
    con.connect(function (err) {
      if (err) throw err;
      //   console.log("Connected successfully...!");
      //   console.log("--------------------------");
      sql = "USE TUTORIALS";
      con.query(sql);
    
      //creating a composite key column during the table creation...!
      sql = `CREATE TABLE employee(ID Int NOT NULL, emp_Id INT NOT NULL, emp_Name varchar(25), PRIMARY KEY(ID, emp_Id))`;
      con.query(sql);
    
      //describe table details
      sql = "DESCRIBE TABLE employee";
      con.query(sql, function (err, result) {
        if (err) throw err;
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    [
        {
          id: 1,
          select_type: ''SIMPLE'',
          table: ''employee'',
          partitions: null,
          type: ''ALL'',
          possible_keys: null,
          key: null,
          key_len: null,
          ref: null,
          rows: 1,
          filtered: 100,
          Extra: null
        }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class CompositeKey {
       public static void main(String[] args) {
          String url = "jdbc:mysql://localhost:3306/TUTORIALS";
          String username = "root";
          String password = "password";
          try {
             Class.forName("com.mysql.cj.jdbc.Driver");
             Connection connection = DriverManager.getConnection(url, username, password);
             Statement statement = connection.createStatement();
             System.out.println("Connected successfully...!");
    
             //Create a composite key in the customers table...!;
             String sql = "Alter TABLE customers ADD PRIMARY KEY(cust_Id, cust_Name)";
             statement.execute(sql);
             System.out.println("Composite key created successfully...!");
             ResultSet resultSet = statement.executeQuery("DESCRIBE customers");
             while (resultSet.next()){
                System.out.println(resultSet.getString(1)+" "+resultSet.getString(2)+" "
                        +resultSet.getString(3)+ " "+ resultSet.getString(4));
             }
             connection.close();
          } catch (Exception e) {
             System.out.println(e);
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Connected successfully...!
    Composite key created successfully...!
    Cust_ID int NO PRI
    Cust_Name varchar(30) NO PRI
    
    import mysql.connector
    #establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    cursorObj = connection.cursor()
    # Create table
    composite_key_query = ''''''CREATE TABLE TEST(ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, MOBILE BIGINT,
    CONSTRAINT CK_TEST PRIMARY KEY (ID, MOBILE))''''''
    cursorObj.execute(composite_key_query)
    connection.commit()
    print("Composite key column is created successfully!")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Composite key column is created successfully!
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Foreign Key nhận dự án làm có lương

    MySQL – Foreign Key

    Table of content


    In MySQL, a Foreign Key is a column (or combination of columns) in a table whose values match the values of a Primary Key column in another table. Thus, using the Foreign key, we can link two tables together.

    A Foreign Key is also known as a Referencing key of a table because it can reference any field defined as unique.

    The table that has the primary key is known as the parent table and the key with the foreign key is known as the child table.

    In addition to linking to tables, the Foreign Key constraint ensures referential integrity by preventing changes to data in the primary key table from invalidating the link to data in the foreign key table. i.e, a Foreign key prevents operations, like “dropping the table”, that would eliminate the connection between two tables.

    Creating MySQL Foreign Key

    We can create a Foreign Key on a MySQL table using the CONSTRAINT… FOREIGN KEY… REFERENCES keyword in the CREATE TABLE statement.

    Syntax

    Following is the syntax to add Foreign Key constraints on a column of a table −

    CREATE TABLE table2(
       column1 datatype,
       column2 datatype,
       ...
       CONSTRAINT constraint_name
       FOREIGN KEY (column2)
       REFERENCES table1(column1)
    );
    

    Example

    Let us create a table named CUSTOMERS using the CREATE TABLE statement −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25) UNIQUE,
       SALARY DECIMAL (18, 2),
       PRIMARY KEY(ID)
    );
    

    To demonstrate the foreign key we need two tables so lets create another table as −

    CREATE TABLE ORDERS (
       OID INT NOT NULL,
       DATE VARCHAR (20) NOT NULL,
       CUSTOMER_ID INT NOT NULL,
       AMOUNT DECIMAL (18, 2),
       CONSTRAINT fk_customers FOREIGN KEY (CUSTOMER_ID)
       REFERENCES CUSTOMERS(ID)
    );
    

    Verification

    To verify if the foreign key is created, let us drop the CUSTOMERS table without dropping the ORDERS table using the following statement −

    DROP TABLE CUSTOMERS;
    

    An error is displayed as follows −

    ERROR 3730 (HY000): Cannot drop table ''customers'' referenced by a foreign key constraint ''fk_customers'' on table ''orders''.
    

    Creating Foreign Key on Existing Column

    We can also create a Foreign Key constraint on a column of an existing table using the ALTER TABLE… ADD CONSTRAINT statement.

    Syntax

    Following is the syntax to add foreign key constraint on an existing table −

    ALTER TABLE table_name2
    ADD CONSTRAINT constraint_name
    FOREIGN KEY(column_name2)
    REFERENCES table_name1(column_name1);
    

    Example

    Following is the MySQL query to add a foreign key constraint FK_CUSTOMERS on an existing column of an existing table ORDERS referencing primary key of CUSTOMERS table −

    ALTER TABLE ORDERS
    ADD CONSTRAINT FK_CUSTOMERS
    FOREIGN KEY(CUSTOMER_ID)
    REFERENCES CUSTOMERS(ID);
    

    Output

    The table structure displayed will contain a FOREIGN KEY constraint on the CUSTOMER_ID column as shown −

    Field Type Null Key Default Extra
    OID int NO NULL
    DATE varchar(20) NO NULL
    CUSTOMER_ID int NO MUL NULL
    AMOUNT decimal(18,2) YES NULL

    Verification

    To verify if the foreign key we created on ORDERS is referenced to CUSTOMERS table or not, let us drop the CUSTOMERS table without dropping the ORDERS table using the following statement −

    DROP TABLE CUSTOMERS;
    

    An error is displayed as follows −

    ERROR 3730 (HY000): Cannot drop table ''customers'' referenced by a foreign key constraint ''fk_customers'' on table ''orders''.
    

    Dropping MySQL Foreign Key

    We can also drop the foreign key, created on a MySQL table, whenever it is no longer needed in that table. We can do this using the ALTER TABLE… DROP CONSTRAINT statement in MySQL.

    Syntax

    Following is the syntax to drop the foreign key from a table −

    ALTER TABLE table_name DROP CONSTRAINT constraint_name;
    

    Example

    Using the following MySQL query, we are dropping the foreign key constraint from a table −

    ALTER TABLE CUSTOMERS DROP CONSTRAINT fk_customers;
    

    Verification

    Let us verify whether the foreign key is dropped or not by dropping the CUSTOMERS table using the following query −

    DROP TABLE CUSTOMERS;
    

    Primary Key vs Foreign Key

    Even though both the primary key and foreign key refer to the same column, there are many differences to be observed in the way they work. They are listed below.

    Primary Key Foreign Key
    The Primary Key is always unique. The Foreign Key can be duplicated.
    The Primary Key can not be NULL. The Foreign Key can be NULL.
    A table can contain only one Primary Key. We can have more than one Foreign Key per table.

    Creating Foreign Key Using Client Program

    We can also apply a Foreign Key constraint on a table field using a client program.

    Syntax

    To apply foreign key on a field through a PHP program, we need to execute the FOREIGN KEY keyword in CREATE statement using the mysqli function query() as follows −

    $sql = ''CREATE TABLE customers(Customer_Id INT, Customer_Name VARCHAR(30),
    CONSTRAINT tut_cutomers FOREIGN KEY (Customer_Id) REFERENCES customer(cust_ID))
    $mysqli->query($sql);
    

    To apply foreign key on a field through a JavaScript program, we need to execute the FOREIGN KEY keyword in CREATE statement using the query() function of mysql2 library as follows −

    sql = `CREATE TABLE customerss(Customer_Id INT, Customer_Name VARCHAR(30), CONSTRAINT tut_cutomers FOREIGN KEY (Customer_Id) REFERENCES customers(cust_ID) )`;
    con.query(sql);
    

    To apply foreign key on a field through a Java program, we need to execute the FOREIGN KEY keyword in CREATE statement using the JDBC function execute() as follows −

    String sql = "CREATE TABLE customer(Customer_Id INT, Customer_Name VARCHAR(30), CONSTRAINT tut_cutomers FOREIGN KEY (Customer_Id) REFERENCES customers(cust_ID))";
    statement.execute(sql);
    

    To apply foreign key on a field through a Python program, we need to execute the FOREIGN KEY keyword in CREATE statement using the execute() function of the MySQL Connector/Python as follows −

    foreign_key_query = ''CREATE TABLE customer(Customer_Id INT, Customer_Name VARCHAR(30), CONSTRAINT tut_cutomers FOREIGN KEY (Customer_Id) REFERENCES customers(cust_ID))''
    cursorObj.execute(foreign_key_query)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $dbname = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } // printf(''Connected successfully.
    ''); $sql = ''CREATE TABLE customerss(Customer_Id INT, Customer_Name VARCHAR(30), CONSTRAINT tut_cutomers FOREIGN KEY (Customer_Id) REFERENCES customer(cust_ID)) if ($mysqli->query($sql)) { echo "foreign key column created successfully in customers table n"; } if ($mysqli->errno) { printf("Table could not be created!.
    ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    foreign key column created successfully in customers table
    
    var mysql = require("mysql2");
    var con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "password",
    }); //Connecting to MySQL
    
    con.connect(function (err) {
      if (err) throw err;
      //   console.log("Connected successfully...!");
      //   console.log("--------------------------");
      sql = "USE TUTORIALS";
      con.query(sql);
    
      //creating a column that is foreign key!
      sql = `CREATE TABLE customerss(Customer_Id INT, Customer_Name VARCHAR(30), CONSTRAINT tut_cutomers FOREIGN KEY (Customer_Id) REFERENCES customers(cust_ID) )`;
      con.query(sql);
    
      //describe table details
      sql = "DESCRIBE TABLE customers";
      con.query(sql, function (err, result) {
        if (err) throw err;
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    [
        {
          id: 1,
          select_type: ''SIMPLE'',
          table: ''customers'',
          partitions: null,
          type: ''ALL'',
          possible_keys: null,
          key: null,
          key_len: null,
          ref: null,
          rows: 1,
          filtered: 100,
          Extra: null
        }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class ForeignKey {
       public static void main(String[] args) {
          String url = "jdbc:mysql://localhost:3306/TUTORIALS";
          String username = "root";
          String password = "password";
          try {
             Class.forName("com.mysql.cj.jdbc.Driver");
             Connection connection = DriverManager.getConnection(url, username, password);
             Statement statement = connection.createStatement();
             System.out.println("Connected successfully...!");
    
             //Create a foreign key in the customer table...!;
             String sql = "CREATE TABLE customer(Customer_Id INT, Customer_Name VARCHAR(30), CONSTRAINT tut_cutomers FOREIGN KEY (Customer_Id) REFERENCES customers(cust_ID))";
             statement.execute(sql);
             System.out.println("Foreign key created successfully...!");
             ResultSet resultSet = statement.executeQuery("DESCRIBE customer");
             while (resultSet.next()){
                System.out.println(resultSet.getString(1)+" "+resultSet.getString(2)+" "
                        +resultSet.getString(3)+ " "+ resultSet.getString(4));
             }
             connection.close();
          } catch (Exception e) {
             System.out.println(e);
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Connected successfully...!
    Foreign key created successfully...!
    Customer_Id int YES MUL
    Customer_Name varchar(30) YES
    
    import mysql.connector
    #establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    cursorObj = connection.cursor()
    # Create table
    foreign_key_query = ''''''CREATE TABLE customer(Customer_Id INT, Customer_Name VARCHAR(30), CONSTRAINT tut_cutomers FOREIGN KEY (Customer_Id) REFERENCES customers(cust_ID))''''''
    cursorObj.execute(foreign_key_query)
    connection.commit()
    print("Foreign key column is created successfully!")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Foreign key column is created successfully!
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Alternate Key nhận dự án làm có lương

    MySQL – Alternate Key

    Table of content


    An Alternate Key in a table is nothing but an alternative to the primary key in that table. In other words, they are candidate keys that are not currently selected as the primary key of a table (but has a potential to be one). Hence, they can also be used to uniquely identify a tuple(or a record) in a table.

    If a table consists of only one Candidate key that is treated as the primary key of the table, then there is no alternate key in that table.

    There is no specific query or syntax to set the alternate key in a table. It is just an ordinary column that is a secondary candidate to be selected as a primary key.

    Features of Alternate Keys

    Even though alternate keys are not primary keys, they contain some important properties/features of their own. They are listed below −

    • The alternate key does not allow duplicate values.
    • A table can have more than one alternate keys.
    • The alternate key can contain NULL values unless the NOT NULL constraint is set explicitly.
    • All alternate keys can be candidate keys, but all candidate keys can not be alternate keys. As a primary key, which is also a candidate key, can not be considered as an alternate key.

    Types of Keys in a Table

    Below is the list of keys that are present in a table −

    • Candidate key
    • Primary key
    • Alternate key
    • Foreign Key

    Candidate Key

    A Candidate key is a subset of super keys that is used to uniquely identify records of a table. It can either be a single field or multiple fields. Primary keys, alternate keys, foreign keys in a table are all types of candidate key.

    Primary Key

    A Primary Key is a main key that is used to retrieve records from a table. It is a single column or field in a table that uniquely identifies each record in a database table.

    It can be set using the PRIMARY KEY keyword while creating a table using the CREATE TABLE statement. The syntax is as follows −

    CREATE TABLE table_name(
       COLUMN_NAME1 datatype,
       COLUMN_NAME2 datatype,
       ...
       PRIMARY KEY(COLUMN_NAME)
    );
    

    Alternate Key

    An Alternate key is a Candidate key that could be a primary key but is not. Like primary key, it also uniquely identifies the records in a field of a table to retrieve row tuples from the said table. There can be a single or multiple fields identifying as alternate keys in a table.

    There is no syntax to set an alternate key in a database table.

    Foreign Key

    The Primary key of one table will be the Foreign key in another table. While inserting values into these tables, values in the primary key field must match the values in the foreign key field; otherwise, the foreign key column will not accept the INSERT query and throws an error.

    The syntax to set a foreign key field in a table is −

    CREATE TABLE table_name2(
       ... CONSTRAINT constraint_name
       FOREIGN KEY (column_name2)
       REFERENCES table_name1(column_name1)
    );
    

    Example

    In the following example, we are creating a sample table named CUSTOMERS in the MySQL database −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY(ID)
    );
    

    Now let us insert some records into this table created using the INSERT statement as shown below −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00),
    (3, ''Kaushik'', 23, ''Kota'', 2000.00),
    (4, ''Chaitali'', 25, ''Mumbai'', 6500.00),
    (5, ''Hardik'', 27, ''Bhopal'', 8500.00),
    (6, ''Komal'', 22, ''Hyderabad'', 4500.00),
    (7, ''Muffy'', 24, ''Indore'', 10000.00);
    

    Verification

    To verify the keys added to the CUSTOMERS table, let us display the table definition using the following query −

    Field Type Null Key Default Extra
    ID int NO PRI NULL
    NAME varchar(20) NO NULL
    AGE int NO NULL
    ADDRESS char(25) YES NULL
    SALARY decimal(18, 2) YES NULL

    Currently, only PRIMARY KEY is set in the table on ID column. The NAME column acts like the Alternate Key, as it will only contain unique records like a Primary Key column. Whereas, both ID and NAME are the Candidate Keys in the CUSTOMERS table.

    Example

    To illustrate the usage of Foreign Key, we would need two tables. Following is the query to create another table ORDERS with the foreign key set as CUSTOMER_ID.

    CREATE TABLE ORDERS (
       OID INT NOT NULL,
       DATE VARCHAR (20) NOT NULL,
       CUSTOMER_ID INT NOT NULL,
       AMOUNT DECIMAL (18, 2),
       CONSTRAINT fk_customers FOREIGN KEY (CUSTOMER_ID)
       REFERENCES CUSTOMERS(ID)
    );
    

    Using the INSERT statement, insert values into this table as follows −

    INSERT INTO ORDERS VALUES
    (102, ''2009-10-08 00:00:00'', 3, 3000.00),
    (100, ''2009-10-08 00:00:00'', 3, 1500.00),
    (101, ''2009-11-20 00:00:00'', 2, 1560.00),
    (103, ''2008-05-20 00:00:00'', 4, 2060.00);
    

    Verification

    To verify if the ORDERS table is referenced to the CUSTOMERS table or not, we drop the CUSTOMERS table without dropping the ORDERS table.

    DROP TABLE CUSTOMERS;
    

    Following error is displayed −

    ERROR 3730 (HY000): Cannot drop table ''customers'' referenced by a foreign key constraint ''fk_customers'' on table ''orders''.
    

    Rules to be Followed for Alternate Keys

    Below are list of rules of alternate keys that should be followed while inserting the record into a table −

    • Alternate key values should be unique.
    • Alternate key can not be NULL.

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Primary Key nhận dự án làm có lương

    MySQL – Primary Key

    Table of content


    A PRIMARY KEY is a constraint applied on a field of a MySQL table. When this is applied, the values in that particular table column are uniquely identified. It is the most appropriate candidate key to be the main key of any table.

    A table can have only one PRIMARY KEY, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a Composite Key.

    You can either create a primary key while creating a new table or you can apply it on an already existing table in the database. But if it is being applied on an existing table, you must make sure that the table does not already contain a primary key and .

    Creating MySQL Primary Key

    To create a primary key on a new MySQL table, you must specify the column as the PRIMARY KEY while creating a new table using the CREATE TABLE statement.

    Following are some points to remember while creating a Primary Key on a table −

    • The Primary Key column must only contain unique values.
    • It can not hold NULL values.
    • One table can have only one Primary Key.
    • A Primary Key length cannot be more than 900 bytes.

    Syntax

    Following is the syntax to define a column of a table as a primary key −

    CREATE TABLE table_name(
       column_name NOT NULL PRIMARY KEY(column_name)
    );
    

    Example

    In the following example, let us create a table with the name CUSTOMERS in a MySQL database using the CREATE TABLE query. In this query, we will add the PRIMARY KEY constraint on a column named ID.

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25) UNIQUE,
       SALARY DECIMAL (18, 2),
       PRIMARY KEY(ID)
    );
    

    Output

    The table structure displayed will contain a UNI index on the ADDRESS column as shown −

    Field Type Null Key Default Extra
    ID int NO PRI NULL
    NAME varchar(20) NO NULL
    AGE int NO NULL
    ADDRESS char(25) YES NULL
    SALARY decimal(18, 2) YES NULL

    Verification

    To verify further that the PRIMARY KEY constraint is applied on the ID column, let us insert different types of values into the CUSTOMERS table using the following queries −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 23, ''Pune'', 2000.00),
    (1, ''John'', 25, ''Hyderabad'', 3000.00);
    

    Following error is displayed −

    ERROR 1062 (23000): Duplicate entry ''1'' for key ''customers.PRIMARY''
    

    As we can see above, you cannot insert duplicate and null values into this primary key column.

    Creating Primary Key on Existing Column

    We can also add a primary key on an existing column of a table, if it was not created (for any reason) while creating a new table. However, adding a primary key on an existing table is only possible if the table does not already contain a primary key (as a MySQL table must not contain multiple primary keys), and the column it is being applied on must only contain unique values.

    You can add the primary key on an existing table using the ALTER TABLE… ADD CONSTRAINT statement.

    Syntax

    Following is the syntax to create a unique constraint on existing columns of a table −

    ALTER TABLE table_name
    ADD CONSTRAINT
    PRIMARY KEY (column_name);
    

    Example

    Using the ALTER TABLE statement, you can add a PRIMARY KEY on an existing column in the CUSTOMERS table created previously. In the following example, we are applying the PRIMARY KEY on the ID column as shown below −

    ALTER TABLE CUSTOMERS
    ADD CONSTRAINT
    PRIMARY KEY (ADDRESS);
    

    Output

    The table structure displayed will contain a UNI index on the ADDRESS column as shown −

    Field Type Null Key Default Extra
    ID int NO PRI NULL
    NAME varchar(20) NO NULL
    AGE int NO NULL
    ADDRESS char(25) YES NULL
    SALARY decimal(18, 2) YES NULL

    But if the column, on which the PRIMARY KEY is added, contains duplicate or null values, it cannot be set as a primary key.

    Dropping MySQL Primary Key

    MySQL provides the ALTER TABLE… DROP statement to drop the primary key from a table.

    Syntax

    Following is the syntax to drop the PRIMARY KEY constraint using the ALTER TABLE… DROP statement −

    ALTER TABLE table_name DROP PRIMARY KEY;
    

    Example

    Let us consider the CUSTOMERS table with the primary key constraint present on a column named ID. You can drop this constraint from the column ID by executing the following statement

    ALTER TABLE CUSTOMERS DROP PRIMARY KEY;
    

    Output

    The table structure displayed will contain a UNI index on the ADDRESS column as shown −

    Field Type Null Key Default Extra
    ID int NO NULL
    NAME varchar(20) NO NULL
    AGE int NO NULL
    ADDRESS char(25) YES NULL
    SALARY decimal(18, 2) YES NULL

    Creating Primary Key Using Client Program

    We can also apply a Primary Key on a table field using a client program.

    Syntax

    To apply primary key on a field through a PHP program, we need to execute the CREATE query with PRIMARY KEY keyword using the mysqli function query() as follows −

    $sql = ''CREATE TABLE customers(cust_ID INT NOT NULL UNIQUE, cust_Name VARCHAR(30), cust_login_ID INT AUTO_INCREMENT PRIMARY KEY)
    $mysqli->query($sql);
    

    To apply primary key on a field through a JavaScript program, we need to execute the CREATE query with PRIMARY KEY keyword using the query() function of mysql2 library as follows −

    sql = `CREATE TABLE customers(cust_ID INT NOT NULL primary key, cust_Name VARCHAR(30))`;
    con.query(sql);
    

    To apply primary key on a field through a Java program, we need to execute the CREATE query with PRIMARY KEY keyword using the JDBC function execute() as follows −

    String sql = "CREATE TABLE customers(cust_ID INT NOT NULL UNIQUE, cust_Name VARCHAR(30), cust_login_ID INT AUTO_INCREMENT PRIMARY KEY)";
    statement.execute(sql);
    

    To apply primary key on a field through a Python program, we need to execute the CREATE query with PRIMARY KEY keyword using the execute() function of the MySQL Connector/Python as follows −

    primary_key_query = ''CREATE TABLE TEST (ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, PRIMARY KEY (ID))''
    cursorObj.execute(primary_key_query)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $dbname = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } // printf(''Connected successfully.
    ''); $sql = ''CREATE TABLE customers(cust_ID INT NOT NULL UNIQUE, cust_Name VARCHAR(30), cust_login_ID INT AUTO_INCREMENT PRIMARY KEY) if ($mysqli->query($sql)) { echo "Primary key column created successfully in customers table n"; } if ($mysqli->errno) { printf("Table could not be created!.
    ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Primary key column created successfully in customers table
    
    var mysql = require("mysql2");
    var con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "password",
    }); //Connecting to MySQL
    
    con.connect(function (err) {
      if (err) throw err;
      //   console.log("Connected successfully...!");
      //   console.log("--------------------------");
      sql = "USE TUTORIALS";
      con.query(sql);
    
      //create a table that stored primary key
      sql = `CREATE TABLE customers(cust_ID INT NOT NULL primary key, cust_Name VARCHAR(30))`;
      con.query(sql);
    
      //describe table details
      sql = "DESCRIBE TABLE customers";
      con.query(sql, function (err, result) {
        if (err) throw err;
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    [
        {
          id: 1,
          select_type: ''SIMPLE'',
          table: ''customers'',
          partitions: null,
          type: ''ALL'',
          possible_keys: null,
          key: null,
          key_len: null,
          ref: null,
          rows: 1,
          filtered: 100,
          Extra: null
        }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class PrimaryKey {
       public static void main(String[] args) {
          String url = "jdbc:mysql://localhost:3306/TUTORIALS";
          String username = "root";
          String password = "password";
          try {
             Class.forName("com.mysql.cj.jdbc.Driver");
             Connection connection = DriverManager.getConnection(url, username, password);
             Statement statement = connection.createStatement();
             System.out.println("Connected successfully...!");
    
             //Create a primary key in the customer table...!;
             String sql = "CREATE TABLE customers(cust_ID INT NOT NULL UNIQUE, cust_Name VARCHAR(30), cust_login_ID INT AUTO_INCREMENT PRIMARY KEY)";
             statement.execute(sql);
             System.out.println("Primary key created successfully...!");
             ResultSet resultSet = statement.executeQuery("DESCRIBE customers");
             while (resultSet.next()){
                System.out.println(resultSet.getString(1)+" "+resultSet.getString(2)+" "
                        +resultSet.getString(3)+ " "+ resultSet.getString(4));
             }
             connection.close();
            }
             catch (Exception e) {
             System.out.println(e);
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Connected successfully...!
    Primary key created successfully...!
    cust_ID int NO UNI
    cust_Name varchar(30) YES
    cust_login_ID int NO PRI
    
    import mysql.connector
    #establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    cursorObj = connection.cursor()
    # Create table
    primary_key_query = ''''''CREATE TABLE TEST (ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, PRIMARY KEY (ID))''''''
    cursorObj.execute(primary_key_query)
    connection.commit()
    print("Primary key column is created successfully!")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Primary key column is created successfully!
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Union vs Join nhận dự án làm có lương

    MySQL – Union vs Join

    Table of content


    MySQL provides various relational operators to handle data that is spread across multiple tables in a relational database. Out of them, UNION and JOIN queries are fundamentally used to combine data from multiple tables.

    Even though they are both used for the same purpose, i.e. to combine tables, there are many differences between the working of these operators. The major difference is that the UNION operator combines data from multiple similar tables irrespective of the data relativity, whereas, the JOIN operator is only used to combine relative data from multiple tables.

    Working of UNION

    UNION is a type of operator/clause in MySQL, that works similar to the union operator in relational algebra. It does nothing more than just combining information from multiple tables that are union compatible.

    The tables are said to be union compatible if they follow the conditions given below:

    • The tables to be combined must have same number of columns with the same datatype.
    • The number of rows need not be same.

    Once these criteria are met, UNION operator returns all the rows from multiple tables, after eliminating duplicate rows, as a resultant table.

    Note: Column names of first table will become column names of resultant table, and contents of second table will be merged into resultant columns of same data type.

    Syntax

    Following is the syntax of UNION operator in MySQL −

    SELECT * FROM table1
    UNION
    SELECT * FROM table2;
    

    Example

    Let us first create two table “COURSES_PICKED” and “EXTRA_COURSES_PICKED” with the same number of columns having same data types.

    Create table COURSES_PICKED using the following query −

    CREATE TABLE COURSES_PICKED(
       STUDENT_ID INT NOT NULL,
       STUDENT_NAME VARCHAR(30) NOT NULL,
       COURSE_NAME VARCHAR(30) NOT NULL
    );
    

    Insert values into the COURSES_PICKED table with the help of the query given below −

    INSERT INTO COURSES_PICKED VALUES
    (1, ''JOHN'', ''ENGLISH''),
    (2, ''ROBERT'', ''COMPUTER SCIENCE''),
    (3, ''SASHA'', ''COMMUNICATIONS''),
    (4, ''JULIAN'', ''MATHEMATICS'');
    

    Create table EXTRA_COURSES_PICKED using the following query −

    CREATE TABLE EXTRA_COURSES_PICKED(
       STUDENT_ID INT NOT NULL,
       STUDENT_NAME VARCHAR(30) NOT NULL,
       EXTRA_COURSE_NAME VARCHAR(30) NOT NULL
    );
    

    Following is the query to insert values into the EXTRA_COURSES_PICKED table −

    INSERT INTO EXTRA_COURSES_PICKED VALUES
    (1, ''JOHN'', ''PHYSICAL EDUCATION''),
    (2, ''ROBERT'', ''GYM''),
    (3, ''SASHA'', ''FILM''),
    (4, ''JULIAN'', ''PHOTOGRAPHY'');
    

    Now, let us combine both these tables using the UNION query as follows −

    SELECT * FROM COURSES_PICKED
    UNION
    SELECT * FROM EXTRA_COURSES_PICKED;
    

    Output

    The resultant table obtained after performing the UNION operation is −

    STUDENT_ID STUDENT_NAME COURSE_NAME
    1 John English
    1 John Physical Education
    2 Robert Computer Science
    2 Robert Gym
    3 Sasha Communications
    3 Sasha Film
    4 Julian Mathematics
    4 Julian Photography

    Working of JOIN

    The Join operation is used to combine information from multiple related tables into one, based on their common fields.

    In this operation, every row of the first table will be combined with every row of the second table. The resultant table obtained will contain the rows present in both tables. This operation can be used with various clauses like ON, WHERE, ORDER BY, GROUP BY etc.

    There are two types of Joins:

    • Inner Join
    • Outer Join

    The basic type of join is an Inner Join, which only retrieves the matching values of common columns. It is a default join. Other joins like Cross join, Natural Join, Condition Join etc. are types of Inner Joins.

    Outer join includes both matched and unmatched rows from the first table, in the resultant table. It is divided into subtypes like Left Join, Right Join, and Full Join.

    Even though the join operation can merge multiple tables, the simplest way of joining two tables is without using any Clauses other than the ON clause.

    Syntax

    Following is the basic syntax of Join operation −

    SELECT column_name(s)
    FROM table1
    JOIN table2
    ON table1.common_field = table2.common_field;
    

    Example

    In the following example, we will try to join the same tables we created above, i.e., COURSES_PICKED and EXTRA_COURSES_PICKED, using the query below −

    mysql> SELECT c.STUDENT_ID, c.STUDENT_NAME, COURSE_NAME,
    COURSES_PICKED FROM COURSES_PICKED c JOIN EXTRA_COURSES_PICKED e
    ON c.STUDENT_ID = e.STUDENT_ID;
    

    Output

    The resultant table will be displayed as follows −

    STUDENT_ID STUDENT_NAME COURSE_NAME COURSE_PICKED
    1 John ENGLISH Physical Education
    2 Robert COMPUTER SCIENCE Gym
    3 Sasha COMMUNICATIONS Film
    4 Julian MATHEMATICS Photography

    UNION vs JOIN

    As we saw in the examples given above, the UNION operator is only executable on tables that are union compatible, whereas, the JOIN operator joins two tables that need not be compatible but should be related.

    Let us summarize all the difference between these queries below −

    UNION JOIN
    UNION operation is only performed on tables that are union compatible, i.e., the tables must contain same number of columns with same data type. JOIN operation can be performed on tables that has at least one common field between them. The tables need not be union compatible.
    The data combined will be added as new rows of the resultant table. The data combined will be adjoined into the resultant table as new columns.
    This works as the conjunction operation. This works as an intersection operation.
    UNION removes all the duplicate values from the resultant tables. JOIN retains all the values from both tables even if they”re redundant.
    UNION does not need any additional clause to combine two tables. JOIN needs an additional clause ON to combine two tables based on a common field.
    It is mostly used in scenarios like, merging the old employees list in an organization with the new employees list. This is used in scenarios where merging related tables is necessary. For example, combining tables containing customers list and the orders they made.

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc