Basic Logics · Real Scenario Logic's

Joining Non-Related Tables

Introduction

In this Article, We are going to see how to join or relate or make connection between Non-related Tables In SQL Server.

Demo Table – SQL Script

IF OBJECT_ID('Tempdb..#T1') IS NOT NULL  DROP TABLE #T1;

CREATE TABLE #T1 (T1_Name VARCHAR(75));
 
INSERT INTO #T1 (T1_Name) VALUES ('Animal'),('Bat'),('Cat'),('Duet');

SELECT * FROM #T1;
IF OBJECT_ID('Tempdb..#T2') IS NOT NULL  DROP TABLE #T2;

CREATE TABLE #T2 (T2_Class VARCHAR(10));
 
INSERT INTO #T2 (T2_Class) VALUES ('Z'),('T'),('H'); 

SELECT * FROM #T2;

Demo Table – Table with Data

Table #T1
Table #T2

Joining Non-Related Tables

To Join Non-Related Tables , we are going to introduce one common joining column of Serial Numbers like below. To check how to Implement Serial Numbers Without Ordering Any of the Columns, Please check here.

SQL Script

SELECT T1.T1_Name,ISNULL(T2.T2_Class,'') AS T2_Class FROM 
( SELECT T1_Name,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS S_NO FROM #T1) T1
LEFT JOIN
( SELECT T2_Class,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS S_NO FROM #T2) T2
ON t1.S_NO=T2.S_NO;

Image Pic

Final Result

Conclusion

In this Article, we saw how to make Join between two Non-Related Tables in SQL Server. These Queries are unit tested with both On-Premises and Azure Sql db.

Thanks for reading!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s