Вы находитесь на странице: 1из 11

Simple Queries in MySql

Data Types:
Numeric: INT(M), TINYINT, SMALLINT, MEDIUMINT, BIGINT
FLOAT(M,D), DECIMAL(M,D), DOUBLE(M,D)
Date and Time: DATE, DATETIME
String / Text: CHAR(L), VARCHAR(L), BLOB or TEXT, ENUM

Difference between Char and Varchar datatypes:


VAR is a fixed length field while VARCHAR is a variable length field. It means if we declare
Name VAR(n)  if a value in the field is shorter than the length ‘n’ then blanks are added but
the size of value remains n bytes. While if we decalare it as:
Name VARCHAR(n)  if a value in the field is shorter than the length ‘n’ then blanks are not
added and the size of value is the actual size.
If we declare :  Name CHAR(20) and Name VARCHAR(20) and stores the value “Shubham” in this field
then CHAR(20) will occupy 20 bytes of memory while VARCHAR(20) will occupy only 7 bytes of memory.

Comments: Anything written inside /* */ is a comment. A comment is a text that is not executed and it
is only for the documentation purpose.

Open a database: USE Ex.  USE employee;  it will open the database name employee
To create a database: CREATE DATABASE employee;  it will create a database employee
To see existing databases:  SHOW DATABASES;  will display the names of existing MySql databases
in our system
To see the tables in the database  SHOW TABLES;  will display the names of all tables in the current
database

To see the structure of table:  DESC or DESCRIBE


Ex. DESC empl;  it will display the structure of the table EMPL
To see the CREATE TABLE command of any table :  SHOW CREATE TABLE <tablename>
Ex. SHOW CREATE TABLE empl;  it will display create table command
Simple Queries:
To display the complete table  SELECT * FROM tablename;
Ex.  SELECT * FROM student;
To display only specific columns  SELECT colname1, colname2, …..
FROM tablename;
Ex.  SELECT empno, empname, sal
FROM empl;
Eliminating Redundant (Duplicate) Data  DISTINCT
Ex.  SELECT DISTINCT JOB FROM EMPL;  It will display the different types of JOB.
(If there are repeated values in the column, it will not be repeated in the display)
Performing Simple Calculations:  SELECT 5*10 ;  will display 50
SELECT CURDATE( );  will display the current date as 2013-09-03
Scalar Expressions with Selected Fields:
Ex. SELECT ENAME, SAL +1000 FROM EMPL;
It will display the salary with an addition of 1000 but it will not change the salary in the table.
Using Column Alias (Another name):
Ex. SELECT ENAME, SAL + 100 AS ‘NEW SALARY’ FROM EMPL;
Or
SELECT ENAME, SAL + 100 ‘NEW SALARY’ FROM EMPL;
Here we have change the column name of SAL+1000 as NEW SALARY.
Handling Nulls:  IFNULL(<columnname>, substituted value)
Ex. SELECT ENAME, SAL, IFNULL(COMM , ‘NOT ELINGIBLE’) FROM EMPL;
(Here all the NULL values in the column COMM will be displayed as ‘NOT ELIGIBLE’ in the result)
Putting Text in the Query Output: Whatever the text we want to put in each record, we write it as column
name in single or double quotes.
Ex. SELECT ENAME, “GETS RS.” , SAL FROM EMPL;  will produce the following output
ENAME GETS RS. SAL
SMITH GETS RS. 800
MOMIN GETS RS. 1250

Selecting Specific Rows (Filtering Records)  WHERE clause


WHERE clause can be used with:
1. Relational Operators  > , < , >=, <=, <> ( not equals to )
SELECT * FROM EMPL WHERE SAL >= 2000;
SELECT * FROM EMPL WHERE JOB < > ‘SALESMAN’;

2. Logical Operators  AND , OR, NOT ( NOT is used before column name)
SELECT * FROM EMPL WHERE JOB = ‘SALESMAN’ OR JOB = ‘CLERK’;
SELECT * FROM EMPL WHERE NOT DEPT = 10;  see here, NOT appear before the column name

3. Range Operator  BETWEEN, NOT BETWEEN (this operator includes both lower value and upper
value)
SELECT * FROM EMPL WHERE SAL BETWEEN 1500 AND 2500;
(both 1500 and 2500 are included)
SELECT * FROM EMPL WHERE SAL NOT BETWEEN 1500 AND 2500;

4. List Operator  IN , NOT IN


SELECT * FROM EMPL WHERE DEPTNO IN(10,20,30);
SELECT * FROM EMPL WHERE JOB NOT IN(‘CLERK’,’SALESMAN’,’MANAGER’);

5. Pattern Matching  LIKE ( is used without = sign and uses two wildcards _ and %. _ can replace any
one character and it must be compulsory while % can replace any substring or no string)
SELECT * FROM EMPL WHERE ENAME LIKE ‘_ _ _ M%’;  see here, = sign is not used
(It will display the records where the 4th character of employee name is M)
SELECT ENAME FROM EMPL WHERE ENAME LIKE ‘_ _ _ M’;
(It will display the names of employees which have 4 characters in their names and 4 th character is M)
SELECT ENAME FROM EMPL WHERE ENAME LIKE ‘M%’;
(It will display the names of all employees whose name starts with M)
SELECT ENAME FROM EMPL WHERE ENAME NOT LIKE ‘%M’;
(It will display the names of all employees whose name does not end with M)
6. Searching for NULL  IS NULL , IS NOT NULL (we don’t use = sign when searching NULLs)
SELECT * FROM EMPL WHERE COMM IS NULL;  see here, = sign is not used
SELECT * FROM EMPL WHERE COMM IS NOT NULL;

Sorting the Results (Arranging the result into ascending or descending order using any column):
ODER BY clause  SELECT * FROM EMPL ORDER BY ENAME DESC;
(Will display the result in descending order using the column ENAME)
SELECT * FROM EMPL ORDER BY SAL;
(Will display the result in ascending order using the column SAL)
SELECT * FROM EMPL ORDER BY JOB,ENAME DESC;
(Will display the result in ascending order of JOB and the same JOB group will be
arranged in descending order by using ENAME)
SELECT EMPNO, ENAME AS NAME FROM EMPL ORDER BY NAME;  sorted using alias (NAME)
Scalar Expressions with Selected Fields:
SELECT ename, salary+Salary*.15
FROM Employee;
This command will not change the salary but will display the result as per calculation given in query. The
column name will be as given Salary+Salary*.15
Using Column Alias (Using captions or another names for the salary): The alias is a temporary and another
name given to the column or table in a particular query
Ex. SELECT ename, salary+Salary*.15 as ‘Increased Salary’
FROM Employee;
Now the column name displayed for Salary+Salry*.15 will be ‘Increased Salary’
Aggregate (Group Functions) Functions: Aggregate or group functions work upon groups of rows, rather
than on single rows. Aggregate functions always returns a single value for a group or table.
Various Aggregate Functions:
(i) AVG( ) (ii) SUM( ) (iii) MIN( ) (iv) MAX (v) COUNT( ) (vi) COUNT(*)
Count(*): It counts the number of rows in the table. It condition is given then it counts the number of rows
fulfilling the WHERE condition. It returns numeric value.
Count(column_name): It does not count the NULL values in the column. It returns the number of NOT NULL
values in the column.
Ex.
Salary SELECT Count(*) FROM EMP; will return 6
1200 SELECT Count(Salary) FROM EMP; will return 4
1300 SELECT AVG(Salary) FROM EMP; will return 1400
NULL SELECT SUM(Salary) FROM EMP; will return 5600
1500 SELECT MIN(Salary) FROM EMP; will return 1200
NULL SELECT MAX(Salary) FROM EMP; will return 1600
1600
Note: AVG( ) will consider only NOT NULL values so in the above example ie. 5600/4 = 1400
GROUP BY Clause: The GROUP BY clause combines all those records that have identical values in a
particular field or group of fields. The GROUP BY clause is used in SELECT statement to divide the table into
groups. Grouping can be done by a column name, or with aggregate function in which case the aggregate
function produces a single value for each group.
Note(Important):
Grouping can be done using a column having identical values.
Whenever we use GROUP BY clause, the column names which can appear after SELECT can be:
 A column using which we have done the grouping
 Aggregate functions
Ex.
EMPNO EName JOB MGR HIREDATE Salary COMM DEPTNO
---------- ------------- --------- ---------- --------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
To count the number of employees in each type of job, the query will be:

SELECT JOB,COUNT(JOB)
FROM EMOLOYEE Notice the column names used after
GROUP BY JOB; SELECT are
1. Group Column Name
To find out the average salary and sum salary of those 2. Aggregate Functions
Employees having ‘A’ in their name in each
department, we can write the query as:

SELECT DEPTNO, AVG(SAL), SUM(SAL)


FROM EMPLOYEE
WHERE ENAME LIKE ‘%A%’
GROUP BY DEPTNO;

Result:

JOB COUNT(JOB) DEPTNO AVG(SAL) SUM(SAL)


CLERK 4 10 2450 2450
SALESMAN 4 20 1100 1100
MANAGER 3 30 1575 6300
ANALYST 2
PRESIDENT 1

HAVING Clause (Placing conditions on Group): is used to put conditions on group or to filter the records
from a group made using GROUP BY clause.
Difference between WHERE and HAVING clause:
 The HAVING Clause puts conditions on groups in contrast to WHERE clause that places conditions on
individual rows.
 WHERE conditions cannot include aggregate functions while HAVING can include aggregate functions
Ex. If we write the above query as:
SELECT JOB,COUNT(JOB) JOB COUNT(JOB)
Will produce the result CLERK 4
FROM EMOLOYEE
GROUP BY JOB SALESMAN 4
HAVING COUNT(JOB) > 2; MANAGER 3

Note: Compare the result with the previous query result, you will observe that the ANALYST and PRESIDENT
groups has been remove because of HAVING clause.

Note: We can use an aggregate function in the HAVING clause even if it is not in the SELECT list.
Ex.
SELECT JOB,SUM(SALARY) See we have used COUNT(JOB)>2 in
FROM EMOLOYEE the HAVING clause which does not
GROUP BY JOB exist in the SELECT list
HAVING COUNT(JOB) > 2;
JOINS
Join: A join is a query that combines rows from two or more than two tables. In a join query, more than one
table are listed in FROM clause separated by comma or named/unnamed JOIN keyword.
Ex.
SELECT * FROM EMPL, DEPT;  This query will give us the Cartesian Product of these two tables

Qualified name: Qualified names are very useful in identifying a field (column) if the two joining tables have
columns/fields with same name. Qualified name is like  tablename.fieldname
Ex. Employee. Empid, dept.deptid, student.regno etc.

Using Table Alias: A table alias is a temporary label given along with table name in FROM clause. This alias
can be used in that proper query instead of the table name.
Ex. SELECT E.deptno, dname, empno, job, sal
FROM empl E, dept D  E and D are temporary names given to empl and dept table
WHERE E.deptno = D.deptno;  Here E and D are used instead of actual table names
(to cut down on the amount of typing required in queries we can use aliases for table name in SELECT and
WHERE clauses)
Types of Joins:
EQUI Join: The join, in which the columns are compared for equality, is called equi-join.
Ex. SELECT EMPL.EMPNO, NAME, SAL, DEPT, DEPTNAME
FROM EMPL, DEPT
WHERE EMPL.EMPNO = DEPT.EMPNO;  the two columns are compared for equality
OR
SELECT EMPL.EMPNO, NAME, SAL, DEPT, DEPTNAME
FROM EMPL JOIN DEPT
ON(EMPL.EMPNO=DEPT.EMPNO);  the two columns are compared for equality
NON-EQUI Join: Join in which tables are compared for some relationship other than equality.
SELECT EMPL.EMPNO, NAME, SAL, DEPT, DEPTNAME
FROM EMPL, DEPT
WHERE NAME LIKE ‘%A’;  the two columns are not compared for equality
NATURAL Join: The join in which one of the identical columns (coming from joined table) exists, is called
Natural Join. i.e. Equi Join – One of the identical column = Natural Join
SELECT EMPL.EMPNO, NAME, SAL, DEPT, DEPTNAME
FROM EMPL NATURAL JOIN DEPT;  using NATURAL JOIN keyword
CROSS Join: The cross (or Cartesian Product) is a very basic type of join that simply matches each row from
one table to every row from another table.
SELECT EMPNO, NAME, SAL, DEPT, DEPTNAME
FROM EMPL , DEPT;  simplest form without join condition
Or
SELECT EMPNO, NAME, SAL, DEPT, DEPTNAME
FROM EMPL JOIN DEPT;  if we don’t name the join type and no equijoin
Or
SELECT EMPNO, NAME, SAL, DEPT, DEPTNAME
FROM EMPL CORSS JOIN DEPT;  using CROSS JOIN keyword

LEFT Join: The join in which all rows from the first table will be returned whether there are matches in the
second table or not. For unmatched rows of the first table, NULL is shown in columns of the second table.
SELECT EMPL.EMPNO, NAME, SAL, DEPT, DEPTNAME
FROM EMPL LEFT JOIN DEPT
ON(EMPL.EMPID=DEPT.EMPLID);
RIGHT Join: Is just reverse of LEFT join. In RIGHT join, all rows from the second table will be returned
whether there are matches in the first table or not. For unmatched rows of the second table, NULL is shown in
columns of the first table.
SELECT EMPL.EMPNO, NAME, SAL, DEPT, DEPTNAME
FROM EMPL RIGHT JOIN DEPT
ON(EMPL.EMPID=DEPT.EMPLID);

DDL (Data Definition Language Commands)


1. CREATE TABLE 2. DROP TABLE 3. ALTER TABLE 4. DROP VIEW
CREATE TABLE command:
Syntax: Example:
CREATE TABLE tablename CREATE TABLE employee
( (
Columnname datatype constraint(s), EmpId INTEGER(4) PRIMARY KEY,
Columnname datatype constraint(s), EName VARCHAR(20) NOT NULL,
Columnname datatype constraint(s), Salary DECIMAL(7,2),
Columnname datatype constraint(s) Age INTEGER(2) CHECK(AGE>18),
); Sex CHAR(1) DEFAULT ‘M’
);

Constraint: A constraint is a condition or check applicable on a field or set of fields.


Integrity Constraints: are the rules that a database must comply at all times. Integrity constraints determine
what all changes/insertions are permissible to a database. Integrity constraints can be laid on a table while
creating it using CREATE TABLE command or while altering the table using ALTER table command.
Constraints are of two types:
Column Level Constraints/Inline Constraints: applied on individual columns of a table separately. It is
applied while defining the column.
Table Level Constraints: When a constraint is applied on a group of columns of the table, it is called table
constraint. It is applied after defining all the columns in a table.
Some Constraints are given below:
(1) Primary Key (2) UNIQUE (3) NOT NULL (4) DEFAULT (5) CHECK (6) FOREIGN KEY
How to apply constraints:
Example:
Example: CREATE TABLE employee
CREATE TABLE employee (
( EmpId INTEGER(4),
EmpId INTEGER(4) PRIMARY KEY, EName VARCHAR(20) NOT NULL, Column level Constraint
EName VARCHAR(20) NOT NULL, Salary DECIMAL(7,2), Column level Constraint
Salary DECIMAL(7,2), Age INTEGER(2),
Age INTEGER(2) CHECK(AGE>18), Sex CHAR(1) DEFAULT ‘M’,
Sex CHAR(1) DEFAULT ‘M’ PRIMARY KEY(EmpId), Table level Constraint
); CHECK (Salary<5000.00)
); Table level Constraint

See in the above examples, Primary Key has been applied on the table as Column Level constraint as well as
Table Level constraint respectively.

Foreign Key: A Foreign key is a non-key column of a table(child table) that draws its values from primary
key(or unique key) of another table(called parent table).
 The table in which a foreign key is defined is called a referencing table or child table.
 A table to which a foreign key points is called a referenced table or parent table.
Implementing Foreign Key Constraint:
Suppose there are three tables name ITEM, SALES and Customer as given below:
Table: Item
ItemCode Itemname Manufacturer Price Quantity
101 Soap Lux 42.25 100g
102 Shampoo Sunsilk 62.52 150ml ItemCode is
103 Fairness Cream Fair & Lovely 49.25 50g Primary Key
104 Rice Lal Kila 85.65 1Kg
105 Noodles Maggi 22.11 400g
106 Detergent Tide 105.45 500g
Table: Sales
SalesID ItemCode Qty_Sold Customer_ID SalesID is Primary Key
1 101 2 1001
2 105 1 1002 ItemCode is Foreign Key pointing to
3 106 5 1001 Item(ItemCode)
4 102 4 1003
5 101 3 1004 Customer_ID is Foreign Key
6 101 2 1005 pointing to Customer(Cusomter_ID)
Table: Customer
Customer_ID Name City Contact
1001 Subhash Ajmer 9985288952
1002 Vinjay Jaipur 9985688745 Customer_ID is Primary Key
1003 Kartik Jodhpur 8874545214
1004 Somya Jaipur 9985612548
1005 Shabbir Udaipur 7785412365

1. Defining Foreign Key Using Column Level Constraint:

CREATE TABLE Sales


(
SalesID INT(3) Primary Key,
ItemCode INT(4) REFERENCES Item( ItemCode ),
Qty_Sold INT(2),
Customer_ID INT(5) REFERENCES Customer(Customer_ID)
);

2. Defining Foreign Key Using Table Level Constraint:


CREATE TABLE Sales
(
SalesID INT(3) Primary Key,
ItemCode INT(4),
Qty_Sold INT(2),
Customer_ID INT(5),
FOREIGN KEY (ItemCode) REFERENCES Item (ItemCode)
ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (Customer_ID) REFERENCES Customer Customer_ID)
ON DELETE CASCADE ON UPDATE CASCADE
);
3. Defining Foreign Key Using Table Level Constraint Names (Naming Constraints):
CREATE TABLE Sales
(
SalesID INT(3) Primary Key,
ItemCode INT(4),
Qty_Sold INT(2),
Customer_ID INT(5),
CONSTRAINT fkey_1 FOREIGN KEY (ItemCode) REFERENCES Item (ItemCode)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fkey_2 FOREIGN KEY (Customer_ID) REFERENCES Customer Customer_ID)
ON DELETE CASCADE ON UPDATE CASCADE
);

Self Referencing Table: The referenced and referential table associated with a foreign key may be the same.
Such table is called a self-referential table and this is known as self-referential integrity.

The following rules are applied when a foreign key is specified:


1. The referenced (parent) table must already have been created or it will be a self-reference.
2. A primary key must be defined for the referenced (parent) table.
3. A null value is permitted in foreign key, although a primary key can never contain null values.
4. The number of columns in the foreign key must be the same as the number of columns in the primary
key (or unique key) of the referenced (parent) table. (i.e. in case of composite key)
5. The data types of the columns in the foreign key must match those of the corresponding columns in the
primary key of the referenced (parent) table.

ALTER TABLE Command: Used to change the definition of the existing table. Using ALTER TABLE
command we can:
1. Add new column to a table [ADD COLUMN]
2. Drop a column from the existing table [DROP COLUMN]
3. Modify column-definition of a table[MODIFY / CHANGE]
4. Add constraints to a table [ADD CONSTRAINT]
5. Drop constraints from a table [DROP CONSTRAINT]
6. Enable / Disable constraints of a table [SET]

Add Column to a table:


To add a new column COMPANY in the above table ITEM with data type varchar(30) containing not null
constraint, the query will be:
ALTER TABLE ITEM
ADD COLUMN COMPANY VARCHAR(30) NOT NULL;

Drop a column:
To drop a column named COMPANY from the table item.
ALTER TABLE ITEM
DROP COLUMN COMPANY;

Modify column definition:


In a PLAYERS table, to increase the length of the CITY column from 30 to 40 and make it NOT NULL.
ALTER TABLE PLAYERS
CHANGE CITY CITY VARCHAR(40) NOT NULL; Notice: When we use CHANGE clause the column
Or name comes twice (i.e. old column name and new
ALTER TABLE PLAYERS column name) but when we use MODIFY clause only
MODIFY CITY VARCHAR(40) NOT NULL; the column name comes once.
Basically CHANGE clause is used to change the column name.
Ex. In a PLAYERS table, to change the name of the column CITY to ADDRESS we can write the query.
ALTER TABLE PLAYERS
CHANGE CITY ADDRESS VARCHAR(40) NOT NULL;

Note: Both MODIFY and CHANGE allow you to make changes in column definition, but there is a slight
difference between the two:
 With CHANGE clause, you always need to specify the name of the column twice.
 With MODIFY clause, you cannot change the name of the column whereas with CHANGE, you can do
so.

Add constraints to a table:


Adding Primary Key constraint to a table:
ALTER TABLE EMP
ADD PRIMARY KEY(EMPID);
Or
ALTER TABLE EMP
ADD CONSTRAINT PRIMARY KEY(EMPID);
Or This is a named constraint and the
ALTER TABLE EMP name of the constraint is pk_1.
ADD CONSTRAINT pk_1 PRIMARY KEY(EMPID);

Adding Foreign Key Constraint to a table:


To make SALES(ITEMNO) as foreign key referencing to the ITEM(ITEMNO)
ALTER TABLE SALES
ADD CONSTRAINT FOREIGN KEY(ITEMNO) REFERENCES ITEM(ITEMNO);
Or
ALTER TABLE SALES
ADD CONSTRAINT fk_1 FOREIGN KEY(ITEMNO) REFERENCES ITEM(ITEMNO);
This is a named constraint and the
Removing Constraints: name of the constraint is fk_1.
To Remove Primary Key constraint:
ALTER TABLE EMP
DROP PRIMARY KEY;
To Remove Foreign Key Constraint:
ALTER TABLE EMP
DROP FOREIGN KEY fk_1;

To view the constraints and their columns:  SHOW CREATE TABLE <tablename>;
Ex. SHOW CREATE TABLE empl;
To enable/disable constraints:  We cannot disable the Primary Key constraint but we can drop it. Foreign
key constraint can be enabled or disabled using:
SET FOREIGN_KEY_CHECKS = 0 ;  to disable it
SET FOREIGN_KEY_CHECKS = 1 ;  to enable it

Dropping tables:
DROP TABLE EMPL;
Or
DROP TABLE IF EXISTS EMPL;
Once this command is executed, the table name no longer recognized and no more command can be given on
that table (object).
TCL (Transaction Control Language)
Transaction: A transaction is a logical unit of work (LUW) that must succeed or fail in it entirely. A
transaction is an atomic operation which may not be divided into smaller operations.

Transaction Properties (ACID properties):


Atomicity(ALL-OR-NONE concept): This property ensures that either all operations of the transaction are
reflected properly in the database or none are. Atomicity ensures either all-or-none operations of a transaction
are carried out. This property has two states: Done or Never-Started.
Consistency: The property implies that if the database was in a consistent state before the start of the
transaction-execution, then upon termination of transaction, the database must also be in a consistent state.
Isolation: This property implies that each transaction is unaware of other transactions executing concurrently
(simultaneously) in the system. It indicates that the actions performed by the transactions will be isolated or
hidden from the outside the transaction utile the transaction terminates. This property makes a transaction
relatively independent.
Durability: This property of a transaction ensure that after the successful completion of a transaction (i.e. when
a transaction is COMMITed) the changes made by it to the database persists (i.e. remain in the database), even
if there are system failures. The permanence of COMMIT action of a transaction requires that any failure after
COMMIT, must not cause loss of updates (data changes) made by the transaction.

Transaction Control Commands:


1) BEGIN / BEGIN WORK / START TRANSACTION
2) COMMIT / COMMIT WORK
3) ROLLBACK
4) SAVEPOINT
5) SET AUTOCOMMIT

Note: (Important Points)


 A Transaction ends with COMMIT or ROLLBACK command.
 If we don’t start a transaction using BEGIN or START TRANSACTION commands (i.e. implicit start),
all the commands are automatically committed. (i.e. auto commit)
 With START TRANSACTION / BEGIN, auto-commit remains disabled until we end the transaction
with COMMIT or ROLLBACK.
 If we are in a middle of a current transaction, and a START TRANSACTION / BEGIN or a DDL
command is executed, the current transaction will be committed and ended.

COMMIT:
 Is used to end a transaction and to make all changes permanent in the database.
 COMMIT also releases any locks acquired by the transaction.
ROLLBACK:
 Is used to end a transaction and undo the work done by that transaction.
 It cancels the entire transaction i.e. it rolls the transaction to the beginning or to a particular save-point.
SAVEPOINT:
 SAVEPOINTS are special operations that allow us to divide the work of transaction into different
segments. In case a failure, we can execute rollbacks to the particular savepoint only
 SAVEPOINT statement defines a marker in a transaction. These markers are useful in rolling back a
transaction till the marker.
AUTOCOMMIT: When the autocommit is enabled:
 Every statement is considered one transaction and is committed there and then.
 Successful execution of a statement is implicitly (automatically) followed by COMMIT
 The occurrence of an error aborts (cancel) the transaction, rolling back any changes.
To begin a transaction:
 BEGIN
 BEGIN WORK
 START TRANSACTION;
To commit a transaction:
 COMMIT;
 COMMIT WORK;
To Rollback a transaction completely:
 ROLLBACK;
 ROLLBACK WORK;
To create a savepoint:
SAVEPOINT <savepoint_name>;
Ex. SAVEPOINT AAA;
To Rollback a transaction to a particular savepoint:
ROLLBACK TO SAVEPOINT <savepoint_name>;
ROLLBACK TO SAVEPOINT AAA;
To enable or disable autocommit:
SET autocommit = 0;  to disable autocommit
SET autocommit = 1;  to enable autocommit
To check whether autocommit is enabled or disabled:
SELECT @@autocommit;
If the server returns 1 i.e. autocommit is currently enable
If the server returns 0 i.e. autocommit is currently disable

Вам также может понравиться