Sei sulla pagina 1di 18

subhashv1224@gmail.

com
SCHOOL (DATABASE)

MySQL: Page 1

STUDENT (Table/Relation (Main or Primary Table) ATTRIBUTES/FIELDS/COLUMNS FOREIGN KEY REGNO 121 122 123 124 SNAME AMIT SANJAY ARUN SUNIL STD 12 12 12 12 SEC D D C A

MARKS (Related Table) REGNO 121 121 121 122 122 123 123 TERM 1 2 3 1 2 1 2 TOTAL 445 432 446 467 455 421 468

ROWS / TUPLES / RECORDS

PRIMARY KEY

A DATABASE may be defined as a collection of interrelated data stored together to serve multiple applications. A DBMS(Database Management System) refers to a software that is responsible for storing, maintaining and utilizing databases. A database along with a DBMS is referred as a Database System. Advantages of a Database System: 1. Databases reduce the data redundancy to a large extent: Duplication of data is known as data redundancy. 2. They can control data inconsistency: Inconsistency happens when two entries about the same data do not agree. 3. Database facilitates sharing of data 4. Databases enforce standards: The Database system can ensure that all data stored centrally follow the applicable standards. 5. Databases can ensure data security: Data security refers to protection of data against accidental or intentional disclosure to unauthorized persons or unauthorized modification or destruction 6. Databases maintain integrity. Table/Relation Table is a database object or structure where the data is stored. A table will contain rows and columns. A row in a table is called 'tuple' and the column in the table is called 'Attribute' or Field. Domain: This is a pool of values from which actual values appearing in a given column are drawn. Degree : This refers to number of attributes or columns in a table. Cardinality: This refers to the number of rows or tuples in a relation. Primary Key It is a unique and non-nullable attribute of the table i.e. PK field cannot contain NULL values The primary key of a relational table uniquely identifies each record in the table. Foreign key (Field that is a Primary Key in some other table.) It is a field in a relational table that matches the primary key column of another table. Foreign key is used to establish and enforce a link between the data in two tables. Candidate Keys A key that uniquely identifies rows in a table. Any of the identified candidate keys can be used as the table's primary key. Super Key A Candidate Key as a Super Key that contains only the minimum number of columns necessary to determine uniqueness. Referential Integrity: It is a system of rules that a DBMS uses to ensure that relationships between records in a related tables are valid and the users dont accidentally delete or change related data.

subhashv1224@gmail.com
You can set referential integrity when all the following conditions are met: The matching field from the main table is a primary key. The related fields have the same data type. Both the related tables belong to the same database.

MySQL: Page 2

When referential integrity is enforced, you must observe the following rules: 1. You cant enter a value in the foreign key field of the related table that doesnt exist in the primary key field of the main table. However you can enter a null value in the foreign key specifying that the records are unrelated. 2. You cant delete a record from a primary table if matching records exist in a related table. 3. You cant change a primary key value in the main table, if that record has related records. Categories if SQL commands Data Definition Language: SQL statements that can be used either interactively or within programming language source code to define databases and their components are DDL commands. CREATE -Create tables ALTER -Changing the table definition DROP -Drop tables RENAME -Renaming table TRUNCATE -Deletes the data

Data Manipulation Language [DML] These are SQL statements that can be used to manipulate the data in a relational table. It includes SELECT - extracts data from a database table UPDATE - updates data in a database table DELETE - deletes data from a database table INSERT INTO - inserts new data into a database table Data Control Language[DCL] These are SQL statements that can be used for control access to data in a database. It includes GRANT -to allow specified users to perform specified tasks. REVOKE- to cancel previously granted or denied permissions Transaction Control Language[TCL] These are SQL statements that can be used for used to control transactional processing in a database. These includes COMMIT -to make changes in a table permanent. ROLLBACK -to undo all changes of a transaction Null Values: if a column in a row has no value, then column is said to contain a null value. You should use a null value when the actual value is not known or when a value would not be meaningful. Note that, Dont use null to represent a value of zero, because they are not equivalent. Any arithmetic expression containing a null value ALWAYS evaluates to null. Comment: it is a text that is not executed. It is only for documentation purpose. These can be written in MySQL in three ways: Comments enclosed in /* */ Comments beginning with two hyphens followed by a space (-- ). This is a single line comment. Comment beginning with # symbol. This is also a single line comment.

Constraints: It is a condition or check applicable on a field or set of fields. Common type are: 1. not null ensures that a column cannot have null value. If you dont provide a value for such a column, it will result in an error 2. default provides a default value for a column when none is specified. 3. unique ensures that all values in a column are different. 4. check ensures that all values in a column satisfies a certain criteria. 5. primary key the value of this column will be used to uniquely identify a row. 6. foreign key used to ensure referential integrity of the data. Note that PK cannot have null values but UNIQUE can have. Also, there can be ONLY ONE PK in a table while multiple fields can be UNIQUE. Different ways of using CHECK constraint: std sal section city mf int(2) int(6) char(2) varchar(15) char(2) CHECK (std>=9 and std<=12), .. CHECK (sal BETWEEN 10000 AND 20000), .. CHECK (section IN (A,B,C,D,E)), . CHECK (city NOT IN (KOTA)), . CHECK (mf IN (M,F)), .

subhashv1224@gmail.com
create database abc; use abc ; ( this command will make the database abc active) Now create the following two tables: CREATE TABLE dept ( -> deptno int(4) primary key, -> dname varchar(20) not null , -> loc varchar (20) not null );

MySQL: Page 3

CREATE TABLE empl ( -> empno int(6) primary key , -> ename varchar (25) not null , -> job varchar(15) not null, -> mgr int(6) , -> hiredate date , -> sal decimal(10,2) check (sal > 0) , -> comm decimal(6,2) , -> deptno int(4) default 10, -> foreign key (deptno) references dept(deptno) );

INSERTING ROWS/RECORDS/TUPLES: The rows are added to the table using INSERT command of SQL. You can Insert records in two ways: 1. Without specifying column names: In this case, you need to provide values for all the fields of the table and in the same order in which they appear in the table definition. INSERT INTO empl VALUES -> (8369,SMITH,CLERK,8902,1990-12-18,800,NULL,20 ) ; 2. With specifying column names: In this case, you need to provide values ONLY for those fields that appear in the column list of INSERT statement and also in the same order as they appear in the column list. The values for the columns that you omit in the column list of INSERT statement will be set to NULL If you omit a column in the column list of INSERT statement and if you have given a default constraint for that column, then that default value will be set for that omitted column. INSERT INTO empl (empno, ename, job, hiredate, sal) -> VALUES (8893,AMIR,PRESIDENT,1991-11-18,5000); In the above example, the value for the omitted column mgr will be set to null the value for the omitted column comm will be set to null the value for the omitted column deptno will be set to 10 because it has been given a default value with a default constraint. Dates are by default entered in YYYY-MM-DD format.

Now INSERT the following records in dept Deptno 10 20 30 40 Dname ACCOUNTING MARKETING SALES PRODUCTION Loc DELHI MUMBAI JAIPUR BANGLORE

Making simple queries through SELECT command: 1. To view ALL the Records and ALL columns: SELECT * FROM EMPL ;

To VIEW SELECTIVE RECORDS FROM THE TABLE WE WILL USE WHERE CLAUSE WITH SELECT STATEMENT. 2. To view selective columns: SELECT empno, ename FROM empl; 3. To view unique values from a column, DISTINCT keyword is used. SELECT DISTINCT job FROM empl ; 4. To view records of employees who are managers: SELECT * FROM empl WHERE job=manager ; 5. To view those records where a column contains null values: SELECT * FROM empl WHERE comm. IS NULL; 6. To view those records where a column DOES NOT contains null values: SELECT * FROM empl WHERE comm IS NOT NULL; You can check more than 2 conditions by using AND & OR keywords. With AND, both the conditions have to be TRUE if the entire condition has to be TRUE. With OR, any one of the two condition has to be TRUE if the entire condition has to be TRUE.

subhashv1224@gmail.com

MySQL: Page 4

7. Display those managers who are getting a salary more than 1000: SELECT * FROM empl WHERE job=manager AND sal>1000; 8. Display all those employees who are managers or clerks. SELECT * FROM empl WHERE job=manager OR job=clerk; 9. Display all those managers and clerks who are getting salary more than 1000. SELECT * FROM empl WHERE (job=manager OR job=clerk) AND sal>1000 ; Identify the logical error with the following query: SELECT * FROM empl WHERE job=manager OR job=clerk AND sal>1000 ; To check conditions based on a range of values, the BETWEEN clause is used with SELECT statement. This operator defines a range of values that the column values must fall in to make the condition true. The range includes both lower and upper value. 10. To view records where an employee gets a salary between 2000 to 3000. SELECT * FROM empl WHERE sal BETWEEN 2000 AND 3000. 11. To view records where an employee dont get a salary between 2000 to 3000. SELECT * FROM empl WHERE sal NOT BETWEEN 2000 AND 3000. To check conditions based on LIST, IN and NOT IN clause are used with SELECT statement. The IN and NOT IN operator selects values that match any value in a given list of values. 12. To view records of members who live in Jaipur or Kota or Jodhpur from the table shop. SELECT * FROM shop WHERE city IN(Jaipur,Jodhpur,Kota) ; 13. To view records of members who DO NOT live in Udaipur. SELECT * FROM shop WHERE city NOT IN(Udaipur); 1) Conditions based on pattern matches. SQL includes a string-matching operator LIKE and NOT LIKE for comparisons on character strings using patterns. Patterns are described using two special wildcard characters: % -> this character matches any substring. _ -> this character matches any one character. 14. To view records of employees whose name begin with A. SELECT * FROM empl WHERE ename LIKE A% ; 15. To view records where a name is a 4 lettered. SELECT * FROM empl WHERE ename LIKE ____ ; 16. To view records where name starts with A and ends with S: SELECT * FROM empl WHERE ename LIKE A%S ; 17. To view records where A is the second character and S is the second last character in name field. SELECT * FROM empl WHERE ename LIKE _A%S_ ; 18. To view records where name does not contain in anywhere. SELECT * FROM empl WHERE ename NOT LIKE %IN% ; To view records in a sorted manner, ORDER BY clause is used with SELECT statement. The default sort order is ascending. To sort in descending order, add desc after the column name. 19. Display records in sorted manner by the name of the employees. SELECT * FROM empl ORDER BY ename ; 20. Display records of those employees who are managers in the descending order of their name: SELECT * FROM empl WHERE job=MANAGER ORDER BY ename DESC ; 21. Display records of all the employees in the sorted order of their jobs in ascending order and names in descending order. SELECT * FROM empl ORDER BY job, ename desc ; To make changes to a record, UPDATE command will be used. 22. To increase the salary of all those employees who are clerks by 10%. UPDATE empl SET sal=sal + (10/100*sal) WHERE job=CLERK ; 23. Change the name of SETH to SID. UPDATE empl SET ename=SID WHERE empno=8521; ( Can you guess why I have not written: ..WHERE ename=SETH..) To delete record(s), DELETE command will be used. 24. Delete all the records from empl table: DELETE FROM empl; ( Note that it is NOT DELETE * FROM empl) 25. Delete records of all those employees who do not get any commission: DELETE FROM empl WHERE comm. IS NULL ; NOTE that, you can use all those statements with WHERE clause of UPDATE and DELETE which you used with SELECT statement. Also, UPDATE and DELETE statements will not produce any output on the screen.

subhashv1224@gmail.com

MySQL: Page 5

Database Integrity Constraints: when you create a table, you can place constraints on the values that can be entered into its fields. If constraints are specified, SQL will reject any values entered or changed through insert or update command that violate the criteria you define. A constraint refers to a condition or a check that is applied to a column(field) or set of columns in a table. The constraints applied to maintain data integrity are also known as database integrity constraints. Following are some commonly used database constraints : (a) UNIQUE (b) CHECK (c) DEFAULT (d) PRIMARY KEY (e) FOREIGN KEY NOT NULL keyword immediately after column name and its data type indicates that the specific column can never have NULL or empty values. -> Column Constraints apply only to individual columns and they appear in front of the specific column. CREATE TABLE students ( regno int(6) NOT NULL PRIMARY KEY, Column Constraints sname varchar(30) NOT NULL , std int(3) NOT NULL CHECK (std BETWEEN 1 AND 12) , section char(2) NOT NULL CHECK (section IN (A , B, C, D, E ) ), mf char(2) NOT NULL CHECK (mf IN (M, F ) ) , city varchar(15) NOT NULL DEFAULT Jaipur , mobile int(10) UNIQUE ) ; All the above constraints are being used with columns so they are termed as COLUMN CONSTRAINTS. -> Table Constraints apply to groups of one or more columns and they appear in the end of table definition. The above table can be created using table constraints in the following way : CREATE TABLE students ( regno int(6) NOT NULL , sname varchar(30) NOT NULL , std int(3) NOT NULL , section char(2) NOT NULL , mf char(2) NOT NULL , city varchar(15) NOT NULL DEFAULT Jaipur , mobile int(10) UNIQUE , PRIMARY KEY (REGNO), Table Constraints CHECK (std BETWEEN 1 AND 12) , CHECK (section IN (A, B, C, D, E) ) , CHECK (mf IN (M, F ) ) , UNIQUE (mobile) ) ; UNIQUE constraint : This constraint ensure that no two rows have the same value in the specified column(s). PRIMARY KEY constraint: this constraint declares the specified column as the PK of the table. UNIQUE and PRIMARY KEY both ensures unique values for each row for the specified column. But the differences are : UNIQUE allows NULL values. Multiple columns with this constraints can exist. PK does not allow NULL values. ONLY one column or group of columns with this Constraint can exist.

DEFAULT constraint: Using this constraint, a default value for a column can be specified. This is a column constraint. If you dont specify a value with INSERT INTO command for this column then the value specified with DEFAULT constraint will be assigned for that column. CHECK constraint: this limits values that can be inserted into a column of a table. With CHECK following properties can be used : EX. city EX. salary EX. std EX. orddate char(20) float(10,2) int(3) char(10) CHECK (city IN (Jaipur, Ajmer, Kota, Udaipur) ), .. CHECK (sal > 5000.00 ), . CHECK (std BETWEEN 1 and 12 ) , .. CHECK (orddate LIKE --/--/---- ) ,

FOREIGN KEY constraint: Referential Integrity is ensured through this constraint. Whenever two tables are related by a common column, then the related column(s) in the Parent Table (Primary Table) should either be declared as Primary Key or as UNIQUE and the related column(s) in the Child Table should have a Foreign Key constraint. Ex. Considering the table Student you created previously as a Parent Table, we have a field regno as a Primary Key. Now we will create a Child table called test with the related field regno which should be declared as Foreign Key . Note that the datatype of the related field should be of the same type.

subhashv1224@gmail.com

MySQL: Page 6

In this example, Foreign Key is named as References as it is used as a Column Constraint: CREATE TABLE test ( regno int(6) not null references student (regno ) , term int (2) not null check (term > 0 and term <4 ) , eng int(3) check (eng <= 70) , ) ; The OTHER way to declare Foreign Key In this example, Foreign Key is named as FOREIGN KEY as it is used as a Table Constraint: CREATE TABLE test ( regno int(6) not null , term int (2) not null check (term > 0 and term <4 ) , eng int(3) check (eng <= 70) , FOREIGN KEY (regno) REFERENCES student ( regno ) ON DELETE CASCADE ON UPDATE CASCADE ) ; Role of FOREIGN KEY / REFERENCES Constraint: it results in rejection of INSERT or UPDATE statement if a corresponding value does not currently exists in the PARENT or PRIMARY TABLE if ON DELETE CASCADE option has been set , then upon deleting a row in the Parent Table all its related records in the CHILD TABLE gets deleted. In the absence of this clause, it rejects the deletion operation if corresponding record in the Child Table exists. if ON UPDATE CASCADE option has been set , then upon updating a row in the Parent Table all its related records in the CHILD TABLE gets updated. In the absence of this clause, it rejects the updation operation if corresponding record in the Child Table exists. The Foreign Key column in the Child Table must reference a Primary Key or Unique column in the Parent Table. Both the related columns in the Parent and Child Table must have the same data type.

Assigning Names to Constraints: By default MySQL assigns a unique name to each constraint defined by you. MySQL names constraints as : SYS_Cn where n is an integer that makes the constraint name unique. Ex. SYS_C003121, SYS_C001592 etc. However, you yourself can name a constraint created by you. This can be done as following : CREATE TABLE test ( regno term eng phy che mat inf

int(6) int (2) int(3) int(3) int(3) int(3) int(3)

not null , not null check (term > 0 and term <4 ) , check (eng <= 70) , check ( phy <=70) , check ( che <=70) , check ( mat <=70) , check ( inf <=70) ,

CONSTRAINT regno_test FOREIGN KEY (regno) REFERENCES student ( regno ) ON DELETE CASCADE ON UPDATE CASCADE ) ; Copy all the records of empl table into empl2 table. For this to happen, empl2 should have the same structure as that of empl table. INSERT INTO empl2 VALUES ( SELECT * FROM empl) ; Display the structure of the table. DESCRIBE empl;

OR

DESC empl ;

2) To perform simple calculations you can write the expression or formulae to be calculated next to the SELECT keyword: 1. To calculate 3.1415 * 6 + 2 / 23 * 3 SELECT 3.1415 * 6 + 2 / 23 * 3 ; 2. To display current system date SELECT CURDATE(); 3) The table in which foreign key is defined is called as referencing table or child table. A table to which a foreign key points to is called a referenced table or parent table or primary table

subhashv1224@gmail.com

MySQL: Page 7

Using COLUMN ALIASES: the columns/fields that you select in a query can be given a different name for display/output purposes ONLY. Column Alias means another name given to a column for output. 1. Display name, salary and commission field from empl table by using a meaning column alias name for the three columns: SELECT ename AS Name, sal AS Salary, comm AS Commission FROM empl ; 2. Display name and annual salary for each employee using a suitable column alias name: SELECT ename AS Name, sal AS SALARY, sal * 12 AS Annual Salary FROM empl ; Note that sal * 12 is a calculated column and NOT a real column as such. 4) The ALTER TABLE command is used to change definitions of existing tables. This is a DDL command that works on a table structure rather than table data. This command is used to: Add a new column/field to the table [ ADD clause ] Add an integrity constraint to the table. Redefine a column (datatype, size, default value etc.) [ MODIFY clause ] Rename a column/field. [CHANGE clause ] Delete a column/field. [ DROP clause ] 1. Write a query to add a new column telno of type int(12) in the table empl ALTER TABLE empl ADD ( telno int(12) ) ; 2. Write a query to modify column job of empl table to have a new width of 20 characters. ALTER TABLE empl MODIFY job varchar(20) NOT NULL ; 3. Write a query to change the column name telno to tel_number of table empl ALTER TABLE empl CHANGE telno tel_number int(12) ; 4. Write a query to remove tel_number field from empl table. ALTER TABLE empl DROP tel_number; 5. Write a query to set sno field of a table student as primary key which was not done earlier. ALTER TABLE student ADD PRIMARY KEY(sno); 6. Write a query to set sno field of related table test as foreign key which will be referring sno field of student table which was not done at the time of creating the table ALTER TABLE test ADD CONSTRAINT test_student FOREIGN KEY(sno) REFERENCES student ; In this query, you have noticed ADD CONSTRAINT test_student: this statement is actually naming a foreign key constraint as test_student instead of the default name provided by MySQL. Also notice REFERENCES student: here you have not provided the field name of the student table to which this related table is referring to. The reason is, if the name of the related field have the same name as that in the main table or primary table then you need not to write the field name. the other way this command could have been written was as follows: ALTER TABLE test ADD CONSTRAINT test_student FOREIGN KEY(sno) REFERENCES student(sno) 7. Write a query to set custno field of related table shop as foreign key which will be referring custnumber field of customer table which was not done at the time of creating the table ALTER TABLE shop ADD CONSTRAINT shop_cust FOREIGN KEY(custno) REFERENCES customer(custnumber) ; In this query since the name of the related fields in both the tables are different, you need to give the field name along with the main table name with references keyword. 8. Write a query to remove foreign key constraint from shop table. ALTER TABLE shop DROP FOREIGN KEY shop_cust ; 9. Write a query to remove primary key constraint from customer table. ALTER TABLE customer DROP PRIMARY KEY ; In 8 query NOTE that to remove a foreign key constraint you HAVE to give a name to the FOREIGN KEY CONSTRAINT and the reason being that you can have any number of FOREIGN KEYS defined in a table. th In 9 query, you need NOT HAVE to give a name to PRIMARY KEY constraint and the reason being that you can have ONLY ONE PK in a table. NOTE that PRIMARY KEY constraint implies two more constraints automatically namely UNIQUE and NOT NULL .
th

subhashv1224@gmail.com
EMPL TABLE empno Ename Job mgr Hiredate 8369 SMITH CLERK 8902 1990-12-18 8499 ANYA SALESMAN 8698 1991-02-20 8521 SETH SALESMAN 8698 1991-02-22 8566 MAHADEVAN MANAGER 8839 1991-04-02 8654 MOMIN SALESMAN 8698 1991-09-28 8698 BINA MANAGER 8839 1991-05-01 8882 SHIVANSH MANAGER 8839 1991-06-09 8888 SCOTT ANALYST 8566 1992-12-09 8893 AMIR PRESIDENT NULL 1991-11-18 8844 KULDEEP SALESMAN 8698 1991-09-08 8886 ANOOP CLERK 8888 1993-01-12 8900 JATIN CLERK 8698 1991-12-03 8902 FAKIR ANALYST 8566 1991-12-03 8934 MITA CLERK 8882 1992-01-23 Now write the queries for the following based on the empl table: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30.

MySQL: Page 8
Sal 800.00 1600.00 1250.00 2985.00 1250.00 2850.00 2450.00 3000.00 5000.00 1500.00 1100.00 950.00 3000.00 1300.00 comm NULL 300 500 NULL 1400 NULL NULL NULL 0.00 NULL NULL NULL NULL NULL deptno 20 30 30 20 30 30 10 20 10 30 20 30 20 NULL

Display all records and all columns from the table. Display employee number and the name of all the employees from the table. Display employee name, salary, commission and salary added with commission from the table. Write a query to display employee name, salary and department number of those employees who are not getting any commission. Write a query to display employee name, number, salary and annual salary of all those employees who are getting commission with suitable alias names. List all department numbers from the table. List all the unique department numbers from the table. List details of all clerks who have not been assigned department as yet. List details of all those employees with 4 lettered name. List the details of all those employees whose annual salary is between 25000 to 40000. How many job types are offered to employees? List the details of employees who earn more commission than their salaries. Write a query to display the name, job title and salary of employees who do not have a manager. Write a query to display the name of employees whose name contains A as third alphabet. Write a query to display the name of the employees whose name contains T as the last alphabet. Write a query to display the name of employee who is having L as any alphabet of the name. Write a query to display name and salary of those employees whose salary is greater than or equal to 2200 from the table. Write a query to display name and salary of all those employees who dont have salary in the range of 2500 to 4000. Write a query to display the name of those employees whose name contains M as first alphabet and L as third alphabet. Display all those records where employee name contains sh in the name field. Display records of those clerks who earn a salary more than 1000. Display records of those clerks and salesman who earn a salary more than 1000. Display all records in a sorted order by job and then by name. Display records in sorted order of their names in descending order and jobs in ascending order. Display records of those employees who have joined after 1 July 1991. Display records of those employees who work in department 10. Display records of those clerks who work in department # 10 or 20. Display those managers whose name begin with s. Display those salesman or managers who work in department 30. Display names of those employees who are not getting any commission. Student ( Table) Name Game SAMEER CRICKET SUJIT TENNIS KAMAL SWIMMING VEENA TENNIS ARCHANA VOLLEYBALL ARPIT CRICKET

studentno 10 11 12 13 14 15 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

class 7 8 7 7 9 10

grade1 B A B C A A

Supw PHOTOGRAPHY GARDENING PHOTOGRAPHY COOKING LITERATURE GARDENING

grade2 A C B A A C

Display the names of the students who are getting a grade C in either GAME or SUPW. Display the different games offered in the school. Display the SUPW taken up by the students, whose name starts with A. Display all the students whose game is cricket or tennis. Display all the students whose game is cricket or tennis and they are in class 7. Display records of those students who have got A grade in both GAME and SUPW. Display names of those students who are in class 9 10. Display records of all those students whose name contains R anywhere. Display the records of all those students whose name begins with A and who have opted for cricket. Display records of those students who have got A grade in either Photography or Gardening.

subhashv1224@gmail.com
CREATE TABLE dept ( -> deptno int(4) primary key, -> dname varchar(20) not null , -> loc varchar (20) not null );

MySQL: Page 9
CREATE TABLE empl ( -> empno int(6) primary key , -> ename varchar (25) not null , -> job varchar(15) not null, -> mgr int(6) , -> hiredate date , -> sal decimal(10,2) check (sal > 0) , -> comm decimal(6,2) , -> deptno int(4) default 10, -> foreign key (deptno) references dept(deptno) ); JOINS

A JOIN is a query that combines rows from two or more tables. In such a query, more than one table are listed in FROM clause. The function of combining data from multiple tables is called joining. 1) In the above two tables, deptno field in dept table is a primary key. And the empl table contains the field deptno which is a foreign key as it is deriving its value from the deptno field of dept table. In Unrestricted Join or Cartesian Product of two tables, all possible combinations are formed of all rows of both the tables. SELECT * FROM empl , dept ; It returns n1 x n2 rows where n1(empl) is number of rows in first table and n2(dept) is number of rows in second table. The join in which columns are compared for equality is called Equi-Join. In this, all columns from joining table appear in the output even if they are identical. SELECT * FROM empl , dept WHERE empl.deptno = dept.deptno ; -- this is a join condition In this, we are joining two tables empl and dept on the basis of their common field deptno. Also notice empl.deptno: this type of statement is termed as qualified field names. A field name needs to be qualified with its table name when two tables contain a field with the same name so as to avoid ambiguity. To qualify a field name you need to type the table name followed by the dot and the field name. The join in which only one of the identical columns coming from the joined tables appear is called a Natural Join. SELECT empl.* , dname, loc FROM empl, dept WHERE empl.deptno = dept.deptno ; JOINING TABLES USING JOIN CLAUSES A JOIN clause without a join condition will create a CARTESIAN PRODUCT of two tables: SELECT * FROM empl JOIN dept ; If no join condition is specified with a JOIN clause, a Cartesian Product is the output. To create equi-join on some common field of two tables, write the query as: SELECT * FROM empl JOIN dept ON ( empl.deptno = dept.deptno ) ; You can specify join fields through USING clause also in place of ON clause, but with USING clause you just have to specify the name of the join field whereas with ON clause, join condition is specified. But USING clause requires that joining fields have the same name in both the tables. SELECT * FROM empl JOIN dept USING (deptno) ; USING sub clause with JOIN clause produces a Natural Join whereas ON sub clause with JOIN clause produces Equi-Join A CROSS JOIN clause will obtain the Cartesian product of two tables and also you cant give a join condition with such type of join. SELECT * FROM empl CROSS JOIN dept ; A NATURAL JOIN clause joins two table based on a common field. Also this clause will display the common field only once. But specifying this clause requires that joining field of both the tables must have the same name. SELECT * FROM empl NATURAL JOIN dept ; In the above query, you need not specify a join condition. But if joining fields have different names than this clause will not work and you have to write the query with = sign as : SELECT * FROM shop, customer WHERE shop.custno = customer.cno ; In the above query you can see that the related field of both the tables has different names that is custno in shop table and cno in customer table and as such NATURAL JOIN clause will not work.

subhashv1224@gmail.com

MySQL: Page 10

When you display an equi join or natural join, it shows only the matched rows. But if we want to know which all rows from a table did not match with other, MySQL Left Join or Right Join will be used. 1. When using LEFT JOIN all rows from the first(left) table will be returned whether there are matches in the second table or not. For unmatched rows in the first table, NULL is shown in columns of second table. For example, dept table has a deptno which is not there in empl table, then if you left join dept table with empl, NULL is returned for non-existing values in empl table: SELECT dept.* ,ename,mgr,sal FROM dept LEFT JOIN empl ON dept.deptno = empl.deptno ; Lets see how the above query works: MySQL starts with the left table (dept here). For each row from the table dept MySQL scans the table empl, finds the deptno of the enployees and returns employee name(ename), managers code(mdr) and his salary(sal). Then these fields of empl table are joined with the matching row from the table dept. for unmatched rows, it returns NULL for ename, mgr and sal fields. 2. RIGHT JOIN works just like LJ but with table order reversed. All rows from second(right) table are going to be returned whether or not there are matches in the first table. Now queries based on two tables: 1. Consider the tables HANDSETS and CUSTOMER given below: HANDSETS TABLE SetName TouchScreen Nokia 2G N Nokia 3G Y BlackBerry N CUSTOMER TABLE SetNo CustAddress N2 Delhi B1 Mumbai N2 Mumbai N1 Kolkata B1 Delhi

SetCode N1 N2 B1

PhoneCost 5000 8000 14000

CustNo 1 2 3 4 5

a. Display the CustNo, CustAddress, and corresponding SetName for each customer. b. Display the Customer details for each customer who uses a Nokia handset. c. Give the output of the following query: SELECT setno, setname FROM handsets,customer WHERE setno=setcode AND CustAddress=Delhi ; 2. Consider the tables DOCTORS and PATIENTS given below: DOCTORS TABLE DocName Department M. Pandey ENT G.P.Gupta Paed C.K. Sharma Ortho PATIENTS TABLE PatName Department Neeraj ENT Mohit Ortho Ragini ENT Mohit Paed Nandini Ortho

DocID 101 102 201

OPD_Days TTS MWF MWF

PatNo 1 2 3 4 5

DocID 101 201 101 102 201

a. Display the PatNo, PatName and corresponding DocName for each patient. b. Display the list of patients whose OPD-Days are MWF. c. Give the output of the following query: SELECT opd_days, COUNT(*) FROM doctors, patients WHERE patients.department = doctors.department GROUP BY opd_days ;

subhashv1224@gmail.com Types of SQL Functions:


MySQL: Page 11

Single row functions (Scalar): works with a single row at a time. These functions return a result for every row of a queried table. Multiple row functions (Group or Aggregate): work with data of multiple rows at a time and return aggregate value.

How are aggregate functions in MySQL?


Aggregate functions perform summary operations on a set of values, such as counting, averaging, or finding minimum or maximum values. Aggregate functions often are used in conjunction with a GROUP BY clause to arrange values from a result set into groups. In this case, the aggregate function produces a summary value for each group. The GROUP BY clause combines all those records that have identical values in a particular field or a group of fields. In other words this clause is used in SELECT statements to divide the table into groups. Grouping can be done by a column name, or with aggregate functions in which case the aggregate produces a value for each group. Grouping can be based on the values in one or more columns of the selected rows. For example, the Country table indicates which continent each country is part of, so you can group the records by continent and calculate the average population of countries in each continent:

SELECT Continent, AVG(Population) FROM Country GROUP BY Continent; 2) Placing conditions on Groups by HAVING clause: The HAVING clause places conditions on groups in contrast to WHERE clause that places conditions on individual rows. While WHERE conditions cannot include aggregate functions, HAVING conditions can do. Functions such as AVG() that calculate summary values for groups are known as "aggregate" functions because they're based on aggregates or groups of values. There are several types of aggregate functions. Those discussed here are as follows: MIN() and MAX() find smallest and largest values. SUM() and AVG() summarize numeric values to produce sums (totals) and averages. COUNT() counts rows, values, or the number of distinct values.

Aggregate functions may be used with or without a GROUP BY clause that places rows into groups. Without a GROUP BY clause, an aggregate function calculates a summary value based on the entire set of selected rows. (That is, MySQL treats all the rows as a single group.) With a GROUP BY clause, an aggregate function calculates a summary value for each group. For example, if a WHERE clause selects 20 rows and the GROUP BY clause arranges them into four groups of five rows each, a summary function produces a value for each of the four groups. The MIN() and MAX() Aggregate Functions MIN() and MAX() are comparison functions. They return smallest or largest numeric values, lexically first or last string values, and earliest or latest temporal values. The following queries determine the smallest and largest country populations and the lexically first and last country names:

mysql> SELECT MIN(Population), MAX(Population) FROM Country; +-----------------+-----------------+ | MIN(Population) | MAX(Population) | +-----------------+-----------------+ | 0| 1277558000 | +-----------------+-----------------+ mysql> SELECT MIN(Name), MAX(Name) FROM Country; +-------------+-----------+ | MIN(Name) | MAX(Name) | +-------------+-----------+ | Afghanistan | Zimbabwe | +-------------+-----------+

It is to be noted that MIN() and MAX() ignore NULL values. The SUM() and AVG() Aggregate Functions The SUM() and AVG() functions calculate sums and averages. For example, the Country table in the world database contains a Population column, so you can calculate the total world population and the average population per country like this:

subhashv1224@gmail.com
mysql> SELECT SUM(Population), AVG(Population) FROM Country; +-----------------+-----------------+ | SUM(Population) | AVG(Population) | +-----------------+-----------------+ | 6078749450 | 25434098.1172 | +-----------------+-----------------+

MySQL: Page 12

SUM() and AVG() are most commonly used with numeric values. If you use them with other types of values, those values are subject to numeric conversion, which might not produce a sensible result. It is to be noted that SUM() and AVG() ignore NULL values. The COUNT() Aggregate Function The COUNT() function can be used in several ways to count either rows or values. To illustrate, the examples here use the following table that has several rows containing various combinations of NULL and non-NULL values:

mysql> SELECT i, j FROM t; +------+------+ |i | j | +------+------+ | 1 | NULL | | NULL | 2 | | 1 | 1 | | 1 | 1 | | 1 | 3 | | NULL | NULL | | 1 | NULL | +------+------+

COUNT() may be used as follows: COUNT(*) counts the total number of rows: mysql> SELECT COUNT(*) FROM t; | COUNT(*) | | 7| COUNT(expression) counts the number of non-NULL values of the given expression. It's common for expression to be a column name, in which case COUNT() counts the number of non-NULL values in the column: mysql> SELECT COUNT(i), COUNT(j) FROM t; | COUNT(i) | COUNT(j) | | 5| 4| COUNT(DISTINCT expression) counts the number of distinct (unique) non-NULL values of the given expression. expression can be a column name to count the number of distinct non-NULL values in the column: mysql> SELECT COUNT(DISTINCT i), COUNT(DISTINCT j) FROM t; | COUNT(DISTINCT i) | COUNT(DISTINCT j) | | 1| 3| It's also possible to give a list of expressions separated by commas. In this case, COUNT() returns the number of distinct combinations of values that contain no NULL values. The following query counts the number of distinct rows for which neither i nor j is NULL:

mysql> SELECT COUNT(DISTINCT i, j) FROM t; | COUNT(DISTINCT i, j) | | 2| Aggregation for NULL Values or Empty Sets In general, aggregate functions ignore NULL values. The exception is COUNT(), which behaves as follows: COUNT(*) does not ignore NULL values because it counts rows, even those that contain NULL values. COUNT(expression) and COUNT(DISTINCT) do ignore NULL values.

subhashv1224@gmail.com

MySQL: Page 13

A SELECT statement might produce an empty result set if the table is empty or the WHERE clause selects no rows from it. If the set of values passed to an aggregate function is empty, the function computes the most sensible value. For COUNT(), the result is zero. But functions such as MIN(), MAX(), SUM(), AVG(), and GROUP_CONCAT() return NULL.

Examples of Aggregate Functions based on empl table:


1) Display number of records in the table. SELECT COUNT(*) FROM EMPL; 2) Display total number of departments in the table. SELECT COUNT(DEPTNO) FROM EMPL; 3) Display count of employees working in each job in the table. SELECT JOB, COUNT(JOB) FROM EMPL GROUP BY JOB; 4) Display total number of employees working in each department. SELECT DEPTNO, COUNT(DEPTNO) FROM EMPL GROUP BY DEPTNO; 5) Display total employees working those jobs where job name begins with s. SELECT JOB, COUNT(JOB) FROM EMPL GROUP BY JOB HAVING JOB LIKE S%; 6) Display total employees and total salary given to those jobs where job name begins with s. SELECT JOB, COUNT(JOB), SUM(SAL) FROM EMPL GROUP BY JOB HAVING JOB LIKE S%; 7) Display count and sum of those jobs where number of employees working is more than 2. SELECT JOB, COUNT(JOB), SUM(SAL) FROM EMPL GROUP BY JOB HAVING COUNT(JOB) > 2; 8) Display count and sum of those jobs where total salary assigned to the job is greater than 5000. SELECT JOB, COUNT(JOB), SUM(SAL) FROM EMPL GROUP BY JOB HAVING SUM(SAL) > 5000 ; 9) Display maximum salary in the table. SELECT MAX(SAL) FROM EMPL; 10) Display the details of the employee who is getting the maximum salary in the table. SELECT * FROM EMPL WHERE SAL = ( SELECT MAX(SAL) FROM EMPL ) ; Here we have used a sub-query inside a query. Also make sure that the sub-query SHOULD return ONE and ONLY ONE record. 11) Display the name of employee who is getting maximum salary in a particular job. SELECT ENAME, JOB AS J, SAL FROM EMPL WHERE SAL >= (SELECT MAX(SAL) FROM EMPL GROUP BY JOB HAVING JOB=J) ; 12) Display those employees whose name begins with s from each job type. SELECT ENAME, JOB FROM EMPL WHERE ENAME LIKE S% GROUP BY JOB ; 13) Group records department-wise than job-wise. SELECT DEPTNO, JOB, COUNT(DEPTNO) FROM EMPL GROUP BY DEPTNO, JOB ; 14) Display total salary given to each department. SELECT DEPTNO, SUM(SAL) FROM EMPL GROUP BY DEPTNO; 15) Display total salary given to department # 10. SELECT DEPTNO, SUM(SAL) FROM EMPL WHERE DEPTNO=10 GROUP BY DEPTNO; OR SELECT DEPTNO, SUM(SAL) FROM EMPL GROUP BY DEPTNO HAVING DEPTNO=10 ;; 16) Display total salary, average salary and total employees working in each department. SELECT DEPTNO, SUM(SAL), AVG(SAL), COUNT(DEPTNO) FROM EMPL GROUP BY DEPTNO; 17) Display the details of the employee who is getting maximum salary in that department. SELECT DEPTNO AS D, ENAME, SAL FROM EMPL WHERE SAL >= (SELECT MAX(SAL) FROM EMPL GROUP BY DEPTNO HAVING DEPTNO=D) OR DEPTNO IS NULL ORDER BY DEPTNO; 18) Display highest and lowest salary and their difference of each department. SELECT DEPTNO, MAX(SAL), MIN(SAL), MAX(SAL) MIN(SAL) FROM EMPL GROUP BY DEPTNO; 19) Display salary, commission and sum of total and commission for each employee. Ensure that the total salary should not be a null value. SELECT ENAME, SAL, COMM, SAL + IFNULL(COMM,0) AS TOTAL FROM EMPL; The IFNULL function will substitute any NULL value in comm field with 0 and thus the result displayed will be a Non-NULL value. 20) Display those jobs where number of employees is less than 3. SELECT JOB, COUNT(*) FROM EMPL GROUP BY JOB HAVING COUNT(*) < 3 ; 21) Display employee number his name, his manager code and his managers name from the table. SELECT E1.EMPNO, E1.ENAME, E1.MGR, E2.ENAME FROM EMPL AS E1 LEFT JOIN EMPL AS E2 ON E1.MGR = E2.MGR ; If you include a non-group expression in the select list of a query with GROUP BY, MySQL will not produce any error. Rather it will pick value of the non-group field from the first row of the group. Such queries may result in ambiguous result. Ex. SELECT ENAME, SUM(SAL) FROM EMPL GROUP BY DEPTNO; This query will display the first name of the first group of dept#.

subhashv1224@gmail.com
SINGLE ROW FUNCTIONS (Scalar)

MySQL: Page 14

A Function is a special type of pre defined command that perform some operation and return a single value. Following are some commonly used String, Numeric and DateTime functions . These functions are row level functions i.e. these functions works on each row if used with tables. CHAR(N) CHAR() interprets each argument N as an integer and returns a string consisting of the characters given by the code values of those integers. NULL values are skipped. mysql> SELECT CHAR(77,121,83,81,'76'); MySQL CONCAT(str1,str2,...) arguments. Returns the string that results from concatenating the arguments. May have one or more

mysql> SELECT CONCAT('My', 'S', 'QL'); | MySQL INSTR(str,substr) Returns the position of the first occurrence of substring substr in string str. This is the same as the two-argument form of LOCATE(), except that the order of the arguments is reversed. mysql> SELECT INSTR('jaipur', 'ur'); |5 LCASE(str) LCASE() is a synonym for LOWER().

LEFT(str,len) Returns the leftmost len characters from the string str, or NULL if any argument is NULL. mysql> SELECT LEFT(rajasthan', 3); raj LENGTH(str) Returns the length of the string str, measured in bytes. . mysql> SELECT LENGTH('text'); |4 LOWER(str) Returns the string str with all characters changed to lowercase according to the current character set mapping. mysql> SELECT LOWER('QUADRATICALLY'); | quadratically LTRIM(str) Returns the string str with leading space characters removed. mysql> SELECT LTRIM(' hello'); hello MID(str,pos,len) MID(str,pos,len) is a synonym for SUBSTRING(str,pos,len). REPEAT(str,count) Returns a string consisting of the string str repeated count times. If count is less than 1, returns an empty string. Returns NULL if str or count are NULL. mysql> SELECT REPEAT('MySQL', 3); | MySQLMySQLMySQL REVERSE(str) Returns the string str with the order of the characters reversed. mysql> SELECT REVERSE('abcd'); | dcba RIGHT(str,len) Returns the rightmost len characters from the string str, or NULL if any argument is NULL. mysql> SELECT RIGHT('jaipur', 2); | ur RTRIM(str) Returns the string str with trailing space characters removed. ');

mysql> SELECT RTRIM('hello | hello

STRCMP(str1, str2) Compares two strings and returns 0 if both strings are equal, it returns -1 if the first argument is smaller than the second according to the current sort order otherwise it returns 1. mysql> SELECT STRCMP('MOHD', 'MOHD'); |0 mysql> SELECT STRCMP('AMOHD', 'MOHD'); | -1

subhashv1224@gmail.com
mysql> SELECT STRCMP('MOHD', 'AMOHD'); |1

MySQL: Page 15

SUBSTRING(str,pos) OR SUBSTRING(str FROM pos) OR SUBSTRING(str,pos,len) The forms without a len argument return a substring from string str starting at position pos. The forms with a len argument return a substring len characters long from string str, starting at position pos. The forms that use FROM are standard SQL syntax. It is also possible to use a negative value for pos. In this case, the beginning of the substring is pos characters from the end of the string, rather than the beginning. A negative value may be used for pos in any of the forms of this function. mysql> SELECT SUBSTRING('Quadratically',5); | ratically | mysql> SELECT SUBSTRING(rajasthan' FROM 6); |than mysql> SELECT SUBSTRING('Quadratically',5,6); | ratica TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str) TRIM([remstr FROM] str) Returns the string str with all remstr prefixes or suffixes removed. If none of the specifiers BOTH, LEADING, or TRAILING is given, BOTH is assumed. remstr is optional and, if not specified, spaces are removed. mysql> SELECT TRIM(' bar '); | bar UCASE(str) UPPER(str) current character set mapping. mysql> SELECT UPPER('Xaviers'); | XAVIERS Numeric Functions ABS(X) The ABS() function returns the absolute value of X. Consider the following example: Returns the string str with all characters changed to uppercase according to the

mysql> SELECT ABS(2); |2 mysql> SELECT ABS(-2); |2 CEIL(X) CEILING(X) following example: mysql> SELECT CEILING(3.46); |4 mysql> SELECT CEIL(-6.43); | -6 FLOOR(X) This function returns the largest integer value that is not greater than X. These function return the smallest integer value that is not smaller than X. Consider the

mysql>SELECT FLOOR(7.55); |7 FORMAT(X,D) The FORMAT() function is used to format the number X in the following format: ###,###,###.## truncated to D decimal places. mysql>SELECT FORMAT(423423234.65434453,2); | 423,423,234.65 GREATEST(n1,n2,n3,..........) n2, n3, a nd so on). The GREATEST() function returns the greatest value in the set of input parameters (n1,

mysql>SELECT GREATEST(3,5,1,8,33,99,34,55,67,43); | 99 LEAST(N1,N2,N3,N4,......) The LEAST() function is the opposite of the GREATEST() function. Its purpose is to return the least-valued item from the value list (N1, N2, N3, and so on). mysql>SELECT LEAST(3,5,1,8,33,99,34,55,67,43); |1

subhashv1224@gmail.com
MOD(N,M) mysql>SELECT MOD(29,3); |2 POW(X,Y) POWER(X,Y)

MySQL: Page 16

This function returns the remainder of N divided by M. Consider the following example:

These two functions return the value of X raised to the power of Y.

mysql> SELECT POWER(3,3); | 27 ROUND(X) ROUND(X,D) This function returns X rounded to the nearest integer. If a second argument, D, is supplied, then the function returns X rounded to D decimal places. D must be positive or all digits to the right of the decimal point will be removed. Consider the following example: mysql>SELECT ROUND(5.693893); |6 mysql>SELECT ROUND(5.693893,2); | 5.69 SIGN(X) This function returns the sign of X (negative, zero, or positive) as .1, 0, or 1.

mysql>SELECT SIGN(-4.65); | -1 mysql>SELECT SIGN(0); |0 mysql>SELECT SIGN(4.65); |1 SQRT(X) This function returns the non-negative square root of X. Consider the following example:

mysql>SELECT SQRT(49); |7 TRUNCATE(X,D) This function is used to return the value of X truncated to D number of decimal places. If D is 0, then the decimal point is removed. If D is negative, then D number of values in the integer part of the value is truncated. Consider the following example: mysql>SELECT TRUNCATE(7.536432,2); | 7.53 CURDATE() Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context. mysql> SELECT CURDATE(); | 1997-12-15 mysql> SELECT CURDATE() + 0; | 19971215 CURRENT_DATE and CURRENT_DATE() CURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE() CURTIME() Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context. The value is expressed in the current time zone. mysql> SELECT CURTIME(); | 23:50:26 CURRENT_TIME and CURRENT_TIME() CURTIME(). DATE(expr) CURRENT_TIME and CURRENT_TIME() are synonyms for

Extracts the date part of the date or datetime expression expr.

mysql> SELECT DATE('2003-12-31 01:02:03'); | 2003-12-31 DAY(date) DAY() is a synonym for DAYOFMONTH(). Returns the name of the weekday for date.

DAYNAME(date)

mysql> SELECT DAYNAME('1998-02-05'); | Thursday DAYOFMONTH(date) Returns the day of the month for date, in the range 0 to 31.

subhashv1224@gmail.com
mysql> SELECT DAYOFMONTH('1998-02-03'); |3

MySQL: Page 17

DAYOFWEEK(date) Returns the weekday index for date (1 = Sunday, 2 = Monday, ., 7 = Saturday). These index values correspond to the ODBC standard. mysql> SELECT DAYOFWEEK('1998-02-03'); |3 DAYOFYEAR(date) Returns the day of the year for date, in the range 1 to 366.

mysql> SELECT DAYOFYEAR('1998-02-03'); | 34 HOUR(time) Returns the hour for time. The range of the return value is 0 to 23 for time-of-day values. However, the range of TIME values actually is much larger, so HOUR can return values greater than 23. mysql> SELECT HOUR('10:05:03'); | 10 LAST_DAY(date) Takes a date or datetime value and returns the corresponding value for the last day of the month. Returns NULL if the argument is invalid. MINUTE(time) Returns the minute for time, in the range 0 to 59. MONTH(date) Returns the month for date, in the range 0 to 12. mysql> SELECT MONTH('1998-02-03') |2 MONTHNAME(date) Returns the full name of the month for date.

mysql> SELECT MONTHNAME('1998-02-05'); | February NOW() Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context. The value is expressed in the current time zone. mysql> SELECT NOW(); | 1997-12-15 23:50:26 SECOND(time) Returns the second for time, in the range 0 to 59. SYSDATE() Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context. mysql> SELECT SYSDATE(); | 2006-04-12 13:47:44 TIME(expr) Extracts the time part of the time or datetime expression expr and returns it as a string.

mysql> SELECT TIME('2003-12-31 01:02:03'); | 01:02:03 YEAR(date) Returns the year for date, in the range 1000 to 9999, or 0 for the .zero. date.

mysql> SELECT YEAR('98-02-03'); | 1998

subhashv1224@gmail.com DATABASE TRANSACTIONS

MySQL: Page 18

A TRANSACTION is a logical unit of work that must succeed or fail in its entirety. This means that a transaction may involve many sub-steps which should either all be carried out successfully or all should be ignored if some failure occurs. Transaction Properties: In order to maintain the data integrity, the database system maintains the following properties of the transaction often termed as ACID properties: Atomicity: this property ensures All or None operations are carried out i.e. the transaction runs to completion as an indivisible unit, at the end of which either no change at all will be made to the database or the database will have changed in a consistent manner. This property has two states: o DONE state means a transaction must complete successfully and its effect should be visible in the database. o NEVER STARTED state means if a transaction fails during execution then all its modifications must be undone to bring back the database to the last consistent state i.e. remove all the effects of a failed transaction. Consistency: this ensures that if the database was in a consistent state before the start of the transaction, then upon its termination, the database will be in a consistent state. Isolation: this implies that each transaction is unaware of other transaction executing concurrently in the system. Durability: this ensures that on the successful completion of a transaction i.e. when a transaction is COMMITed, the changes made by it to the database persist, even if there are system failures. MySQL offers a set of commands for transaction control purpose and these subset of commands are known as TCL (Transaction Control Language commands): a. BEGIN | START TRANSACTION marks the beginning of a transaction. b. COMMIT ends the current transaction by saving database changes and start a new transaction. c. ROLLBACK ends the current transaction by discarding database changes and starts a new transaction. d. SAVEPOINT defines breakpoints for the transaction to allow partial rollbacks. e. SET AUTOCOMMIT enables or disables the default autocommit mode. Explain how the following sql script would affect the table: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. Statement 1: Statement 2 -3 : Statement 4: Statement 5: Statement 6: Statement 7: Statement 8: Statement 9: Statement 10: Statement 11-12: Statement 13: START TRANSACTION UPDATE .. INSERT SAVEPOINT S1 INSERT SAVEPOINT S2 DELETE ROLLBACK WORK TO SAVEPOINT S2 UPDATE ROLLBACK WORK TO SAVPOINT S1 UPDATE DELETE COMMIT WORK transaction begins these two changes are not yet permanent a savepoint is defined with the name s1 this change is not yet permanent a savepoint is defined with the name s2 this change is not yet permanent a rollback is issued. However, only those changes performed after savepoint s2 are undone. The statement 7 will be undone. this change is not yet permanent a rollback to savepoint s1 is entered. All changes performed after statement 4 is undone. Thus statement 5, 7, 9 will be undone. these two changes are not yet permanent. all non-permanent changes are made permanent. Thus statements 2, 3, 11 and 12 will be made permanent.

Note that a transaction ends with: An explicit COMMIT statement and the changes will be committed or An explicit ROLLBACK statement and the changes will be undone or An explicit START TRANSACTION statement the transaction is committed or Implicitly by issuing any DDL command a transaction is committed. SET AUTOCOMMIT: by default, MySQL has autocommit ON, which means if you do not start a transaction explicitly through BEGIN or START TRANSACTION command, then every statement is considered one transaction and is committed there and then. SET AUTOCOMMIT=1; will enable auto-commit. To disable auto-commit type: SET AUTOCOMMIT=0; this is to make sure that changes made by statement are not made permanent until you explicitly issue a COMMIT command.

Potrebbero piacerti anche