SlideShare a Scribd company logo
6SQL SERVER: JOININGDATABASETABLES
SQL JOIN: PrerequisitesBefore 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 recordEg: Consider a dream databaseHere, 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: PrerequisitesForeign Key:A Foreign key is a field/attribute in one table which is used as a primary key in another tableEg: Consider a dream databaseEvery 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 TableNotice that foreign key entries can repeat( where-as primary key entries can’t!)Foreign KeyPrimary KeyLuck TableRefer-ences
SQL JOIN: Prerequisites3.SELECT StatementThe 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 tableNameEg: select * from DreamTable lists the entire tableExample: 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 JOINAn SQL JOIN command combines records from two or more tables in a database.Types of Joins:
Inner JoinAn 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 TaleMoogle Department TableNOTE: 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 JoinIllustration: Now, on performing the Inner joint on the above given table:Moogle Employee TaleMoogle Department TableLet us call the field that is used for joining the tables as joining fieldJoin based on the EmpID fieldNew Table (Inner Joint)
Inner JoinThe 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 table2on 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.EmpIDBottom-line: Inner Joints are highly strict. They only accept records that have perfect matching in the other table.
Inner JoinThis is an illustration of an Inner Joint:
Outer JoinThe 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 JoinA 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 TaleMoogle Department TableLeft outer Join based on the EmpID fieldCan you guess what the result might be? Go to the next slide to find out!
Left Outer JoinLeft outer Join based on the EmpID field
Understanding Left Outer JoinThe 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:StartGet 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 valuesend
Understanding Left Outer JoinConfused 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 TableTable1: Gifts table
Understanding Left Outer Join
Left Outer JoinHaving 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 JoinA 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 TaleMoogle Department TableRight outer Join based on the EmpID fieldNow, Can you deduce what the result might be?
Right Outer JoinRight outer Join based on the EmpID fieldNOTE: 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 JoinThe SQL command for the right outer join resembles the left outer joinSelect * 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 JoinA 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 JoinThe SQL command for the full outer join resembles the right outer joinSelect * 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 JoinA 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 slideNOTE: 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 JoinIllustration: 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.BoysGirlsBoys X GirlsX
Summary6. Joining Databases  SQL Joins
  Inner Join

More Related Content

PPTX
Depth first search [dfs]
PDF
Graph Data Structure
PPT
Data Structure and Algorithms Binary Tree
PPT
Testing for share
PDF
Advance database system(part 8)
ODT
Sql joins
PPTX
PDF
SQL JOINS
Depth first search [dfs]
Graph Data Structure
Data Structure and Algorithms Binary Tree
Testing for share
Advance database system(part 8)
Sql joins
SQL JOINS

Similar to MS SQL SERVER: Joining Databases (20)

PPTX
joins in database
PPTX
SQL JOIN
PPTX
Day-06-Joining presentation of SQL lecture form uni .pptx
DOC
SQL Joins
PPTX
Ch1_s2_QueryMultipleTablesByUsingJoins.pptx
PPTX
Joins (A JOIN clause is used to combine rows from two or more tables, based o...
PPTX
joins dbms.pptx
PPTX
Practical Joins Algorithms in database system
PPTX
sql joinsubdjbrjdbjrjnfkjcnkrnfknrkfkrfkrfkrk
PPTX
sqlyyybdbyehduheufhuehfuheuwehfiewifhewihfiehfiwf
PPTX
join_SQL000000000000000000000000000000000.pptx
PPTX
Querying_with_T-SQL_-_03 (1).pptx
PPTX
Querying_with_T-SQL_-_03.pptx
PPT
Ms sql server ii
PDF
SQL JOINS
PPTX
SQL JOIN.pptx
PPTX
askndmf,dskmlf,bvdmk,v nmdsvjkmc,dvjkcmsdcvjnkmd
PDF
Tipos de Joins para consultas em banco de dados.pdf
PDF
SQL joins for Database Testing easy .pdf
PPTX
Joins.pptxjjbmmmnnnnnjjjxrhjfluflurulrdudlu
joins in database
SQL JOIN
Day-06-Joining presentation of SQL lecture form uni .pptx
SQL Joins
Ch1_s2_QueryMultipleTablesByUsingJoins.pptx
Joins (A JOIN clause is used to combine rows from two or more tables, based o...
joins dbms.pptx
Practical Joins Algorithms in database system
sql joinsubdjbrjdbjrjnfkjcnkrnfknrkfkrfkrfkrk
sqlyyybdbyehduheufhuehfuheuwehfiewifhewihfiehfiwf
join_SQL000000000000000000000000000000000.pptx
Querying_with_T-SQL_-_03 (1).pptx
Querying_with_T-SQL_-_03.pptx
Ms sql server ii
SQL JOINS
SQL JOIN.pptx
askndmf,dskmlf,bvdmk,v nmdsvjkmc,dvjkcmsdcvjnkmd
Tipos de Joins para consultas em banco de dados.pdf
SQL joins for Database Testing easy .pdf
Joins.pptxjjbmmmnnnnnjjjxrhjfluflurulrdudlu
Ad

More from sqlserver content (20)

PPTX
MS SQL SERVER: Using the data mining tools
PPTX
MS SQL SERVER: SSIS and data mining
PPTX
MS SQL SERVER: Programming sql server data mining
PPTX
MS SQL SERVER: Olap cubes and data mining
PPTX
MS SQL SERVER: Microsoft time series algorithm
PPTX
MS SQL SERVER: Microsoft sequence clustering and association rules
PPTX
MS SQL SERVER: Neural network and logistic regression
PPTX
MS SQL SERVER: Microsoft naive bayes algorithm
PPTX
MS SQL SERVER: Decision trees algorithm
PPTX
MS SQL Server: Data mining concepts and dmx
PPTX
MS Sql Server: Reporting models
PPTX
MS Sql Server: Reporting manipulating data
PPTX
MS Sql Server: Reporting introduction
PPTX
MS Sql Server: Reporting basics
PPTX
MS Sql Server: Datamining Introduction
PPTX
MS Sql Server: Business Intelligence
PPTX
MS SQLSERVER:Feeding Data Into Database
PPTX
MS SQLSERVER:Doing Calculations With Functions
PPTX
MS SQLSERVER:Deleting A Database
PPTX
MS SQLSERVER:Customizing Your D Base Design
MS SQL SERVER: Using the data mining tools
MS SQL SERVER: SSIS and data mining
MS SQL SERVER: Programming sql server data mining
MS SQL SERVER: Olap cubes and data mining
MS SQL SERVER: Microsoft time series algorithm
MS SQL SERVER: Microsoft sequence clustering and association rules
MS SQL SERVER: Neural network and logistic regression
MS SQL SERVER: Microsoft naive bayes algorithm
MS SQL SERVER: Decision trees algorithm
MS SQL Server: Data mining concepts and dmx
MS Sql Server: Reporting models
MS Sql Server: Reporting manipulating data
MS Sql Server: Reporting introduction
MS Sql Server: Reporting basics
MS Sql Server: Datamining Introduction
MS Sql Server: Business Intelligence
MS SQLSERVER:Feeding Data Into Database
MS SQLSERVER:Doing Calculations With Functions
MS SQLSERVER:Deleting A Database
MS SQLSERVER:Customizing Your D Base Design
Ad

Recently uploaded (20)

PPTX
Machine Learning_overview_presentation.pptx
PPTX
Tartificialntelligence_presentation.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation theory and applications.pdf
PPTX
1. Introduction to Computer Programming.pptx
PPTX
A Presentation on Artificial Intelligence
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Spectroscopy.pptx food analysis technology
PPT
Teaching material agriculture food technology
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Machine Learning_overview_presentation.pptx
Tartificialntelligence_presentation.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Approach and Philosophy of On baking technology
Encapsulation theory and applications.pdf
1. Introduction to Computer Programming.pptx
A Presentation on Artificial Intelligence
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Programs and apps: productivity, graphics, security and other tools
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
20250228 LYD VKU AI Blended-Learning.pptx
Encapsulation_ Review paper, used for researhc scholars
gpt5_lecture_notes_comprehensive_20250812015547.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Spectral efficient network and resource selection model in 5G networks
The Rise and Fall of 3GPP – Time for a Sabbatical?
Spectroscopy.pptx food analysis technology
Teaching material agriculture food technology
Accuracy of neural networks in brain wave diagnosis of schizophrenia

MS SQL SERVER: Joining Databases

  • 2. SQL JOIN: PrerequisitesBefore 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 recordEg: Consider a dream databaseHere, 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: PrerequisitesForeign Key:A Foreign key is a field/attribute in one table which is used as a primary key in another tableEg: Consider a dream databaseEvery 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 TableNotice that foreign key entries can repeat( where-as primary key entries can’t!)Foreign KeyPrimary KeyLuck TableRefer-ences
  • 4. SQL JOIN: Prerequisites3.SELECT StatementThe 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 tableNameEg: select * from DreamTable lists the entire tableExample: 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 JOINAn SQL JOIN command combines records from two or more tables in a database.Types of Joins:
  • 7. Inner JoinAn 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 TaleMoogle Department TableNOTE: 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 JoinIllustration: Now, on performing the Inner joint on the above given table:Moogle Employee TaleMoogle Department TableLet us call the field that is used for joining the tables as joining fieldJoin based on the EmpID fieldNew Table (Inner Joint)
  • 9. Inner JoinThe 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 table2on 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.EmpIDBottom-line: Inner Joints are highly strict. They only accept records that have perfect matching in the other table.
  • 10. Inner JoinThis is an illustration of an Inner Joint:
  • 11. Outer JoinThe 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 JoinA 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 TaleMoogle Department TableLeft outer Join based on the EmpID fieldCan you guess what the result might be? Go to the next slide to find out!
  • 13. Left Outer JoinLeft outer Join based on the EmpID field
  • 14. Understanding Left Outer JoinThe 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:StartGet 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 valuesend
  • 15. Understanding Left Outer JoinConfused 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 TableTable1: Gifts table
  • 17. Left Outer JoinHaving 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 JoinA 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 TaleMoogle Department TableRight outer Join based on the EmpID fieldNow, Can you deduce what the result might be?
  • 19. Right Outer JoinRight outer Join based on the EmpID fieldNOTE: 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 JoinThe SQL command for the right outer join resembles the left outer joinSelect * 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 JoinA 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 JoinThe SQL command for the full outer join resembles the right outer joinSelect * 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 JoinA 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 slideNOTE: 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 JoinIllustration: 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.BoysGirlsBoys X GirlsX
  • 27. Inner Join
  • 28. Outer Join
  • 29. Left Outer Join
  • 30. Right Outer Join
  • 31. Full Outer Join
  • 32. Cross JoinVisit more self help tutorialsPick a tutorial of your choice and browse through it at your own pace.The tutorials section is free, self-guiding and will not involve any additional support.Visit us at www.dataminingtools.net