Teachnique
      CourseRoadmaps
      Login

      HomeIntroductionFeaturesVersionsVariablesInstallationAdministrationPHP SyntaxNode.js SyntaxJava SyntaxPython SyntaxConnectionWorkbench

      Create DatabaseDrop DatabaseSelect DatabaseShow DatabaseCopy DatabaseDatabase ExportDatabase ImportDatabase Info

      Create UsersDrop UsersShow UsersChange PasswordGrant PrivilegesShow PrivilegesRevoke PrivilegesLock User AccountUnlock User Account

      Create TablesShow TablesAlter TablesRename TablesClone TablesTruncate TablesTemporary TablesRepair TablesDescribe TablesAdd/Delete ColumnsShow ColumnsRename ColumnsTable LockingDrop TablesDerived Tables

      QueriesConstraintsInsert QuerySelect QueryUpdate QueryDelete QueryReplace QueryInsert IgnoreInsert on Duplicate Key UpdateInsert Into Select

      Create ViewsUpdate ViewsDrop ViewsRename Views

      IndexesCreate IndexDrop IndexShow IndexesUnique IndexClustered IndexNon-Clustered Index

      Where ClauseLimit ClauseDistinct ClauseOrder By ClauseGroup By ClauseHaving ClauseAND OperatorOR OperatorLike OperatorIN OperatorANY OperatorEXISTS OperatorNOT OperatorNOT EQUAL OperatorIS NULL OperatorIS NOT NULL OperatorBetween OperatorUNION OperatorUNION vs UNION ALLMINUS OperatorINTERSECT OperatorINTERVAL Operator

      Using JoinsInner JoinLeft JoinRight JoinCross JoinFull JoinSelf JoinDelete JoinUpdate JoinUnion vs Join

      Unique KeyPrimary KeyForeign KeyComposite KeyAlternate Key

      TriggersCreate TriggerShow TriggerDrop TriggerBefore Insert TriggerAfter Insert TriggerBefore Update TriggerAfter Update TriggerBefore Delete TriggerAfter Delete Trigger

      Data TypesVARCHARBOOLEANENUMDECIMALINTFLOATBITTINYINTBLOBSET

      Regular ExpressionsRLIKE OperatorNOT LIKE OperatorNOT REGEXP Operatorregexp_instr() Functionregexp_like() Functionregexp_replace() Functionregexp_substr() Function

      Fulltext SearchNatural Language Fulltext SearchBoolean Fulltext SearchQuery Expansion Fulltext Searchngram Fulltext Parser

      Date and Time FunctionsArithmetic OperatorsNumeric FunctionsString FunctionsAggregate Functions

      NULL ValuesTransactionsUsing SequencesHandling DuplicatesSQL InjectionSubQueryCommentsCheck ConstraintsStorage EnginesExport Table into CSV FileImport CSV File into DatabaseUUIDCommon Table ExpressionsOn Delete CascadeUpsertHorizontal PartitioningVertical PartitioningCursorStored FunctionsSignalResignalCharacter SetCollationWildcardsAliasROLLUPToday DateLiteralsStored ProcedureExplainJSONStandard DeviationFind Duplicate RecordsDelete Duplicate RecordsSelect Random RecordsShow ProcesslistChange Column TypeReset Auto-IncrementCoalesce() Function

      Useful FunctionsStatements ReferenceQuick GuideUseful ResourcesDiscussion

      Feedback

      Submit request if you have any questions.

      Course
      After Update Trigger

      MySQL Tutorial

      This SQL tutorial is structured for beginners to guide them from the foundational concepts to advanced data manipulation and querying techniques in SQL. By the end of this tutorial, you will have developed a robust understanding of SQL, equipping you with the knowledge to efficiently manage and analyze data across various database systems. This guide sets the stage for your growth into a skilled data professional, ready to tackle complex data challenges and contribute to the field of data analysis and database management.

      After Update Trigger

      A Trigger is simply defined as a response to an event. In MySQL, a trigger is a special stored procedure that resides in the system catalogue, 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

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

      Example

      Following are the programs −
      PHPNodeJSJavaPython
      $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