SQL Server Subqueries Example with Result
A Subquery is a query written inside another query.
It is enclosed within parentheses ().
1. Create Sample Table
Insert Records
Example 1: Subquery with WHERE Clause
Find employees whose salary is greater than average salary.
Result
| EmpName | Salary |
|---|
| Amit | 50000 |
| Sneha | 60000 |
Example 2: Subquery with IN Operator
Find employees working in departments where salary is greater than 50000.
Result
| EmpName | Department |
|---|
| Amit | IT |
| Sneha | IT |
Example 3: Subquery with MAX()
Find employee having highest salary.
Result
Example 4: Correlated Subquery
Find employees earning more than average salary of their department.
Result
| EmpName | Department | Salary |
|---|
| Sneha | IT | 60000 |
| Rohit | HR | 35000 |
Types of Subqueries in SQL Server
-
Single Row Subquery
Returns one row.
-
Multiple Row Subquery
Returns multiple rows.
-
Correlated Subquery
Depends on outer query.
-
Nested Subquery
Subquery inside another subquery.
Comments
Post a Comment