65.9K
CodeProject is changing. Read more.
Home

Creating SQL Joins in Simple Steps

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

Sep 18, 2012

CPOL

2 min read

viewsIcon

20451

Simple steps to create SQL joins by using SQL Server 2008 Management Studio

Introduction

This tip explains how to create SQL joins in a very simple way. With this, developers need not put much effort to frame SQL Joins. This is very simple and easy to do.

Note: Please feel free to send comments... thanks in advance.

Background

The idea behind posting this tip is to provide users with a simple way of creating join queries. Most people might already know it. But still it might help newbies.

Using the Code

For this explanation, I have created two tables as follows:

Table 1. T_EMPLOYEE (T stands for table, this is the method that I use to create tables)

Below is my Employee table design:

Table 2. T_DEPARTMENTS

Below is my Department table design:

And please make sure that you have some rows(data) in both the tables.

Note: Relationship between fields has already been created between EMP_DEPARTMENT and DEPT_ID.

Now moving into the actual stuff about creating Joins, please follow the steps given below:

  1. Open SQL Server 2008 Management Studio
  2. Expand your database, locate "Views" and right click on that
  3. Click on "New View"
  4. The following dialog will be displayed:

  5. Select both the tables and click on Add button... and Close the window.. you will find the following screen with the relationship between both the tables which we made.

    Tables with relations

  6. Observe that it has pre-populated basic INNER JOIN query based on Primary and Foreign Key relation.
  7. Now for our convenience and requirement, we don't require all the fields. So Select the required fields from both the tables.
  8. I have selected the following fields. And for ease of understanding, I have given alias names too.

  9. That's it. Now you have your SQL query which joins two tables. Execute it, then you will find the following table as an output table.

  10. So, you can use this for:
    • Joining more than two tables
    • Union of tables
    • and lot more

Points of Interest

This is so simple and pretty straight forward.