SlideShare a Scribd company logo
INTERNAL TECHNICAL
TRAINING SESSION FOR
SQL
BY :- RAHUL KUMAR SINGH
(JAVA TEAM)
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.
2
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
3
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.
4
Sid cid Fee
S1 C1 5000
S1 C2 6000
S2 C2 7000
S2 C3 7000
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).
5
Sid cid Fee
S1 C1 5000
S1 C2 6000
S2 C3 7000
S2 C4 8000
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?
6
Sid cid Fee
S1 C1 5000
S1 C2 6000
S2 C2 7000
S2 C3 7000
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 KEY
CREATE TABLE roll (
id int(11) NOT NULL AUTO_INCREMENT,
surname varchar(100) NOT NULL,
PRIMARY KEY(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7
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.
8
Sid cid Fee
S1 C1 5000
S1 C2 6000
S2 C3 7000
S2 C4 8000
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.
9
Sid cid Fee
S1 C1 5000
S1 C2 6000
S2 C3 7000
S2 C4 8000
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.
10
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.
11
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 relation
r2 – referenced relation
12
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;
13
FOREIGN KEY(Contd.)
ID SURNAME
14
ID rollno name
REFERENCING RELATION
REFERENCED RELATION
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;
15
DROP FOREIGN KEY
SHOW 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]
16
SIMPLE SQL QUERY
SELECT table1.A, table1.B, table2.C
FROM table1, table2
WHERE table1.B = table2.B
GROUP BY(attribute)
HAVING(condition)
ORDER BY(attribute(desc))
17
ORDER OF QUERY EXECUTION
6) SELECT table1.A, table1.B, table2.C
1) FROM table1, table2
2) WHERE table1.B = table2.B
3) GROUP BY(attribute)
4) HAVING(condition)
5) ORDER BY(attribute(desc))
18
EXECUTION OF AN SQL QUERY
A B
1 2
3 4
5 6
19
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
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.
20
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
21
JOINS(Contd.)
 JOINS is nothing but cartesian product of two or more tables
22
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 :
JOINS(Contd.)
23
JOINS(Contd.)
SELECT person.lastname, person.firstname, orders.orderno
FROM persons INNER JOIN orders
ON persons.pid = orders.pid
SELECT person.lastname, person.firstname, orders.orderno
FROM persons, orders
WHERE persons.pid = orders.pid
24
JOINS(Contd.)
EXPLICIT JOIN
SELECT person.lastname, person.firstname, orders.orderno
FROM persons INNER JOIN orders
ON persons.pid = orders.pid
IMPLICIT JOIN (ANSI SQL 92 SYNTAX)
SELECT person.lastname, person.firstname, orders.orderno
FROM persons, orders
WHERE persons.pid = orders.pid
25
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
26
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
27
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
28
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?
29
NAME LOCATION
A New york
B Canada
C New york
Employee :
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’);
30
JOINS – SELF JOIN(Contd.)
 APPROACH – 3
 SELF JOIN
SELECT e1.name
FROM employee e1, employee e2
WHERE e1.location = e2.location
AND e2.name = ‘A’;
 SELF JOIN must have aliases.
31
NAME LOCATION NAME LOCATION
A New york A New york
B Canada A New york
C New york A New york
A New york B Canada
B Canada B Canada
C New york B Canada
A New york C New york
B Canada C New york
C New york C New york
e1 e2
TRIGGERS
 A trigger is a statement that the system executes automatically as a side
effect of modification to the database.
 SYNTAX FOR TRIGGER CREATION
DELIMITER //
CREATE TRIGGER `insertmasterproducttax` AFTER INSERT ON `producttax`
FOR EACH ROW BEGIN
INSERT INTO transaction.producttax
SET
transaction.producttax.id = NEW.id,
transaction.producttax.product_id = NEW.product_id,
transaction.producttax.taxtype_id = NEW.taxtype_id;
END;
//
DELIMITER;
32
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.
33
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.
34
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 cursor
fetches one row at a time.
35
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.
36
FLOWCHART OF CURSOR
37
MULTIPLE UPDATE STATEMENTS
UPDATE [tablename] SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END
38
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.
39

More Related Content

What's hot

Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
amitabros
 
SQL Sort Notes
SQL Sort NotesSQL Sort Notes
SQL Sort Notes
ShivaAdasule
 
UKOUG Tech14 - Using Database In-Memory Column Store with Complex Datatypes
UKOUG Tech14 - Using Database In-Memory Column Store with Complex DatatypesUKOUG Tech14 - Using Database In-Memory Column Store with Complex Datatypes
UKOUG Tech14 - Using Database In-Memory Column Store with Complex Datatypes
Marco Gralike
 
Entity Attribute Value (Eav)
Entity   Attribute   Value (Eav)Entity   Attribute   Value (Eav)
Entity Attribute Value (Eav)Tâm
 
SQL Transactions - What they are good for and how they work
SQL Transactions - What they are good for and how they workSQL Transactions - What they are good for and how they work
SQL Transactions - What they are good for and how they work
Markus Winand
 
Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queries
PRAKHAR JHA
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
Achmad Solichin
 
Some OOP paradigms & SOLID
Some OOP paradigms & SOLIDSome OOP paradigms & SOLID
Some OOP paradigms & SOLID
Julio Martinez
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)
Vidyasagar Mundroy
 
Dbms lab Manual
Dbms lab ManualDbms lab Manual
Dbms lab Manual
Vivek Kumar Sinha
 
Erlang for data ops
Erlang for data opsErlang for data ops
Erlang for data ops
mnacos
 
Dbms practical list
Dbms practical listDbms practical list
Dbms practical list
RajSingh734307
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
Swapnali Pawar
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
Ram Sagar Mourya
 
SQL Differences SQL Interview Questions
SQL Differences  SQL Interview QuestionsSQL Differences  SQL Interview Questions
SQL Differences SQL Interview Questions
MLR Institute of Technology
 
Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)
Vidyasagar Mundroy
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
Mohamed Mosaad
 
Assignment#07
Assignment#07Assignment#07
Assignment#07
Sunita Milind Dol
 

What's hot (19)

Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
SQL Sort Notes
SQL Sort NotesSQL Sort Notes
SQL Sort Notes
 
UKOUG Tech14 - Using Database In-Memory Column Store with Complex Datatypes
UKOUG Tech14 - Using Database In-Memory Column Store with Complex DatatypesUKOUG Tech14 - Using Database In-Memory Column Store with Complex Datatypes
UKOUG Tech14 - Using Database In-Memory Column Store with Complex Datatypes
 
Entity Attribute Value (Eav)
Entity   Attribute   Value (Eav)Entity   Attribute   Value (Eav)
Entity Attribute Value (Eav)
 
SQL Transactions - What they are good for and how they work
SQL Transactions - What they are good for and how they workSQL Transactions - What they are good for and how they work
SQL Transactions - What they are good for and how they work
 
Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queries
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
 
Some OOP paradigms & SOLID
Some OOP paradigms & SOLIDSome OOP paradigms & SOLID
Some OOP paradigms & SOLID
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)
 
Drupal7 dbtng
Drupal7  dbtngDrupal7  dbtng
Drupal7 dbtng
 
Dbms lab Manual
Dbms lab ManualDbms lab Manual
Dbms lab Manual
 
Erlang for data ops
Erlang for data opsErlang for data ops
Erlang for data ops
 
Dbms practical list
Dbms practical listDbms practical list
Dbms practical list
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
 
SQL Differences SQL Interview Questions
SQL Differences  SQL Interview QuestionsSQL Differences  SQL Interview Questions
SQL Differences SQL Interview Questions
 
Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
Assignment#07
Assignment#07Assignment#07
Assignment#07
 

Similar to Sql

Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
Nitesh Singh
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
FilestreamFilestream
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007paulguerin
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server iiIblesoft
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
YitbarekMurche
 
6_SQL.pdf
6_SQL.pdf6_SQL.pdf
6_SQL.pdf
LPhct2
 
Lab
LabLab
DBMS_INTRODUCTION OF SQL
DBMS_INTRODUCTION OF SQLDBMS_INTRODUCTION OF SQL
DBMS_INTRODUCTION OF SQL
Azizul Mamun
 
Interview Questions.pdf
Interview Questions.pdfInterview Questions.pdf
Interview Questions.pdf
TarunKumar893717
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
Stewart Rogers
 
Sql intro
Sql introSql intro
Sql introglubox
 
DDL and DML statements.pptx
DDL and DML statements.pptxDDL and DML statements.pptx
DDL and DML statements.pptx
Karthick Panneerselvam
 

Similar to Sql (20)

Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
MySQL Indexes
MySQL IndexesMySQL Indexes
MySQL Indexes
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
6_SQL.pdf
6_SQL.pdf6_SQL.pdf
6_SQL.pdf
 
Lab
LabLab
Lab
 
Query
QueryQuery
Query
 
DBMS_INTRODUCTION OF SQL
DBMS_INTRODUCTION OF SQLDBMS_INTRODUCTION OF SQL
DBMS_INTRODUCTION OF SQL
 
Ch3
Ch3Ch3
Ch3
 
Sql
SqlSql
Sql
 
Interview Questions.pdf
Interview Questions.pdfInterview Questions.pdf
Interview Questions.pdf
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Sql intro
Sql introSql intro
Sql intro
 
DDL and DML statements.pptx
DDL and DML statements.pptxDDL and DML statements.pptx
DDL and DML statements.pptx
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
Sql basics
Sql  basicsSql  basics
Sql basics
 

Recently uploaded

The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 

Recently uploaded (20)

The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 

Sql

  • 1. INTERNAL TECHNICAL TRAINING SESSION FOR SQL BY :- RAHUL KUMAR SINGH (JAVA TEAM)
  • 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. 2
  • 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 3
  • 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. 4 Sid cid Fee S1 C1 5000 S1 C2 6000 S2 C2 7000 S2 C3 7000
  • 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). 5 Sid cid Fee S1 C1 5000 S1 C2 6000 S2 C3 7000 S2 C4 8000
  • 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? 6 Sid cid Fee S1 C1 5000 S1 C2 6000 S2 C2 7000 S2 C3 7000
  • 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 KEY CREATE TABLE roll ( id int(11) NOT NULL AUTO_INCREMENT, surname varchar(100) NOT NULL, PRIMARY KEY(id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 7
  • 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. 8 Sid cid Fee S1 C1 5000 S1 C2 6000 S2 C3 7000 S2 C4 8000
  • 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. 9 Sid cid Fee S1 C1 5000 S1 C2 6000 S2 C3 7000 S2 C4 8000
  • 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. 10
  • 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. 11
  • 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 relation r2 – referenced relation 12
  • 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; 13
  • 14. FOREIGN KEY(Contd.) ID SURNAME 14 ID rollno name REFERENCING RELATION REFERENCED RELATION
  • 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; 15
  • 16. DROP FOREIGN KEY SHOW 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] 16
  • 17. SIMPLE SQL QUERY SELECT table1.A, table1.B, table2.C FROM table1, table2 WHERE table1.B = table2.B GROUP BY(attribute) HAVING(condition) ORDER BY(attribute(desc)) 17
  • 18. ORDER OF QUERY EXECUTION 6) SELECT table1.A, table1.B, table2.C 1) FROM table1, table2 2) WHERE table1.B = table2.B 3) GROUP BY(attribute) 4) HAVING(condition) 5) ORDER BY(attribute(desc)) 18
  • 19. EXECUTION OF AN SQL QUERY A B 1 2 3 4 5 6 19 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
  • 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. 20
  • 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 21
  • 22. JOINS(Contd.)  JOINS is nothing but cartesian product of two or more tables 22 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 :
  • 24. JOINS(Contd.) SELECT person.lastname, person.firstname, orders.orderno FROM persons INNER JOIN orders ON persons.pid = orders.pid SELECT person.lastname, person.firstname, orders.orderno FROM persons, orders WHERE persons.pid = orders.pid 24
  • 25. JOINS(Contd.) EXPLICIT JOIN SELECT person.lastname, person.firstname, orders.orderno FROM persons INNER JOIN orders ON persons.pid = orders.pid IMPLICIT JOIN (ANSI SQL 92 SYNTAX) SELECT person.lastname, person.firstname, orders.orderno FROM persons, orders WHERE persons.pid = orders.pid 25
  • 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 26
  • 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 27
  • 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 28
  • 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? 29 NAME LOCATION A New york B Canada C New york Employee :
  • 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’); 30
  • 31. JOINS – SELF JOIN(Contd.)  APPROACH – 3  SELF JOIN SELECT e1.name FROM employee e1, employee e2 WHERE e1.location = e2.location AND e2.name = ‘A’;  SELF JOIN must have aliases. 31 NAME LOCATION NAME LOCATION A New york A New york B Canada A New york C New york A New york A New york B Canada B Canada B Canada C New york B Canada A New york C New york B Canada C New york C New york C New york e1 e2
  • 32. TRIGGERS  A trigger is a statement that the system executes automatically as a side effect of modification to the database.  SYNTAX FOR TRIGGER CREATION DELIMITER // CREATE TRIGGER `insertmasterproducttax` AFTER INSERT ON `producttax` FOR EACH ROW BEGIN INSERT INTO transaction.producttax SET transaction.producttax.id = NEW.id, transaction.producttax.product_id = NEW.product_id, transaction.producttax.taxtype_id = NEW.taxtype_id; END; // DELIMITER; 32
  • 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. 33
  • 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. 34
  • 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 cursor fetches one row at a time. 35
  • 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. 36
  • 38. MULTIPLE UPDATE STATEMENTS UPDATE [tablename] SET salary = CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000 WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000 WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000 END 38
  • 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. 39