The Wayback Machine - https://web.archive.org/web/20240822161840/https://www.geeksforgeeks.org/sql-select-from-multiple-tables-with-ms-sql-server/
Open In App

SQL – SELECT from Multiple Tables with MS SQL Server

Last Updated : 14 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n rows then the resulting table after selecting two tables i.e cross join of two tables contains m*n rows.

Let us see how to select multiple tables using the MSSQL server:
 

Creating a database :

Creating a database GeeksForGeeks by using the following SQL query as follows.

CREATE DATABASE GeeksForGeeks;

Using the database :

Using the database student using the following SQL query as follows.

USE GeeksForGeeks;

Creating Tables:

Creating three tables student, branch_details, credit_details  with SQL query as follows:

CREATE TABLE student
(  
stu_id varchar(10),
stu_name varchar(20),
branch varchar(20)
);

CREATE TABLE branch_details
(  
branch_name varchar(10),
subjects INT
);

CREATE TABLE credit_details
(  
branch varchar(20), 
max_credits INT,
min_credits_required INT
);

Verifying the database :

To view the description of the three tables in the database GeeksForGeeks using the following SQL query as follows.

EXEC sp_columns student;
EXEC sp_columns branch_details;
EXEC sp_columns credit_details;

Inserting data into the three tables:

Inserting rows into tables using the following SQL query as follows:

INSERT INTO student VALUES
('1901401','DEVA','C.S'),
('1901402','HARSH','C.S'),
('1901403','DAVID','E.C'),
('1901404','GAURAV','E.C');

INSERT INTO branch_details VALUES
('C.S',8),
('E.C',7),
('M.E',7),
('I.C.E',9),
('E.E.E',8);

INSERT INTO credit_details VALUES
('C.S',24, 12),
('E.C',21, 11),
('M.E',21, 11),
('I.C.E',27,14),
('E.E.E',24,12);

Verifying the inserted data :

Viewing the three tables after inserting rows by using the following SQL query as follows.

SELECT * FROM student;
SELECT * FROM branch_details;
SELECT * FROM credit_details;

Using SELECT statement for n tables:

SYNTAX:
SELECT columns
FROM table_1, table_2,...table_n
WHERE condition; 

Using SELECT statements for 2 tables student, branch_details:

SELECT * FROM student, branch_details;

This table contains 4*5 = 20 rows.

Using SELECT statements for 3 tables student, branch_details, credit_details:

SELECT * FROM student, branch_details, credit_details;

The resulting table contains 5*4*5 = 100 rows.

We can obtain other types of join by selecting multiple tables and mentioning appropriate condition in the WHERE clause but instead of using the SELECT with multiple tables and adding conditions using the keywords of joins is more optimal.

Example:

Query to display students who have enrolled in a course and their particulars.

SELECT student.stu_id, student.stu_name,
student.branch, subjects, max_credits
FROM student, branch_details, credit_details
WHERE student.branch = branch_details.branch_name AND 
branch_details.branch_name = credit_details.branch;

Note: When there are columns with the same name in different tables it is good to dot operator to point to the particular tables data.



Similar Reads

Insert Multiple Values Into Multiple Tables in SQL Server
To insert multiple values into multiple tables in SQL Server, use the OUTPUT clause. The SQL OUTPUT clause allows to insert multiple values into multiple tables in a single query. Output clause clause in SQL is used to capture data affected by Data Manipulation Language (DML) statements like INSERT, UPDATE, or DELETE. SyntaxSyntax to insert multipl
2 min read
Select into and temporary tables in MS SQL Server
1. Select into : Suppose a table has some particular rows that has to be transferred to another table of the same database. It can be done using select into statement as follows - select list into destination from source (where condition) Example : There are two tables named student and marks. The marks of the students has to be transferred from ma
2 min read
SELECT data from Multiple Tables in SQL
The statement is used to retrieve the fields from multiple tables and with the help of JOIN operations we easily fetch the records from multiple tables, Generally JOINS are used when there are common records between two tables. In this article, we will look into various types of JOIN that are used in SQL. SQL JoinsSQL joins combine two or more tabl
3 min read
SQL Server | Convert tables in T-SQL into XML
In this, we will focus on how tables will be converted in T-SQL into XML in SQL server. And you will be able to understand how you can convert it with the help of command. Let's discuss it one by one. Overview :XML (Extensible Markup Language) is a markup language similar to HTML which was designed to share information between different platforms.
2 min read
SQL Query to select Data from Tables Using Join and Where
The aim of this article is to make a simple program to Join two tables using Join and Where clause using MySQL. Below is the method to do the same using MySQL. The prerequisites of this article are MySQL and Apache Server on your computer are installed. What is a Query in SQL? A SQL query is a request passed for data/information from a table in a d
3 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
Copy tables between databases in SQL Server using Import-and-Export Wizard
Introduction to Import-and-Export Wizard : The wizard allows easy steps through a process, and to execute the data copy process with writing very little or no code. However, for importing and exporting data from one source into another, the below steps could be followed - Open the Object Explorer, select the database, right-click on the database na
2 min read
Magic Tables in SQL Server
Magic tables are the temporary logical tables that are created by the SQL server whenever there are insertion or deletion or update( D.M.L) operations. The recently performed operation on the rows gets stored in magic tables automatically. These are not physical table but they are just temporary internal tables. These magic tables can't be retrieve
3 min read
How to Update Two Tables in One Statement in SQL Server?
To update two tables in one statement in SQL Server, use the BEGIN TRANSACTION clause and the COMMIT clause. The individual UPDATE clauses are written in between the former ones to execute both updates simultaneously. Here, we will learn how to update two tables in a single statement in SQL Server. SyntaxUpdating two tables in one statement in SQL
3 min read
Copy Tables Between Databases In SQL Server
Copying tables between databases in SQL Server is a common task that is useful in data migration, backup and restore, or even testing and development SQL Server offers various features to copy tables between databases in SQL Server. The simplest and most effective way of copying tables between databases in SQL Server is by generating Scripts using
2 min read
Find all Tables that Contain a Specific Column Name in SQL Server
When managing a database in SQL Server, it's often necessary to find out which tables include a specific column name. This task is essential for database administrators and developers, especially when updating database structures, migrating data safely, or getting a better understanding of how information is organized. There are two ways to find al
2 min read
How to Left Join Multiple Tables in SQL
Left Join is one of the Keywords used while writing queries in SQL. In SQL we normally use Join for the purpose of forming a new table by taking out common data like rows or records or tuples from both the tables which are having matching records in general. Here when it comes to Left Join in SQL it only returns all the records or tuples or rows fr
3 min read
Querying Multiple Tables in SQL
Here, we are going to see how to query multiple tables in SQL. For example, here, we will first create a database named “geeks” then we will create 2 tables “department” and "employee" in that database. After, that we will execute our query on the tables. Creating a Database : Use the below SQL statement to create a database called geeks: CREATE DA
2 min read
How to Retrieve Data from Multiple Tables in SQL?
In SQL, Retrieving data from multiple tables is a common requirement in database operations. In this article, we will explore multiple approaches to retrieving data from multiple tables in SQL. We will provide an introduction to the topic, explain two distinct approaches with their respective syntax, present detailed examples for each approach with
4 min read
Select statement in MS SQL Server
In this article, the most basic statement used in SQL is being discussed. Basic statement: select There are large amounts of data available everywhere. The data is stored in a sequential order in form of a table. Each table consists of a row which represents a unique record and column represents a field. Schemas are used to arrange the tables in a
2 min read
Select top in MS SQL Server
Prerequisite - Select in MS SQL Server Suppose that a user wants to extract the top students from the whole institution but has to use some complex queries to extract the data. To avoid complexity, the user can use 'Select Top'. 'Select Top' extracts the limited number of rows. This results in accurate data along with less time consumption. Syntax
2 min read
Insert Into Select statement in MS SQL Server
Prerequisites - Insert statement in MS SQL Server, Select statement in MS SQL Server Consider a university database. There are two tables namely Student and Marks. In case, the marks of a few students has to be transferred from the marks table to the marks table, there are many ways to do so. One can use subqueries (query nested in another query) b
2 min read
How to Select Group of Rows that Match All Items on a List in SQL Server?
In this article, we will see, how to select a group of rows that match all the items on a list in SQL Server. We can perform the above function by two methods. Those are: By using IN operatorBY performing JOIN using STRING_SPLIT methodIN operator: It allows you to specify a list of values in a WHERE clause. STRING_SPLIT(): this function can be used
2 min read
How to Select Data Between Two Dates and Times in SQL Server?
In SQL, some transactions need to be extracted based on their completion times and dates. Here, the DATETIME2 data type in SQL to perform such operations. For this article, we will be using the Microsoft SQL Server as our database. Note: Here, we will use the two dates and times given in the query and separate them using the BETWEEN keyword. This i
2 min read
How to SELECT DISTINCT on Multiple Columns in SQL?
In the world of databases, data duplication can lead to confusion and inefficiency. SQL provides a powerful tool, SELECT DISTINCT, to retrieve unique values from columns. However, when dealing with multiple columns, the approach becomes more detailed. In this article, We will explore How to SELECT DISTINCT on multiple columns in SQL by understandin
4 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
Join Multiple Tables Using Inner Join
To retrieve data from the single table we use SELECT and PROJECTION operations but to retrieve data from multiple tables we use JOINS in SQL. There are different types of JOINS in SQL. In this article, only operations on inner joins in MSSQL are discussed. Inner Join is the method of retrieval of data from multiple tables based on a required condit
3 min read
Drop Multiple Tables in MySQL
DROP statement in a relational database management system (RDBMS) is used to delete a database object such as a table, index, or view. It can be used to delete the complete database also. The general syntax of the DROP command is as follows: Syntax: DROP object object_name; Example: DROP DATABASE db; In everyday life scenarios and live projects, we
3 min read
How to Alter Multiple Columns at Once in SQL Server?
In SQL, sometimes we need to write a single query to update the values of all columns in a table. We will use the UPDATE keyword to achieve this. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database and Select keyword. Step 1: Create a Database. For t
3 min read
How to Update Multiple Records Using One Query in SQL Server?
To update multiple records in the SQL server, use the UPDATE Statement. Using the SQL UPDATE statement with the WHERE clause users can update multiple records in the table based on some condition. There can be two cases in this situation: Table of Content Update Multiple Records Based on One Condition in SQL ServerUpdate Multiple Records Based on M
4 min read
Joining three or more tables in SQL
There may occur some situations sometimes where data needs to be fetched from three or more tables. This article deals with two approaches to achieve it. Example: Creating three tables: student marks details Note: Click on image if not clear to view in bigger size. Table 1: student create table student(s_id int primary key, s_name varchar(20)); ins
3 min read
Compare and Find Differences Between Two Tables in SQL
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. Here we are going to see how to Compare and Find Differences Between Two Tables in SQL Here, we will first create a database named “geeks” then we will create two tables “departme
3 min read
Joining 4 Tables in SQL
The purpose of this article is to make a simple program to Join two tables using Join and Where clause in SQL. Below is the implementation for the same using MySQL. The prerequisites of this topic are MySQL and the installment of Apache Server on your computer. Introduction :In SQL, a query is a request with some instruction such that inserting, re
3 min read
How to compare columns in two different tables in SQL
Here we are going to see how we can compare the columns of two different tables in SQL. We will be taking a few examples to see how we can do this in different ways. Overview :In this, we will understand overview of SQL query for required operation to perform How to compare columns in two different tables in SQL. We will understand each concept wit
4 min read
SQL Query to Combine Two Tables Without a Common Column
In most of the queries in the learning process, we usually use to join those tables which have some common columns or relationships between them. But when it comes to real-life problems, then such easiest conditions are rarely found. Complex tasks like joining two tables without a common column is majorly found. Let's first have a look at our table
3 min read
Article Tags :
three90RightbarBannerImg