SlideShare a Scribd company logo
1 of 27
6 SQL SERVER: JOININGDATABASETABLES
SQL JOIN: Prerequisites Before we start with SQL Joints, let us go through a few basic DBMS concepts: Primary Key: A Primary key is a field/attribute in a table which is used to uniquely identify a record Eg: Consider a dream database Here, a particular record can be uniquely located using the DreamNumber and hence, it is taken as the Primary key. If there are more than fields, eligible of being the primary key, the decision of choosing one among them lies with the DB designer
SQL JOIN: Prerequisites Foreign Key: A Foreign key is a field/attribute in one table which is used as a primary key in another table Eg: Consider a dream database Every foreign key value must be present as a primary key in the referenced table. Eg: A dream number ‘3’ isn’t possible in ‘Luck Table’ unless such a dream number exists in the ‘Dream Table’ Dream Table Notice that foreign key entries can repeat( where-as primary key entries can’t!) Foreign Key Primary Key Luck Table Refer-ences
SQL JOIN: Prerequisites 3.SELECT Statement The Select statement, as the name specifies, is used to select records from a table. The Syntax is: Select <FieldName> from  <TableName>; To select all records from a table: Select * from tableName Eg: select * from DreamTable lists the entire table Example:  To select Select the Dreams and Times from this table: select dreams, time from DreamTable
What does Joining Tables mean? Joining tables means joining the data contained in the tables. The Programmer may specify various restrictions and rules that the joining must follow so as to suite the Programmer’s needs. For example, suppose that some time in the future, the IT Giants Microsoft and Google merge into a new company ‘Moogle’, it would be easy to join the employee tables of both the companies, as follows:
SQL JOIN An SQL JOIN command combines records from two or more tables in a database. Types of Joins:
Inner Join An SQL JOIN command combines records from two or more tables in a database. Alias: JOIN (Both ‘Inner Join’ and ‘Join’ commands can be used) The Inner join returns a column from each table only if there exists an exact match on the other table. Illustration: Consider the ‘Moogle’ Database (See Slide 1) Moogle Employee Tale Moogle Department Table NOTE: Let us follow the convention that if a field is underlined, it denotes a primary key. If it is italicized then it denotes a foreign key.
Inner Join Illustration: Now, on performing the Inner joint on the above given table: Moogle Employee Tale Moogle Department Table Let us call the field that is used for joining the tables as joining field Join based on the EmpID field New Table (Inner Joint)
Inner Join The SQL Syntax for an Inner join is as follows: Syntax: For inner-joining of tables table1 and table2, the SQL Command is: select * from table1inner join table2 on table1.Field= table2.Field; Hence, for the creation of the Moogle Table(Previous Slide), the SQL Command is: Select * from EmpTable inner join DepTable on  EmpTable.EmpID = DepTable.EmpID Bottom-line: Inner Joints are highly strict. They only accept records that have perfect matching in the other table.
Inner Join This is an illustration of an Inner Joint:
Outer Join The SQL Syntax for an Inner join is as follows: Outer Join:  It returns all rows from the first table stated in the join operation; only returns data for rows from the second stated table where there is a matching value. This can result in null values in the result when the first stated table in the join has a row with no matching row(s) in the second stated table. Types of Outer Join:
Left Outer Join A Left outer join is a type of an outer join where all the records of the first table are considered and are joined with matches(if found) from the second table. If a match for a record (for the field of joining) is not found in the second table, null values are assigned for those fields. Illustration: Moogle Employee Tale Moogle Department Table Left outer Join based on the EmpID field Can you guess what the result might be? Go to the next slide to find out!
Left Outer Join Left outer Join based on the EmpID field
Understanding Left Outer Join The Example would have made clear the mechanism of the left outer join. As an extra measure, let us see a simple algorithm for the left outer join: Start Get two tables to be joint (table1 and table2) Consider table1:  	Consider every record in table1: 		search for a match for that record in table 2, 		for a given value of the joining field 			If found, append that record of 				   table2 to that of table1 			Else assign null for unmatched values end
Understanding Left Outer Join Confused with the algo? Lets make it clear with an example: Consider Harry who maintains a database of the gifts that he got for his birthday. He wants to join the table so that he could find the addresses of people who gifted him.  The field of joining will be Name of the person as it is common in both tables and is the correct choice for the given problem. Table2: Person Table Table1: Gifts table
Understanding Left Outer Join
Left Outer Join Having understood the concept behind left outer joins, its now time to see the sql command behind this: SQL Command: Select * from Table1 left outer join Table2       on Table1.JoiningFieldName1 = Table2.JoiningFieldName2; Now let us consider the other types of joints.
Right Outer Join A Right outer join is a type of an outer join where all the records of the second (which is on the right side) table are considered and are joined with matches(if found) from the first table. If a match for a record (for the field of joining) is not found in the first table, null values are assigned for those fields. Illustration: Moogle Employee Tale Moogle Department Table Right outer Join based on the EmpID field Now, Can you deduce what the result might be?
Right Outer Join Right outer Join based on the EmpID field NOTE: Having understood the left outer join, it is easy to understand the right outer joins. If you find any difficulty, please return to left outer joins.
Right Outer Join The SQL command for the right outer join resembles the left outer join Select * from Table1 right outer join Table2       on Table1.JoiningFieldName1 = Table2.JoiningFieldName2; Now let us consider the final outer join type: Full outer join
Full Outer Join A Full outer join is used in situations where two tables are to be combined without loss of data.  In  Full outer join, all records from the first table and all records from the second table are considered. If there is a common joining field value found, the records are combined. Else, the records are treated as separate in the new joint table, with NULL values for the left out fields. Let us see an illustration: 	Consider the Gift table problem that we saw in slide.no: 15
Full Outer Join
Full Outer Join The SQL command for the full outer join resembles the right outer join Select * from Table1 full outer join Table2       on Table1.JoiningFieldName1 = Table2.JoiningFieldName2; These are the basic join types. To add fun, let us consider an additional join that SQL Server provides: The Cross join
Cross Join A Cross Join is used to produce a Cartesian product between two tables. In mathematical terms, two sets ‘A’ and ‘B’ under cross product means that every variable in set  A will be combined with every variable in set B. The same can be applied to tables here. The SQL command for the cross join is as follows: Select * from Table1 cross join Table2; Illustration: See the next slide NOTE: Do remember to use the go command to run any SQL Statement. You can type a list of commands and run them sequentially with a single go statement also.
Cross Join Illustration: Consider an online dating database. All possible matches between the boys and girls following tables are needed. Here, a cross join would prove useful to find all possible combinations. Boys Girls Boys X Girls X
Summary 6. Joining Databases ,[object Object]
  Inner Join

More Related Content

What's hot

What's hot (20)

MYSQL join
MYSQL joinMYSQL join
MYSQL join
 
Inner join and outer join
Inner join and outer joinInner join and outer join
Inner join and outer join
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
 
Advanced sql
Advanced sqlAdvanced sql
Advanced sql
 
Joins And Its Types
Joins And Its TypesJoins And Its Types
Joins And Its Types
 
Oracle: Joins
Oracle: JoinsOracle: Joins
Oracle: Joins
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
Sql and Sql commands
Sql and Sql commandsSql and Sql commands
Sql and Sql commands
 
Sql server ___________session_17(indexes)
Sql server  ___________session_17(indexes)Sql server  ___________session_17(indexes)
Sql server ___________session_17(indexes)
 
Index in sql server
Index in sql serverIndex in sql server
Index in sql server
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
 
SQL select clause
SQL select clauseSQL select clause
SQL select clause
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Group By, Order By, and Aliases in SQL
Group By, Order By, and Aliases in SQLGroup By, Order By, and Aliases in SQL
Group By, Order By, and Aliases in SQL
 
Chapter 4 Structured Query Language
Chapter 4 Structured Query LanguageChapter 4 Structured Query Language
Chapter 4 Structured Query Language
 
SQL Join Basic
SQL Join BasicSQL Join Basic
SQL Join Basic
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 

Viewers also liked

Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Serverprogrammings guru
 
Sql server JOIN
Sql server JOINSql server JOIN
Sql server JOINRiteshkiit
 
SQL Joins and Query Optimization
SQL Joins and Query OptimizationSQL Joins and Query Optimization
SQL Joins and Query OptimizationBrian Gallagher
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Beat Signer
 
SQL Joinning.Database
SQL Joinning.DatabaseSQL Joinning.Database
SQL Joinning.DatabaseUmme habiba
 
C5 Réseaux : vlsm-classe-nat
C5 Réseaux : vlsm-classe-natC5 Réseaux : vlsm-classe-nat
C5 Réseaux : vlsm-classe-natPRONETIS
 
Join(sql)
Join(sql)Join(sql)
Join(sql)인 이
 
Sql basics
Sql basicsSql basics
Sql basicsKumar
 
Subconsultas y consultas multitabla en bases de datos de sql server
Subconsultas y consultas multitabla en bases de datos de sql serverSubconsultas y consultas multitabla en bases de datos de sql server
Subconsultas y consultas multitabla en bases de datos de sql serverZairaDMM
 
Introduction to MySQL and phpMyAdmin
Introduction to MySQL and phpMyAdminIntroduction to MySQL and phpMyAdmin
Introduction to MySQL and phpMyAdminDrake Huang
 

Viewers also liked (20)

Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
 
Sql server JOIN
Sql server JOINSql server JOIN
Sql server JOIN
 
SQL JOIN Explained Visually
SQL JOIN Explained VisuallySQL JOIN Explained Visually
SQL JOIN Explained Visually
 
Join
JoinJoin
Join
 
joins in database
 joins in database joins in database
joins in database
 
SQL
SQLSQL
SQL
 
SQL Joins and Query Optimization
SQL Joins and Query OptimizationSQL Joins and Query Optimization
SQL Joins and Query Optimization
 
Databases: Normalisation
Databases: NormalisationDatabases: Normalisation
Databases: Normalisation
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
 
SQL Joinning.Database
SQL Joinning.DatabaseSQL Joinning.Database
SQL Joinning.Database
 
Database normalisation
Database normalisationDatabase normalisation
Database normalisation
 
Database normalisation
Database normalisationDatabase normalisation
Database normalisation
 
C5 Réseaux : vlsm-classe-nat
C5 Réseaux : vlsm-classe-natC5 Réseaux : vlsm-classe-nat
C5 Réseaux : vlsm-classe-nat
 
My sql join
My sql joinMy sql join
My sql join
 
SQL JOINS- Reena P V
SQL JOINS- Reena P VSQL JOINS- Reena P V
SQL JOINS- Reena P V
 
Join(sql)
Join(sql)Join(sql)
Join(sql)
 
Sql basics
Sql basicsSql basics
Sql basics
 
Subconsultas y consultas multitabla en bases de datos de sql server
Subconsultas y consultas multitabla en bases de datos de sql serverSubconsultas y consultas multitabla en bases de datos de sql server
Subconsultas y consultas multitabla en bases de datos de sql server
 
Sql basics
Sql basicsSql basics
Sql basics
 
Introduction to MySQL and phpMyAdmin
Introduction to MySQL and phpMyAdminIntroduction to MySQL and phpMyAdmin
Introduction to MySQL and phpMyAdmin
 

Similar to MS Sql Server: Joining Databases

Similar to MS Sql Server: Joining Databases (20)

Join in SQL - Inner, Self, Outer Join
Join in SQL - Inner, Self, Outer JoinJoin in SQL - Inner, Self, Outer Join
Join in SQL - Inner, Self, Outer Join
 
joins and subqueries in big data analysis
joins and subqueries in big data analysisjoins and subqueries in big data analysis
joins and subqueries in big data analysis
 
database .pptx
database .pptxdatabase .pptx
database .pptx
 
Day-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptxDay-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptx
 
SQL PPT on joins
SQL PPT on joinsSQL PPT on joins
SQL PPT on joins
 
Assignment 4
Assignment 4Assignment 4
Assignment 4
 
JOINS.pptx
JOINS.pptxJOINS.pptx
JOINS.pptx
 
Joins
JoinsJoins
Joins
 
Presentation of Joins In Database
Presentation of Joins In DatabasePresentation of Joins In Database
Presentation of Joins In Database
 
Joins
JoinsJoins
Joins
 
Database design normalization note and exercise
Database design normalization note and exerciseDatabase design normalization note and exercise
Database design normalization note and exercise
 
Advance database system(part 8)
Advance database system(part 8)Advance database system(part 8)
Advance database system(part 8)
 
Excel Tutorials - VLOOKUP and HLOOKUP Functions
Excel Tutorials - VLOOKUP and HLOOKUP FunctionsExcel Tutorials - VLOOKUP and HLOOKUP Functions
Excel Tutorials - VLOOKUP and HLOOKUP Functions
 
SQL JOIN.pptx
SQL JOIN.pptxSQL JOIN.pptx
SQL JOIN.pptx
 
Sql joins
Sql joinsSql joins
Sql joins
 
types of SQL Joins
 types of SQL Joins types of SQL Joins
types of SQL Joins
 
V19 join method-c
V19 join method-cV19 join method-c
V19 join method-c
 
SQL Tips Joins.pptx
SQL Tips Joins.pptxSQL Tips Joins.pptx
SQL Tips Joins.pptx
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
 
Chapter9 more on database and sql
Chapter9 more on database and sqlChapter9 more on database and sql
Chapter9 more on database and sql
 

More from DataminingTools Inc

AI: Introduction to artificial intelligence
AI: Introduction to artificial intelligenceAI: Introduction to artificial intelligence
AI: Introduction to artificial intelligenceDataminingTools Inc
 
Data Mining: Text and web mining
Data Mining: Text and web miningData Mining: Text and web mining
Data Mining: Text and web miningDataminingTools Inc
 
Data Mining: Mining stream time series and sequence data
Data Mining: Mining stream time series and sequence dataData Mining: Mining stream time series and sequence data
Data Mining: Mining stream time series and sequence dataDataminingTools Inc
 
Data Mining: Mining ,associations, and correlations
Data Mining: Mining ,associations, and correlationsData Mining: Mining ,associations, and correlations
Data Mining: Mining ,associations, and correlationsDataminingTools Inc
 
Data Mining: Graph mining and social network analysis
Data Mining: Graph mining and social network analysisData Mining: Graph mining and social network analysis
Data Mining: Graph mining and social network analysisDataminingTools Inc
 
Data warehouse and olap technology
Data warehouse and olap technologyData warehouse and olap technology
Data warehouse and olap technologyDataminingTools Inc
 

More from DataminingTools Inc (20)

Terminology Machine Learning
Terminology Machine LearningTerminology Machine Learning
Terminology Machine Learning
 
Techniques Machine Learning
Techniques Machine LearningTechniques Machine Learning
Techniques Machine Learning
 
Machine learning Introduction
Machine learning IntroductionMachine learning Introduction
Machine learning Introduction
 
Areas of machine leanring
Areas of machine leanringAreas of machine leanring
Areas of machine leanring
 
AI: Planning and AI
AI: Planning and AIAI: Planning and AI
AI: Planning and AI
 
AI: Logic in AI 2
AI: Logic in AI 2AI: Logic in AI 2
AI: Logic in AI 2
 
AI: Logic in AI
AI: Logic in AIAI: Logic in AI
AI: Logic in AI
 
AI: Learning in AI 2
AI: Learning in AI 2AI: Learning in AI 2
AI: Learning in AI 2
 
AI: Learning in AI
AI: Learning in AI AI: Learning in AI
AI: Learning in AI
 
AI: Introduction to artificial intelligence
AI: Introduction to artificial intelligenceAI: Introduction to artificial intelligence
AI: Introduction to artificial intelligence
 
AI: Belief Networks
AI: Belief NetworksAI: Belief Networks
AI: Belief Networks
 
AI: AI & Searching
AI: AI & SearchingAI: AI & Searching
AI: AI & Searching
 
AI: AI & Problem Solving
AI: AI & Problem SolvingAI: AI & Problem Solving
AI: AI & Problem Solving
 
Data Mining: Text and web mining
Data Mining: Text and web miningData Mining: Text and web mining
Data Mining: Text and web mining
 
Data Mining: Outlier analysis
Data Mining: Outlier analysisData Mining: Outlier analysis
Data Mining: Outlier analysis
 
Data Mining: Mining stream time series and sequence data
Data Mining: Mining stream time series and sequence dataData Mining: Mining stream time series and sequence data
Data Mining: Mining stream time series and sequence data
 
Data Mining: Mining ,associations, and correlations
Data Mining: Mining ,associations, and correlationsData Mining: Mining ,associations, and correlations
Data Mining: Mining ,associations, and correlations
 
Data Mining: Graph mining and social network analysis
Data Mining: Graph mining and social network analysisData Mining: Graph mining and social network analysis
Data Mining: Graph mining and social network analysis
 
Data warehouse and olap technology
Data warehouse and olap technologyData warehouse and olap technology
Data warehouse and olap technology
 
Data Mining: Data processing
Data Mining: Data processingData Mining: Data processing
Data Mining: Data processing
 

Recently uploaded

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Recently uploaded (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

MS Sql Server: Joining Databases

  • 1. 6 SQL SERVER: JOININGDATABASETABLES
  • 2. SQL JOIN: Prerequisites Before we start with SQL Joints, let us go through a few basic DBMS concepts: Primary Key: A Primary key is a field/attribute in a table which is used to uniquely identify a record Eg: Consider a dream database Here, a particular record can be uniquely located using the DreamNumber and hence, it is taken as the Primary key. If there are more than fields, eligible of being the primary key, the decision of choosing one among them lies with the DB designer
  • 3. SQL JOIN: Prerequisites Foreign Key: A Foreign key is a field/attribute in one table which is used as a primary key in another table Eg: Consider a dream database Every foreign key value must be present as a primary key in the referenced table. Eg: A dream number ‘3’ isn’t possible in ‘Luck Table’ unless such a dream number exists in the ‘Dream Table’ Dream Table Notice that foreign key entries can repeat( where-as primary key entries can’t!) Foreign Key Primary Key Luck Table Refer-ences
  • 4. SQL JOIN: Prerequisites 3.SELECT Statement The Select statement, as the name specifies, is used to select records from a table. The Syntax is: Select <FieldName> from <TableName>; To select all records from a table: Select * from tableName Eg: select * from DreamTable lists the entire table Example: To select Select the Dreams and Times from this table: select dreams, time from DreamTable
  • 5. What does Joining Tables mean? Joining tables means joining the data contained in the tables. The Programmer may specify various restrictions and rules that the joining must follow so as to suite the Programmer’s needs. For example, suppose that some time in the future, the IT Giants Microsoft and Google merge into a new company ‘Moogle’, it would be easy to join the employee tables of both the companies, as follows:
  • 6. SQL JOIN An SQL JOIN command combines records from two or more tables in a database. Types of Joins:
  • 7. Inner Join An SQL JOIN command combines records from two or more tables in a database. Alias: JOIN (Both ‘Inner Join’ and ‘Join’ commands can be used) The Inner join returns a column from each table only if there exists an exact match on the other table. Illustration: Consider the ‘Moogle’ Database (See Slide 1) Moogle Employee Tale Moogle Department Table NOTE: Let us follow the convention that if a field is underlined, it denotes a primary key. If it is italicized then it denotes a foreign key.
  • 8. Inner Join Illustration: Now, on performing the Inner joint on the above given table: Moogle Employee Tale Moogle Department Table Let us call the field that is used for joining the tables as joining field Join based on the EmpID field New Table (Inner Joint)
  • 9. Inner Join The SQL Syntax for an Inner join is as follows: Syntax: For inner-joining of tables table1 and table2, the SQL Command is: select * from table1inner join table2 on table1.Field= table2.Field; Hence, for the creation of the Moogle Table(Previous Slide), the SQL Command is: Select * from EmpTable inner join DepTable on EmpTable.EmpID = DepTable.EmpID Bottom-line: Inner Joints are highly strict. They only accept records that have perfect matching in the other table.
  • 10. Inner Join This is an illustration of an Inner Joint:
  • 11. Outer Join The SQL Syntax for an Inner join is as follows: Outer Join: It returns all rows from the first table stated in the join operation; only returns data for rows from the second stated table where there is a matching value. This can result in null values in the result when the first stated table in the join has a row with no matching row(s) in the second stated table. Types of Outer Join:
  • 12. Left Outer Join A Left outer join is a type of an outer join where all the records of the first table are considered and are joined with matches(if found) from the second table. If a match for a record (for the field of joining) is not found in the second table, null values are assigned for those fields. Illustration: Moogle Employee Tale Moogle Department Table Left outer Join based on the EmpID field Can you guess what the result might be? Go to the next slide to find out!
  • 13. Left Outer Join Left outer Join based on the EmpID field
  • 14. Understanding Left Outer Join The Example would have made clear the mechanism of the left outer join. As an extra measure, let us see a simple algorithm for the left outer join: Start Get two tables to be joint (table1 and table2) Consider table1: Consider every record in table1: search for a match for that record in table 2, for a given value of the joining field If found, append that record of table2 to that of table1 Else assign null for unmatched values end
  • 15. Understanding Left Outer Join Confused with the algo? Lets make it clear with an example: Consider Harry who maintains a database of the gifts that he got for his birthday. He wants to join the table so that he could find the addresses of people who gifted him. The field of joining will be Name of the person as it is common in both tables and is the correct choice for the given problem. Table2: Person Table Table1: Gifts table
  • 17. Left Outer Join Having understood the concept behind left outer joins, its now time to see the sql command behind this: SQL Command: Select * from Table1 left outer join Table2 on Table1.JoiningFieldName1 = Table2.JoiningFieldName2; Now let us consider the other types of joints.
  • 18. Right Outer Join A Right outer join is a type of an outer join where all the records of the second (which is on the right side) table are considered and are joined with matches(if found) from the first table. If a match for a record (for the field of joining) is not found in the first table, null values are assigned for those fields. Illustration: Moogle Employee Tale Moogle Department Table Right outer Join based on the EmpID field Now, Can you deduce what the result might be?
  • 19. Right Outer Join Right outer Join based on the EmpID field NOTE: Having understood the left outer join, it is easy to understand the right outer joins. If you find any difficulty, please return to left outer joins.
  • 20. Right Outer Join The SQL command for the right outer join resembles the left outer join Select * from Table1 right outer join Table2 on Table1.JoiningFieldName1 = Table2.JoiningFieldName2; Now let us consider the final outer join type: Full outer join
  • 21. Full Outer Join A Full outer join is used in situations where two tables are to be combined without loss of data. In Full outer join, all records from the first table and all records from the second table are considered. If there is a common joining field value found, the records are combined. Else, the records are treated as separate in the new joint table, with NULL values for the left out fields. Let us see an illustration: Consider the Gift table problem that we saw in slide.no: 15
  • 23. Full Outer Join The SQL command for the full outer join resembles the right outer join Select * from Table1 full outer join Table2 on Table1.JoiningFieldName1 = Table2.JoiningFieldName2; These are the basic join types. To add fun, let us consider an additional join that SQL Server provides: The Cross join
  • 24. Cross Join A Cross Join is used to produce a Cartesian product between two tables. In mathematical terms, two sets ‘A’ and ‘B’ under cross product means that every variable in set A will be combined with every variable in set B. The same can be applied to tables here. The SQL command for the cross join is as follows: Select * from Table1 cross join Table2; Illustration: See the next slide NOTE: Do remember to use the go command to run any SQL Statement. You can type a list of commands and run them sequentially with a single go statement also.
  • 25. Cross Join Illustration: Consider an online dating database. All possible matches between the boys and girls following tables are needed. Here, a cross join would prove useful to find all possible combinations. Boys Girls Boys X Girls X
  • 26.
  • 27. Inner Join
  • 28. Outer Join
  • 29. Left Outer Join
  • 30. Right Outer Join
  • 31. Full Outer Join
  • 32.