Category: mysql

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

    MySQL – Before Insert Trigger

    Table of content


    As we have already learned, a Trigger is defined as a response to an event performed. In MySQL, a trigger 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. These events include executing SQL statements like INSERT, UPDATE and DELETE etc.

    MySQL Before Insert Trigger

    The Before Insert Trigger is a row-level trigger supported by the MySQL database. As its name suggests, this trigger is executed right before a value is being 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.

    Whenever an INSERT statement is queried in the database, this Trigger is automatically executed first and then only the value is inserted into the table.

    Syntax

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

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

    Example

    Let us see an example demonstrating the BEFORE INSERT trigger. In here, we are creating a new table STUDENT which contains the details of students in an institution, using the following query −

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

    Using the following CREATE TRIGGER statement, create a new trigger sample_trigger on the STUDENT table. Here, we are checking the score of each student and assigning them with a suitable grade.

    DELIMITER //
    CREATE TRIGGER sample_trigger
    BEFORE INSERT ON STUDENT FOR EACH ROW
    BEGIN
    IF NEW.Score < 35 THEN SET NEW.Grade = ''FAIL
    ELSE SET NEW.Grade = ''PASS
    END IF;
    END //
    DELIMITER ;
    

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

    INSERT INTO STUDENT VALUES
    (''John'', 21, 76, NULL),
    (''Jane'', 20, 24, NULL),
    (''Rob'', 21, 57, NULL),
    (''Albert'', 19, 87, NULL);
    

    Verification

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

    Name Age Score Grade
    John 21 76 PASS
    Jane 20 24 FAIL
    Rob 21 57 PASS
    Albert 19 87 PASS

    Before Insert Trigger Using a Client Program

    In addition to create or show a trigger, we can also Perform the “Before Insert trigger” statement using a client program.

    Syntax

    To Perform the Before Insert Trigger through a PHP program, we need to execute the CREATE TRIGGER statement using the mysqli function query() as follows −

    $sql = "Create Trigger sample_trigger BEFORE INSERT ON STUDENT"."
    FOR EACH ROW
    BEGIN
    IF NEW.Score < 35 THEN SET NEW.Grade = ''FAIL
    ELSE SET NEW.Grade = ''PASS
    END IF;
    END";
    $mysqli->query($sql);
    

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

    sql = `Create Trigger sample_trigger BEFORE INSERT ON STUDENT
    FOR EACH ROW
    BEGIN
    IF NEW.Score < 35 THEN SET NEW.Grade = ''FAIL
    ELSE SET NEW.Grade = ''PASS
    END IF;
    END`;
    con.query(sql);
    

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

    String sql = "Create Trigger sample_trigger BEFORE INSERT ON STUDENT FOR EACH ROW BEGIN IF NEW.Score < 35 THEN SET NEW.Grade = ''FAIL
    ELSE SET NEW.Grade = ''PASS
    END IF;
    END";
    statement.execute(sql);
    

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

    beforeInsert_trigger_query = ''CREATE TRIGGER sample_trigger
    BEFORE INSERT ON student
    FOR EACH ROW
    BEGIN
    IF NEW.Score < 35
    THEN SET NEW.Grade = ''FAIL
    ELSE SET NEW.Grade = ''PASS
    END IF;
    END''
    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 = "Create Trigger sample_trigger BEFORE INSERT ON STUDENT"." FOR EACH ROW BEGIN IF NEW.Score < 35 THEN SET NEW.Grade = ''FAIL ELSE SET NEW.Grade = ''PASS END IF; END"; if($mysqli->query($sql)){ printf("Trigger created successfully...!n"); } $q = "INSERT INTO STUDENT VALUES (''John'', 21, 76, NULL)"; $result = $mysqli->query($q); if ($result == true) { printf("Record inserted successfully...!n"); } $q1 = "SELECT * FROM STUDENT"; if($r = $mysqli->query($q1)){ printf("Select query executed successfully...!"); printf("Table records(Verification): n"); while($row = $r->fetch_assoc()){ printf("Name: %s, Age: %d, Score %d, Grade %s", $row["Name"], $row["Age"], $row["Score"], $row["Grade"]); printf("n"); } } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Trigger created successfully...!
    Record inserted successfully...!
    Select query executed successfully...!Table records(Verification):
    Name: Jane, Age: 20, Score 24, Grade FAIL
    Name: John, Age: 21, Score 76, Grade PASS
    
    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 sample_trigger BEFORE INSERT ON STUDENT
     FOR EACH ROW
     BEGIN
     IF NEW.Score < 35 THEN SET NEW.Grade = ''FAIL
     ELSE SET NEW.Grade = ''PASS
     END IF;
     END`;
     con.query(sql);
     console.log("Before Insert query executed successfully..!");
     sql = "INSERT INTO STUDENT VALUES (''Aman'', 22, 86, NULL)";
     con.query(sql);
     console.log("Record inserted successfully...!");
     console.log("Table records: ")
     sql = "SELECT * FROM STUDENT";
     con.query(sql, function(err, result){
     if (err) throw err;
     console.log(result);
     });
    });
    

    Output

    The output produced is as follows −

    Before Insert query executed successfully..!
    Record inserted successfully...!
    Table records:
    [
      { Name: ''Jane'', Age: 20, Score: 24, Grade: ''FAIL'' },
      { Name: ''John'', Age: 21, Score: 76, Grade: ''PASS'' },
      { Name: ''John'', Age: 21, Score: 76, Grade: ''PASS'' },
      { Name: ''Aman'', Age: 22, Score: 86, Grade: ''PASS'' },
      { Name: ''Aman'', Age: 22, Score: 86, Grade: ''PASS'' }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class BeforeInsertTrigger {
       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...!");
                //lets create trigger on student table
                String sql = "Create Trigger sample_trigger BEFORE INSERT ON STUDENT FOR EACH ROW BEGIN IF NEW.Score < 35 THEN SET NEW.Grade = ''FAIL
                ELSE SET NEW.Grade = ''PASS
                END IF;
                END";
                st.execute(sql);
                System.out.println("Triggerd Created successfully...!");
                //lets insert some records into student table
                String sql1 = "INSERT INTO STUDENT VALUES (''John'', 21, 76, NULL), (''Jane'', 20, 24, NULL), (''Rob'', 21, 57, NULL), (''Albert'', 19, 87, NULL)";
                st.execute(sql1);
                //let print table records
                String sql2 = "SELECT * FROM STUDENT";
                rs = st.executeQuery(sql2);
                while(rs.next()) {
                   String name = rs.getString("name");
                   String age = rs.getString("age");
                   String score = rs.getString("score");
                   String grade = rs.getString("grade");
                   System.out.println("Name: " + name + ", Age: " + age + ", Score: " + score + ", Grade: " + grade);
                }
          }catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Triggerd Created successfully...!
    Name: John, Age: 21, Score: 76, Grade: PASS
    Name: Jane, Age: 20, Score: 24, Grade: FAIL
    Name: Rob, Age: 21, Score: 57, Grade: PASS
    Name: Albert, Age: 19, Score: 87, Grade: PASS
    
    import mysql.connector
    # Establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    # Creating a cursor object
    cursorObj = connection.cursor()
    trigger_name = ''sample_trigger''
    table_name = ''Student''
    beforeInsert_trigger_query = f''''''CREATE TRIGGER {trigger_name}
    BEFORE INSERT ON {table_name}
    FOR EACH ROW
    BEGIN
    IF NEW.Score < 35
    THEN SET NEW.Grade = ''FAIL
    ELSE SET NEW.Grade = ''PASS
    END IF;
    END''''''
    cursorObj.execute(beforeInsert_trigger_query)
    print(f"BEFORE INSERT 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 −

    BEFORE INSERT 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 – After Update Trigger nhận dự án làm có lương

    MySQL – After Update Trigger

    Table of content


    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, and is executed whenever an event is performed. 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 Update Trigger

    The After Update Trigger is a row-level trigger supported by the MySQL database. As its name suggests, the After Update Trigger is executed right after a value is updated in a row of 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.

    Once the After Update trigger is defined in MySQL, whenever an UPDATE statement is executed in the database, the value of a table is updated first followed by execution of the trigger set.

    Syntax

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

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

    Example

    Let us first create a table named USERS containing the details of users of an application. Use the following CREATE TABLE query to do so −

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

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

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

    The USERS table is created as follows −

    ID NAME AGE BIRTHDATE
    1 Sasha 23 24/06/1999
    2 Alex 21 12/01/2001

    Creating the trigger:

    Using the following CREATE TRIGGER statement, create a new trigger ”after_update_trigger” on the USERS table to display a customized error using SQLSTATE as follows −

    DELIMITER //
    CREATE TRIGGER after_update_trigger AFTER UPDATE ON USERS FOR EACH ROW
    BEGIN
    IF NEW.AGE < 0
    THEN SIGNAL SQLSTATE ''45000''
    SET MESSAGE_TEXT = ''Age Cannot be Negative
    END IF;
    END //
    DELIMITER ;
    

    Update values of the SAMPLE table using the regular UPDATE statement as shown below −

    UPDATE SAMPLE SET AGE = -1 WHERE NAME = ''Sasha
    

    Output

    An error is displayed as the output for this query −

    ERROR 1644 (45000): Age Cannot be Negative
    

    After Update Trigger Using a Client Program

    We can also execute the After Update Triggers in MySQL database using a client program instead of querying SQL statements directly.

    Syntax

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

    $sql = "CREATE TRIGGER after_update_trigger AFTER UPDATE ON SAMPLE FOR EACH ROW
    BEGIN
    IF NEW.AGE < 0 THEN SIGNAL SQLSTATE ''45000'' SET MESSAGE_TEXT = ''Age Cannot be Negative
    END IF;
    END ";
    $mysqli->query($sql);
    

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

    sql = `CREATE TRIGGER after_update_trigger AFTER UPDATE ON SAMPLE FOR EACH ROW
    BEGIN
    IF NEW.AGE < 0 THEN SIGNAL SQLSTATE ''45000'' SET MESSAGE_TEXT = ''Age Cannot be Negative
    END IF;
    END`;
    con.query(sql);
    

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

    String sql = "CREATE TRIGGER after_update_trigger AFTER UPDATE ON SAMPLE FOR EACH ROW BEGIN IF NEW.AGE < 0 THEN SIGNAL SQLSTATE ''45000'' SET MESSAGE_TEXT = ''Age Cannot be Negative
    END IF;
    END";
    statement.execute(sql);
    

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

    afterUpdate_trigger_query = ''CREATE TRIGGER {trigger_name}
    AFTER UPDATE ON {table_name}
    FOR EACH ROW
    BEGIN
    IF NEW.AGE < 0
    THEN SIGNAL SQLSTATE ''45000''
    SET MESSAGE_TEXT = ''Age Cannot be Negative
    END IF
    END''
    cursorObj.execute(afterUpdate_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 after_update_trigger AFTER UPDATE ON SAMPLE FOR EACH ROW BEGIN IF NEW.AGE < 0 THEN SIGNAL SQLSTATE ''45000'' SET MESSAGE_TEXT = ''Age Cannot be Negative END IF; END "; if($mysqli->query($sql)){ printf("Trigger created successfully...!n"); } $q = "UPDATE SAMPLE SET AGE = -1 WHERE NAME = ''Sasha''"; $result = $mysqli->query($q); if ($result == true) { printf("Record updated successfully...!n"); } if($mysqli->error){ printf("Error message: " , $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Trigger created successfully...!
    PHP Fatal error:  Uncaught mysqli_sql_exception: Age Cannot be Negative
    
    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 after_update_trigger AFTER UPDATE ON SAMPLE FOR EACH ROW
     BEGIN
     IF NEW.AGE < 0 THEN SIGNAL SQLSTATE ''45000'' SET MESSAGE_TEXT = ''Age Cannot be Negative
     END IF;
     END`;
     con.query(sql);
     console.log("After Update query executed successfully..!");
     sql = "UPDATE SAMPLE SET AGE = -1 WHERE NAME = ''Sasha''";
     con.query(sql);
     console.log("Table records: ")
     sql = "SELECT * FROM Sample";
     con.query(sql, function(err, result){
     if (err) throw err;
     console.log(result);
     });
    });
    

    Output

    The output produced is as follows −

    Error: Age Cannot be Negative
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class AfterUpdateTrigger {
        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 = "SELECT * FROM SAMPLE";
                rs = st.executeQuery(sql);
                System.out.println("Sample table records before update: ");
                while(rs.next()) {
                    String id = rs.getString("id");
                    String name = rs.getString("name");
                    String age = rs.getString("age");
                    String birth_date = rs.getString("BIRTHDATE");
                    System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Birth_date: " + birth_date);
                }
                //lets create trigger on student table
                String sql1 = "CREATE TRIGGER after_update_trigger AFTER UPDATE ON SAMPLE FOR EACH ROW BEGIN IF NEW.AGE < 0 THEN SIGNAL SQLSTATE ''45000'' SET MESSAGE_TEXT = ''Age Cannot be Negative
                END IF;
                END";
                st.execute(sql1);
                System.out.println("Triggerd Created successfully...!");
                //let update the table records
                String sql3 = "UPDATE SAMPLE SET AGE = -1 WHERE NAME = ''Sasha''";
                st.execute(sql3);
                //let print SAMPLE table records
                String sql4 = "SELECT * FROM SAMPLE";
                rs = st.executeQuery(sql4);
                System.out.println("Sample table records after update: ");
                while(rs.next()) {
                    String id = rs.getString("id");
                    String name = rs.getString("name");
                    String age = rs.getString("age");
                    String birth_date = rs.getString("BIRTHDATE");
                    System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Birth_date: " + birth_date);
                }
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    Output

    The output obtained is as shown below −

    Sample table records before update:
    Id: 1, Name: Sasha, Age: 23, Birth_date: 24/06/1999
    Id: 2, Name: Alex, Age: 21, Birth_date: 12/01/2001
    Triggerd Created successfully...!
    java.sql.SQLException: Age Cannot be Negative
    
    import mysql.connector
    # Establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    # Creating a cursor object
    cursorObj = connection.cursor()
    table_name = ''Sample''
    trigger_name = ''after_update_trigger''
    afterUpdate_trigger_query = f''''''CREATE TRIGGER {trigger_name}
    AFTER UPDATE ON {table_name}
    FOR EACH ROW
    BEGIN
    IF NEW.AGE < 0
    THEN SIGNAL SQLSTATE ''45000''
    SET MESSAGE_TEXT = ''Age Cannot be Negative
    END IF;
    END''''''
    cursorObj.execute(afterUpdate_trigger_query)
    print(f"AFTER UPDATE Trigger ''{trigger_name}'' is created successfully.")
    connection.commit()
    # Update the "AGE" column
    update_query = "UPDATE Sample SET AGE = -1 WHERE NAME = ''Sasha''"
    cursorObj.execute(update_query)
    print("Update query executed successfully.")
    # close the cursor and connection
    connection.commit()
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    AFTER UPDATE Trigger ''after_update_trigger'' is created successfully.
    Traceback (most recent call last):
      File "C:UsersLenovoAppDataLocalProgramsPythonPython310libsite-packagesmysqlconnectorconnection_cext.py", line 633, in cmd_query
        self._cmysql.query(
    _mysql_connector.MySQLInterfaceError: Age Cannot be Negative
    
    The above exception was the direct cause of the following exception:
    
    Traceback (most recent call last):
      File "C:UsersLenovoDesktopuntitled.py", line 29, in 
        cursorObj.execute(update_query)
      File "C:UsersLenovoAppDataLocalProgramsPythonPython310libsite-packagesmysqlconnectorcursor_cext.py", line 330, in execute
        result = self._cnx.cmd_query(
      File "C:UsersLenovoAppDataLocalProgramsPythonPython310libsite-packagesmysqlconnectoropentelemetrycontext_propagation.py", line 77, in wrapper
        return method(cnx, *args, **kwargs)
      File "C:UsersLenovoAppDataLocalProgramsPythonPython310libsite-packagesmysqlconnectorconnection_cext.py", line 641, in cmd_query
        raise get_mysql_exception(
    mysql.connector.errors.DatabaseError: 1644 (45000): Age Cannot be Negative
    

    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 – Before Delete Trigger nhận dự án làm có lương

    MySQL – Before Delete Trigger

    Table of content


    In MySQL, a trigger is defined a special stored procedure that resides in the system catalogue, and is executed whenever an event is performed. 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. Triggers are categorized into two types −

    • Before Triggers

    • After Triggers

    These triggers can be a response to either insertion operation on a table, update operation or deletion operation. Thus, these special stored procedures respond whenever INSERT, UPDATE or DELETE statements are executed.

    MySQL Before Delete Trigger

    The Before Delete Trigger is a row-level trigger supported by the MySQL database. The Before Delete Trigger is executed right before a value is deleted from a row of 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.

    With this trigger, whenever a DELETE statement is executed in the database, the value is deleted from a table first followed by execution of the trigger set.

    Syntax

    Following is the syntax to create the BEFORE DELETE trigger in MySQL −

    CREATE TRIGGER trigger_name
    BEFORE DELETE ON table_name FOR EACH ROW
    BEGIN
       -- trigger body
    END;
    

    Example

    In this example, we are creating a table named ”CUSTOMERS”, to demonstrate the BEFORE DELETE trigger on, using the following query −

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

    Insert values into this table created using the following INSERT statements −

    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, ''MP'', 4500.00 ),
    (7, ''Muffy'', 24, ''Indore'', 10000.00 );
    

    Creating Another Table

    Now, let us create another empty table to store all former customers after being deleted from the main table ”CUSTOMERS” −

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

    Using the following CREATE TRIGGER statement, create a new trigger ”before_delete_trigger” on the CUSTOMERS table to delete the customer details from CUSTOMERS table and insert them into another table “OLD_CUSTOMERS” −

    DELIMITER //
    CREATE TRIGGER before_delete_trigger
    BEFORE DELETE ON CUSTOMERS
    FOR EACH ROW
    BEGIN
     INSERT INTO OLD_CUSTOMERS VALUES
     (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY);
    END //
    DELIMITER ;
    

    Delete details of ”old” customers from the CUSTOMERS table using the regular DELETE statement as shown below −

    DELETE FROM CUSTOMERS WHERE ID = 3;
    

    Verification

    To verify whether the details are deleted from the OCUSTOMERS table and added onto the OLD_CUSTOMERS table, let us try to retrieve both of their result-sets using SELECT queries.

    The records in CUSTOMERS table are as follows −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.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

    The records in OLD_CUSTOMERS table are as follows −

    ID NAME AGE ADDRESS SALARY
    3 Kaushik 23 Kota 2000.00

    As you can in the tables above, the data has been deleted from the CUSTOMERS table and added to the OLD_CUSTOMERS table.

    Before Delete Trigger Using Client Program

    We can also execute the Before Delete trigger statement using a client program, instead of SQL queries.

    Syntax

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

    $sql = "CREATE TRIGGER before_delete_trigger BEFORE DELETE ON CUSTOMERS FOR EACH ROW
    BEGIN
    INSERT INTO OLD_CUSTOMERS VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY);
    END";
    $mysqli->query($sql);
    

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

    sql = `CREATE TRIGGER before_delete_trigger BEFORE DELETE ON CUSTOMERS FOR EACH ROW
    BEGIN
    INSERT INTO OLD_CUSTOMERS VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY);
    END`;
    con.query(sql);
    

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

    String sql = "CREATE TRIGGER before_delete_trigger BEFORE DELETE ON CUSTOMERS FOR EACH ROW BEGIN INSERT INTO OLD_CUSTOMERS VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY);
    END";
    statement.execute(sql);
    

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

    beforeDelete_trigger_query = ''CREATE TRIGGER {trigger_name}
    BEFORE DELETE ON {table_name}
    FOR EACH ROW
    BEGIN
    INSERT INTO {another_table} VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY);
    END''
    cursorObj.execute(beforeDelete_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 before_delete_trigger BEFORE DELETE ON CUSTOMERS FOR EACH ROW BEGIN INSERT INTO OLD_CUSTOMERS VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY); END"; if ($mysqli->query($sql)) { printf("Trigger created successfully...!n"); } $q = "DELETE FROM CUSTOMERS WHERE ID = 3"; $result = $mysqli->query($q); if ($result == true) { printf("Delete query executed successfully ...!n"); } $q1 = "SELECT * FROM CUSTOMERS"; $res1 = $mysqli->query($q1); if ($res1->num_rows > 0) { printf("SELECT * FROM CUSTOMERS(verification): n"); while($r1 = $res1->fetch_assoc()){ printf("Id %d, Name: %s, Age: %d, Address %s, Salary %f", $r1[''ID''], $r1["NAME"], $r1[''AGE''], $r1["ADDRESS"], $r1["SALARY"],); printf("n"); } } $q2 = "SELECT * FROM OLD_CUSTOMERS"; $res2 = $mysqli->query($q2); if ($res2->num_rows > 0) { printf("SELECT * FROM OLD_CUSTOMER(verification): n"); while($r1 = $res2->fetch_assoc()){ printf("Id %d, Name: %s, Age: %d, Address %s, Salary %f", $r1[''ID''], $r1["NAME"], $r1[''AGE''], $r1["ADDRESS"], $r1["SALARY"],); printf("n"); } } if ($mysqli->error) { printf("Error message: ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Trigger created successfully...!
    Delete query executed successfully ...!
    SELECT * FROM CUSTOMERS(verification):
    Id 1, Name: Ramesh, Age: 32, Address Ahmedabad, Salary 2000.000000
    Id 2, Name: Khilan, Age: 25, Address Delhi, Salary 1500.000000
    Id 4, Name: Chaitali, Age: 25, Address Mumbai, Salary 6500.000000
    Id 5, Name: Hardik, Age: 27, Address Bhopal, Salary 8500.000000
    Id 6, Name: Komal, Age: 22, Address MP, Salary 4500.000000
    Id 7, Name: Muffy, Age: 24, Address Indore, Salary 10000.000000
    SELECT * FROM OLD_CUSTOMER(verification):
    Id 3, Name: kaushik, Age: 23, Address Kota, Salary 2000.000000
    
    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 before_delete_trigger BEFORE DELETE ON CUSTOMERS FOR EACH ROW
     BEGIN
     INSERT INTO OLD_CUSTOMERS VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY);
     END`;
     con.query(sql);
     console.log("Before delete query executed successfully..!");
     sql = "DELETE FROM CUSTOMERS WHERE ID = 3";
     console.log("Delete query executed successfully...!");
     con.query(sql);
     console.log("Customers table records: ")
     sql = "SELECT * FROM CUSTOMERS";
     con.query(sql, function(err, result){
     if (err) throw err;
     console.log(result);
     console.log(''---------------------------------'');
     console.log(''OLD_CUSTOMERS table records: '')
     });
     sql = "SELECT * FROM OLD_CUSTOMERS";
     con.query(sql, function(err, result){
     if (err) throw err;
     console.log(result);
     });
    });
    

    Output

    The output produced is as follows −

    After delete query executed successfully..!
    Delete query executed successfully...!
    Customers table records:
    [
      {
        ID: 1,
        NAME: ''Ramesh'',
        AGE: 32,
        ADDRESS: ''Ahmedabad'',
        SALARY: ''2000.00''
      },
      {
        ID: 2,
        NAME: ''Khilan'',
        AGE: 25,
        ADDRESS: ''Delhi'',
        SALARY: ''1500.00''
      },
      {
        ID: 4,
        NAME: ''Chaitali'',
        AGE: 25,
        ADDRESS: ''Mumbai'',
        SALARY: ''6500.00''
      },
      {
        ID: 5,
        NAME: ''Hardik'',
        AGE: 27,
        ADDRESS: ''Bhopal'',
        SALARY: ''8500.00''
      },
      { ID: 6, NAME: ''Komal'', AGE: 22, ADDRESS: ''MP'', SALARY: ''4500.00'' },
      {
        ID: 7,
        NAME: ''Muffy'',
        AGE: 24,
        ADDRESS: ''Indore'',
        SALARY: ''10000.00''
      }
    ]
    ---------------------------------
    OLD_CUSTOMERS table records:
    [
      {
        ID: 3,
        NAME: ''kaushik'',
        AGE: 23,
        ADDRESS: ''Kota'',
        SALARY: ''2000.00''
      }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class BeforeDeleteTrigger {
        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...!");
                 //create table
                String sql = "CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS VARCHAR(25), SALARY DECIMAL(18, 2), PRIMARY KEY(ID))";
                st.execute(sql);
                System.out.println("Customers table created successfully...!");
                //lets insert some records into customers table
                String sql1 = "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, ''MP'', 4500.00 ), (7, ''Muffy'', 24, ''Indore'', 10000.00 )";
                st.execute(sql1);
                System.out.println("Records inserted successfully...!");
                //print table records
                String sql2 = "SELECT * FROM CUSTOMERS";
                rs = st.executeQuery(sql2);
                System.out.println("Customers table records: ");
                while(rs.next()) {
                    String id = rs.getString("id");
                    String name = rs.getString("name");
                    String age = rs.getString("age");
                    String address = rs.getString("address");
                    String salary = rs.getString("salary");
                    System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Address: " + address + ", Salary: " + salary);
                }
                //let create one more table named Old_customers
                String sql3 = "CREATE TABLE OLD_CUSTOMERS (ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS VARCHAR(25), SALARY DECIMAL(18, 2), PRIMARY KEY(ID))";
                st.execute(sql3);
                System.out.println("OLD_CUSTOMERS table created successully...!");
                //print the records
                String sql4 = "SELECT * FROM OLD_CUSTOMERS";
                rs = st.executeQuery(sql4);
                System.out.println("OLD_CUSTOMERS table records before delete trigger: ");
                while(rs.next()) {
                    String id = rs.getString("id");
                    String name = rs.getString("name");
                    String age = rs.getString("age");
                    String address = rs.getString("address");
                    String salary = rs.getString("salary");
                    System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Address: " + address + ", Salary: " + salary);
                }
                //lets create trigger on student table
                String sql5 = "CREATE TRIGGER before_delete_trigger BEFORE DELETE ON CUSTOMERS FOR EACH ROW BEGIN INSERT INTO OLD_CUSTOMERS VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY); END";
                st.execute(sql5);
                System.out.println("Triggerd Created successfully...!");
                //lets delete one record from customers table;
                String d_sql = "DELETE FROM CUSTOMERS WHERE ID = 3";
                st.execute(d_sql);
                System.out.println("Record with id = 3 deleted successfully....!");
                //let print OLD_CUSTOMERS table records
                String sql6 = "SELECT * FROM OLD_CUSTOMERS";
                rs = st.executeQuery(sql6);
                System.out.println("OLD_CUSTOMERS records: ");
                while(rs.next()) {
                    String id = rs.getString("id");
                    String name = rs.getString("name");
                    String age = rs.getString("age");
                    String address = rs.getString("address");
                    String salary = rs.getString("salary");
                    System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Address: " + address + ", Salary: " + salary);
                }
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    Output

    The output obtained is as shown below −

    Customers table created successfully...!
    Records inserted successfully...!
    Customers table records:
    Id: 1, Name: Ramesh, Age: 32, Address: Ahmedabad, Salary: 2000.00
    Id: 2, Name: Khilan, Age: 25, Address: Delhi, Salary: 1500.00
    Id: 3, Name: kaushik, Age: 23, Address: Kota, Salary: 2000.00
    Id: 4, Name: Chaitali, Age: 25, Address: Mumbai, Salary: 6500.00
    Id: 5, Name: Hardik, Age: 27, Address: Bhopal, Salary: 8500.00
    Id: 6, Name: Komal, Age: 22, Address: MP, Salary: 4500.00
    Id: 7, Name: Muffy, Age: 24, Address: Indore, Salary: 10000.00
    OLD_CUSTOMERS table created successully...!
    OLD_CUSTOMERS table records before delete trigger:
    Triggerd Created successfully...!
    Record with id = 3 deleted successfully....!
    OLD_CUSTOMERS records:
    Id: 3, Name: kaushik, Age: 23, Address: Kota, Salary: 2000.00
    
    import mysql.connector
    # Establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    # Creating a cursor object
    cursorObj = connection.cursor()
    table_name = ''Customers''
    another_table = ''OLD_CUSTOMERS''
    trigger_name = ''before_delete_trigger''
    beforeDelete_trigger_query = f''''''
    CREATE TRIGGER {trigger_name}
    BEFORE DELETE ON {table_name}
    FOR EACH ROW
    BEGIN
    INSERT INTO {another_table} VALUES (OLD.ID, OLD.NAME, OLD.AGE, OLD.ADDRESS, OLD.SALARY);
    END
    ''''''
    cursorObj.execute(beforeDelete_trigger_query)
    print(f"BEFORE DELETE Trigger ''{trigger_name}'' is created successfully.")
    connection.commit()
    # Delete details of old customer
    delete_query = "DELETE FROM Customers WHERE ID = 3;"
    cursorObj.execute(delete_query)
    print("Delete query executed successfully.")
    # close the cursor and connection
    connection.commit()
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    BEFORE DELETE Trigger ''before_delete_trigger'' is created successfully.
    Delete query executed 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 – Delete Join nhận dự án làm có lương

    MySQL – Delete Join

    Table of content


    Simple deletion operation in MySQL can be performed on a single entity or multiple entities of a table. But what if this deletion operation is to be performed on multiple entities of multiple tables? This is where Joins come into picture.

    MySQL DELETE… JOIN

    As we have discussed in this tutorial previously, Joins are used to retrieve records from two or more tables, by combining columns of these tables based on the common fields. This merged data can be deleted with all the changes reflected in original tables.

    Syntax

    Following is the basic syntax of DELETE… JOIN statement in MySQL −

    DELETE table(s)
    FROM table1 JOIN table2
    ON table1.common_field = table2.common_field;
    

    We can use any join clause (INNER JOIN, LEFT JOIN, RIGHT JOIN etc.) while performing deletion.

    Example

    In this example, we first create a table named CUSTOMERS, which contains the personal details of customers including their name, age, address and salary etc.

    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 insert values into this table using the INSERT statement as follows −

    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);
    

    The table will be created as −

    ID NAME AGE ADDRESS SALARY
    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

    Let us create another table ORDERS, containing the details of orders made and the date they are made on.

    CREATE TABLE ORDERS (
       OID INT NOT NULL,
       DATE VARCHAR (20) NOT NULL,
       CUSTOMER_ID INT NOT NULL,
       AMOUNT DECIMAL (18, 2),
    );
    

    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);
    

    The table is displayed as follows −

    OID DATE CUSTOMER_ID AMOUNT
    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

    The delete operation is performed by applying the DELETE… JOIN query on these tables.

    DELETE a
    FROM CUSTOMERS AS a INNER JOIN ORDERS AS b
    ON a.ID = b.CUSTOMER_ID;
    

    Verification

    To verify if the changes are reflected in the tables, we can use SELECT statement to print the tables.

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    DELETE… JOIN with WHERE Clause

    The ON clause in DELETE… JOIN query is used to apply constraints on the records. In addition to it, we can also use WHERE clause to make the filtration stricter. Observe the query below; here, we are trying to delete the records of customers, in the CUSTOMERS table, whose salary is lower than Rs. 2000.00.

    DELETE a
    FROM CUSTOMERS AS a INNER JOIN ORDERS AS b
    ON a.ID = b.CUSTOMER_ID
    WHERE a.SALARY < 2000.00;
    

    Verification

    To verify whether the changes are reflected in the original tables or not, we will use the SELECT statement.

    The CUSTOMERS table after deletion is as follows −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.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

    Delete Join Using Client Program

    In addition to joining two or more than two tables using the MySQL query, we can also perform the Delete Join operation using a client program.

    Syntax

    To perform Delete Join through a PHP program, we need to execute the DELETE statement with JOIN clause using the mysqli function query() as follows −

    $sql = ''DELETE tutorials_tbl, tcount_tbl FROM tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author
    $mysqli->query($sql);
    

    To perform Delete Join through a JavaScript program, we need to execute the DELETE statement with JOIN clause using the query() function of mysql2 library as follows −

    sql = "DELETE tutorials_tbl, tcount_tbl FROM tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author";
    con.query(sql);
    

    To perform Delete Join through a Java program, we need to execute the DELETE statement with JOIN clause using the JDBC function executeUpdate() as follows −

    String sql = "DELETE tutorials_tbl, tcount_tbl FROM tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author";
    statement.executeUpdate(sql);
    

    To perform Delete Join through a python program, we need to execute the DELETE statement with JOIN clause using the execute() function of the MySQL Connector/Python as follows −

    delete_join_query = "DELETE a FROM CUSTOMERS AS a INNER JOIN ORDERS AS b ON a.ID = b.CUST_ID"
    cursorObj.execute(delete_join_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 = ''DELETE tutorials_tbl, tcount_tbl FROM tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author if ($mysqli->query($sql)) { printf("Join deleted successfully!.
    "); } if ($mysqli->errno) { printf("Join could not be deleted !.
    ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Join deleted 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);
    
      //Delete Join
      sql = "DELETE tutorials_tbl, tcount_tbl FROM tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author";
      con.query(sql, function (err, result) {
        if (err) throw err;
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    ResultSetHeader {
      fieldCount: 0,
      affectedRows: 2,
      insertId: 0,
      info: '''',
      serverStatus: 34,
      warningStatus: 0,
      changedRows: 0
    }
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class DeleteJoin {
       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...!");
    
             //MySQL Delete JOIN...!;
             String sql = "DELETE tutorials_tbl, tcount_tbl FROM tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author";
             statement.executeUpdate(sql);
             System.out.println("JOIN Deleted successfully...!");
             connection.close();
          } catch (Exception e) {
             System.out.println(e);
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Connected successfully...!
    JOIN Deleted successfully...!
    
    import mysql.connector
    #establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    cursorObj = connection.cursor()
    delete_join_query = f"""DELETE a FROM CUSTOMERS AS a INNER JOIN ORDERS AS b ON a.ID = b.CUST_ID"""
    cursorObj.execute(delete_join_query)
    connection.commit()
    print("deleted succesfully")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    deleted 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 – Unique Key nhận dự án làm có lương

    MySQL – Unique Key

    Table of content


    A Unique Key in MySQL, when applied on a certain field of a database table, does not allow duplicate values to be inserted in that column, i.e. it is used to uniquely identify a record in a table.

    Usually, any relational database contains a lot of information stored in multiple tables and each table holds a huge number of records. When we are handling such huge amounts of data there is a chance of redundancy (duplicate records). SQL keys are a way to handle this issue.

    This Unique Key works as an alternative to the Primary Key constraint; as both unique and primary keys assure uniqueness in a column of a database table.

    Creating MySQL Unique Key

    We can create a Unique Key on a MySQL table column using the UNIQUE keyword, and it holds the following features −

    • Even though unique key is similar to the primary key in a table, it can accept a single NULL value unlike the primary key.
    • It cannot have duplicate values.
    • It can also be used as a foreign key in another table.
    • A table can have more than one Unique column.

    Syntax

    Following is the syntax to create a UNIQUE key constraint on a column in a table −

    CREATE TABLE table_name(
       column_name1 datatype UNIQUE,
       column_name2 datatype,
       ...
    );
    

    As you observe, we just need to specify the keyword UNIQUE after the name of the desired column while creating a table using CREATE TABLE statement.

    Example

    In this example, let us create a table named CUSTOMERS and define a UNIQUE Key on one of its fields, ADDRESS. Look at the following query −

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

    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 UNI NULL
    SALARY decimal(18, 2) YES NULL

    As you can see in the table definition, the Unique Key is created on the ADDRESS field.

    Creating Multiple Unique Keys

    We can create one or more Unique Key constraints on a column in a single MySQL table. When this constraint is applied in multiple fields, one cannot insert duplicate values in those fields.

    Syntax

    Following is the syntax to create unique key constraints on multiple columns in a table −

    CREATE TABLE table_name(column_name1 UNIQUE, column_name2 UNIQUE,...)
    

    Example

    Assume we have created another table with the name CUSTOMERS in the MySQL database using CREATE TABLE statement.

    Here we are creating a UNIQUE constraint on columns NAME and ADDRESS using the UNIQUE keyword as shown below −

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

    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 UNI NULL
    AGE int NO NULL
    ADDRESS char(25) YES UNI NULL
    SALARY decimal(18, 2) YES NULL

    Creating Unique Key on Existing Columns

    We can add a unique key constraint on an existing column of a table using the ALTER TABLE… ADD CONSTRAINT statement.

    Syntax

    Following is the syntax to create a UNIQUE Key on existing columns of a table −

    ALTER TABLE table_name
    ADD CONSTRAINT unique_key_name
    UNIQUE (column_name);
    

    Note − Here the UNIQUE_KEY_NAME is just the name of the Unique Key. It is optional to specify the name while creating a unique key. It is used to drop the constraint from the column in a table.

    Example

    Using the ALTER TABLE statement, you can add a UNIQUE constraint on any existing column in the CUSTOMERS table created previously. In the following example, we are applying the UNIQUE constraint on the NAME column as shown below −

    ALTER TABLE CUSTOMERS
    ADD CONSTRAINT UNIQUE_NAME
    UNIQUE (NAME);
    

    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 UNI NULL
    AGE int NO NULL
    ADDRESS char(25) YES NULL
    SALARY decimal(18, 2) YES NULL

    Dropping MySQL Unique Key

    If there is an unique constraint on a column already, you can drop it whenever it is not needed. To drop the Unique Constraint from the column of a table you need to use the ALTER TABLE statement again.

    Syntax

    Following is the SQL query to drop the UNIQUE constraint from the column of a table −

    ALTER TABLE TABLE_NAME DROP CONSTRAINT UNIQUE_KEY_NAME;
    

    Example

    In this example, we will drop the constraint named UNIQUE_NAME from the column NAME of the CUSTOMERS table using the following MySQL query −

    ALTER TABLE CUSTOMERS DROP CONSTRAINT UNIQUE_NAME;
    

    Output

    The table structure displayed will contain a UNI index only on the ADDRESS column, referring that the index on NAME column is removed.

    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 Unique Key Using Client Program

    In addition to use a key on a column to identify uniquely using the MySQL query We can also apply a Unique Key constraint on a Field using a client program.

    Syntax

    To apply unique key on a table field through a PHP program, we need to execute the CREATE TABLE statement with the UNIQUE keyword using the mysqli function query() as follows −

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

    To apply unique key on a table field through a JavaScript program, we need to execute the CREATE TABLE statement with the UNIQUE keyword using the query() function of mysql2 library as follows −

    sql = "CREATE TABLE customers(cust_ID INT NOT NULL, cust_Name VARCHAR(30), cust_login_ID INT AUTO_INCREMENT, PRIMARY KEY(cust_login_ID))";
    con.query(sql);
    

    To apply unique key on a table field through a Java program, we need to execute the CREATE TABLE statement with the UNIQUE keyword using the JDBC function execute() as follows −

    String sql = "CREATE TABLE customers(Cust_ID INT NOT NULL UNIQUE, Cust_Name VARCHAR(30))";
    statement.execute(sql);
    

    To apply unique key on a table field through a python program, we need to execute the CREATE TABLE statement with the UNIQUE keyword using the execute() function of the MySQL Connector/Python as follows −

    unique_key_query = ''CREATE TABLE TEST1 (ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, MOBILE BIGINT UNIQUE, AADHAR BIGINT UNIQUE, AGE INT NOT NULL)''
    cursorObj.execute(unique_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)) if ($mysqli->query($sql)) { echo "Unique 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 −

    Unique 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 stores primary key!
      sql = "CREATE TABLE customers(cust_ID INT NOT NULL, cust_Name VARCHAR(30), cust_login_ID INT AUTO_INCREMENT, PRIMARY KEY(cust_login_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 UniqueKey {
       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 unique key in the customer table...!;
             String sql = "CREATE TABLE customers(Cust_ID INT NOT NULL UNIQUE, Cust_Name VARCHAR(30))";
             statement.execute(sql);
             System.out.println("Unique 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...!
    Unique key created successfully...!
    Cust_ID int NO PRI null
    Cust_Name varchar(30) YES  null
    
    import mysql.connector
    #establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    cursorObj = connection.cursor()
    # Create table
    unique_key_query = ''CREATE TABLE TEST1 (ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, MOBILE BIGINT UNIQUE, AADHAR BIGINT UNIQUE, AGE INT NOT NULL)''
    cursorObj.execute(unique_key_query)
    connection.commit()
    print("Unique key column is created successfully!")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Unique 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

  • 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 – 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 – 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 – 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