Top Banner
INTERNAL TECHNICAL TRAINING SESSION FOR SQL BY :- RAHUL KUMAR SINGH (JAVA TEAM)
39

Sql

Apr 16, 2017

Download

Technology

Rahul Singh
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Sql

INTERNAL TECHNICAL TRAINING SESSION FOR SQL

BY :- RAHUL KUMAR SINGH(JAVA TEAM)

Page 2: Sql

2

KEYS Key is a single or combination of multiple fields in a table. It is used to

fetch or retrieve records/data-rows from data table according to the condition/requirement. Keys are also used to create relationship among different database tables or views.

Page 3: Sql

3

TYPES OF KEYS IN SQL Candidate key Super key Primary key Alternative key Foreign key Unique key In our company database primary key and foreign keys are used

heavily

Page 4: Sql

4

CANDIDATE KEY Minimum set of attributes used to differentiate records of the table

(sid,cid) candidate key Subset of (sid,cid) should not be a candidate key.

If candidate key forms with single attribute then the candidate key is called simple candidate key, otherwise it’s called compound candidate key.

Sid cid Fee

S1 C1 5000

S1 C2 6000

S2 C2 7000

S2 C3 7000

Page 5: Sql

5

PRIMARY KEY One of the candidate key is primary key. Candidate key with not null

attribute is called primary key.

cid is primary key here – all distinct values with not null constraint. cid is candidate key also(simple candidate key).

Sid cid Fee

S1 C1 5000

S1 C2 6000

S2 C3 7000

S2 C4 8000

Page 6: Sql

6

PRIMARY KEY(Contd.) A RDBMS can have only one primary key.

No primary key in this table. Is this table valid for mysql InnoDB engine?

Sid cid Fee

S1 C1 5000

S1 C2 6000

S2 C2 7000

S2 C3 7000

Page 7: Sql

7

PRIMARY KEY(Contd.) In mysql, the InnoDB storage engine always creates a primary key, if

you didn’t specify it explicitly, thus making an extra column you don’t have access to.

Primary key can be composite.

SYNTAX TO CREATE PRIMARY KEYCREATE TABLE roll (id int(11) NOT NULL AUTO_INCREMENT,surname varchar(100) NOT NULL,PRIMARY KEY(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Page 8: Sql

8

ALTERNATIVE KEY All candidates keys accept primary key is alternative key.

Here sid, cid and fee are candidate keys. So if we are considering sid as a primary key than cid and fee are alternative keys.

Sid cid Fee

S1 C1 5000

S1 C2 6000

S2 C3 7000

S2 C4 8000

Page 9: Sql

9

SUPER KEY Set of attributes used to differentiate records.

Super keys are :- cid , fee , (cid,sid) , (cid,fee) , (sid,fee) Every candidate key is super key but every super key is not candidate

key.

Sid cid Fee

S1 C1 5000

S1 C2 6000

S2 C3 7000

S2 C4 8000

Page 10: Sql

10

UNIQUE KEY Set of one or more fields/columns of a table that uniquely identify a

record. It is like a primary key but it can accept only one null value and it cannot have duplicate values.

Can have more than one unique key constraint per table. One NULL is allowed because null is unique in itself, hence like similar

to primary key.

Page 11: Sql

11

UNIQUE KEY(Contd.) SYNTAX TO CREATE UNIQUE KEY

CREATE TABLE roll (id int(11) NOT NULL AUTO_INCREMENT,surname varchar(100) NOT NULL,PRIMARY KEY(id),UNIQUE KEY(roll)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Mysql InnoDB engine allows multiple null values for unique keys. Depending on the storage engine null may or may not be seen as a

unique value. BDB engine doesn’t allow multiple null whereas MYISAM & InnoDB

engine allows multiple nulls for unique key constraint.

Page 12: Sql

12

FOREIGN KEY A relation r1 may include among it’s attribute the primary key of an

other relation say r2, the attribute is called foreign key from r1 referencing r2.

r1 – referencing relationr2 – referenced relation

Page 13: Sql

13

FOREIGN KEY(Contd.)CREATE TABLE roll (id int(11) NOT NULL AUTO_INCREMENT,surname varchar(100) NOT NULL,PRIMARY KEY(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE student (id int(11) NOT NULL AUTO_INCREMENT,rollno int(11) NOT NULL,name varchar(100) NOT NULL,PRIMARY KEY(id),FOREIGN KEY(rollno) REFERENCES roll(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Page 14: Sql

14

FOREIGN KEY(Contd.)

ID SURNAME ID rollno name

REFERENCING RELATIONREFERENCED RELATION

Page 15: Sql

15

REFERENTIAL INTEGRITY CONSTRAINT ON DELETE NO ACTION ON DELETE CASCADE ON DELETE SET NULL

CREATE TABLE student (id int(11) NOT NULL AUTO_INCREMENT,rollno int(11) NOT NULL,name varchar(100) NOT NULL,PRIMARY KEY(id),FOREIGN KEY(rollno) REFERENCES roll(id) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Page 16: Sql

16

DROP FOREIGN KEYSHOW CREATE TABLE student; //will give you foreign keys name

tablename_ibfk_[number] //shorthand naming convention for

InnoDB engine

ALTER TABLE student DROP FOREIGN KEY [foreign key name]

Page 17: Sql

17

SIMPLE SQL QUERYSELECT table1.A, table1.B, table2.CFROM table1, table2WHERE table1.B = table2.BGROUP BY(attribute)HAVING(condition)ORDER BY(attribute(desc))

Page 18: Sql

18

ORDER OF QUERY EXECUTION6) SELECT table1.A, table1.B, table2.C1) FROM table1, table22) WHERE table1.B = table2.B3) GROUP BY(attribute)4) HAVING(condition)5) ORDER BY(attribute(desc))

Page 19: Sql

19

EXECUTION OF AN SQL QUERY

A B

1 2

3 4

5 6

A B

2 3

4 5

9 10

A B B C

1 2 2 3

1 2 4 5

1 2 9 10

3 4 2 3

3 4 4 5

3 4 9 10

5 6 2 3

5 6 4 5

5 6 9 10

TABLE 1

TABLE 2

TABLE 1 X TABLE 2

CARTESIAN PRODUCT

Page 20: Sql

20

TRADE OFF BETWEEN TIME AND SPACE If a table has 5000000 entries and joins with another table with same

number of entries, then the joined table(table formed with cartesian product) will contain 25 trillion entries.

Query performances increases with multiple joins but it requires more resources. Depending on the requirement and availability of resources, one should how joins should be used.

Page 21: Sql

21

JOINS JOINS are used to combine rows from two or more tables to save

time(improves query performance).

TYPES OF JOINS INNER JOIN

LEFT OUTER JOIN OUTER JOIN RIGHT OUTER JOIN

FULL OUTER JOIN

Page 22: Sql

22

JOINS(Contd.) JOINS is nothing but cartesian product of two or more tables

A B C

1 2 3

3 1 2

A B C

2 3 4

2 5 1

A B C B C D

1 2 3 2 3 4

1 2 3 2 5 1

3 1 2 2 5 1

3 1 2 2 3 4

R : S :

R JOIN S :

Page 23: Sql

23

JOINS(Contd.)

Page 24: Sql

24

JOINS(Contd.)SELECT person.lastname, person.firstname, orders.ordernoFROM persons INNER JOIN ordersON persons.pid = orders.pid

SELECT person.lastname, person.firstname, orders.ordernoFROM persons, ordersWHERE persons.pid = orders.pid

Page 25: Sql

25

JOINS(Contd.)EXPLICIT JOINSELECT person.lastname, person.firstname, orders.ordernoFROM persons INNER JOIN ordersON persons.pid = orders.pid

IMPLICIT JOIN (ANSI SQL 92 SYNTAX)SELECT person.lastname, person.firstname, orders.ordernoFROM persons, ordersWHERE persons.pid = orders.pid

Page 26: Sql

26

JOINS(Contd.) NATURAL JOIN works same as JOIN but it eliminates duplicate

columns after matching

SELECT * FROM student JOIN roll // simple cartesian product

SELECT * FROM student NATURAL JOIN roll; // no duplicates and checks for matching fields

SELECT * FROM student, roll //duplicates and checks for WHERE student.id = roll.id; matching fields

Page 27: Sql

27

JOINS(Contd.) SELECT * FROM student, roll; //cartesian product

SELECT * FROM student JOIN roll; //cartesian product

SELECT * FROM student JOIN roll //cartesian product, duplicates, with on ON student.id = roll.id; condition only relevant data

SELECT * FROM student INNER JOIN roll //cartesian product, duplicates, ON student.id = roll.id; with on condition only relevant data, without on condition only cartesian product

Page 28: Sql

28

JOINS(Contd.) SELECT * FROM roll NATURAL LEFT OUTER JOIN student;

SELECT * FROM roll NATURAL RIGHT OUTER JOIN student;

In MYSQL FULL OUTER JOIN is implemented by UNION of LEFT OUTER JOIN AND RIGHT OUTER JOIN

Page 29: Sql

29

JOINS – SELF JOIN The SQL SELF JOIN is used to join a table to itself as if the table were two

tables, temporarily renaming at least one table in the SQL statement.

Name of all employee that are from same location from where A belong?

NAME LOCATION

A New york

B Canada

C New york

Employee :

Page 30: Sql

30

JOINS – SELF JOIN(Contd.)

APPROACH – 1 SELECT location FROM employee WHERE name = ‘A’ ; SELECT name FROM employee WHERE location = [x];

APPROACH – 2 NESTED QUERY

SELECT name FROM employee WHERE location IN( SELECT location FROM employee WHERE name = ‘A’);

Page 31: Sql

31

JOINS – SELF JOIN(Contd.) APPROACH – 3

SELF JOINSELECT e1.nameFROM employee e1, employee e2WHERE e1.location = e2.location AND e2.name = ‘A’;

SELF JOIN must have aliases.

NAME LOCATION NAME LOCATIONA New york A New yorkB Canada A New yorkC New york A New yorkA New york B CanadaB Canada B CanadaC New york B CanadaA New york C New yorkB Canada C New yorkC New york C New york

e1 e2

Page 32: Sql

32

TRIGGERS A trigger is a statement that the system executes automatically as a side effect of

modification to the database.

SYNTAX FOR TRIGGER CREATIONDELIMITER // CREATE TRIGGER `insertmasterproducttax` AFTER INSERT ON `producttax`FOR EACH ROW BEGININSERT INTO transaction.producttaxSETtransaction.producttax.id = NEW.id,transaction.producttax.product_id = NEW.product_id,transaction.producttax.taxtype_id = NEW.taxtype_id;END;//DELIMITER;

Page 33: Sql

33

MYSQL STORAGE ENGINE InnoDB – foreign key constraint transaction support ACID properties support MYISAM – no foreign key constraint no transaction support Another big difference is concurrency, MYISAM supports table level locking

whereas InnoDB supports row level locking With MYISAM, a DML statement will obtain an exclusive lock on the table, and

while that lock is held, no other session can perform a SELECT or a DML operation on that table.

InnoDB is slow but supports commit, savepoint and rollback operations whereas MYISAM is fast but does not support any of these operations.

Page 34: Sql

34

CURSORS cursor is a database objects to retrieve data from a result set one row

at a time, instead of the T-SQL commands that operate on all the rows in the result set at one time. We use cursor when we need to update records in a database table in singleton fashion means row by row.

Cursor acts as an iterator over a collection of rows in the result set. The select statement can return multiple rows as a query result. If you

want to process single row at a time then you can define an explicit cursor for this select statement.

Explicit cursors are memory areas which acts as a handle or pointer to context area and allows to fetch and process query results row by row.

Page 35: Sql

35

CURSORS(Contd.) Each time you fetch a row from the cursor, it results in a network

roundtrip, whereas as a normal SELECT query makes only one round trip, however large the result set is.

Normal select Query fetches all rows in one go while cursorfetches one row at a time.

Page 36: Sql

36

CURSORS(Contd.)

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 -- 5000 hike Salary between 40000 and 55000 -- 7000 hike Salary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine each employee’s salary and update his salary according to the above formula.

Page 37: Sql

37

FLOWCHART OF CURSOR

Page 38: Sql

38

MULTIPLE UPDATE STATEMENTS

UPDATE [tablename] SET salary = CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000END

Page 39: Sql

39

CURSORS - disadvantages A cursor is a memory resident set of pointers -- meaning it occupies

memory from your system that may be available for other processes. Poorly written cursors can completely deplete available memory.

you must release the resources that are allocated to the cursor variables.

A cursor allow us to use set of result-sets returned by mysql query in one by one pattern. With the use of cursor we can perform operations on set of resultset on each returned row.Like you are fetching multiple data by any operation and you want to operate those data in loop. so with the use of cursor you can loops through the results.Cursor is convenient to use when you are performing on a complex result-set.