Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

Subqueries in sql Part 59

Автор: kudvenkat

Загружено: 2013-01-07

Просмотров: 385920

Описание:

In this video we will discuss about subqueries in sql server. Let us understand subqueris with an example. Please create the required tables and insert sample data using the script below.

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.
   / @aarvikitchen5572  

Create Table tblProducts
(
[Id] int identity primary key,
[Name] nvarchar(50),
[Description] nvarchar(250)
)

Create Table tblProductSales
(
Id int primary key identity,
ProductId int foreign key references tblProducts(Id),
UnitPrice int,
QuantitySold int
)

Insert into tblProducts values ('TV', '52 inch black color LCD TV')
Insert into tblProducts values ('Laptop', 'Very thin black color acer laptop')
Insert into tblProducts values ('Desktop', 'HP high performance desktop')

Insert into tblProductSales values(3, 450, 5)
Insert into tblProductSales values(2, 250, 7)
Insert into tblProductSales values(3, 450, 4)
Insert into tblProductSales values(3, 450, 9)

Write a query to retrieve products that are not at all sold?
This can be very easily achieved using subquery as shown below.

Select [Id], [Name], [Description]
from tblProducts
where Id not in (Select Distinct ProductId from tblProductSales)

Most of the times subqueries can be very easily replaced with joins. The above query is rewritten using joins and produces the same results.
Select tblProducts.[Id], [Name], [Description]
from tblProducts
left join tblProductSales
on tblProducts.Id = tblProductSales.ProductId
where tblProductSales.ProductId IS NULL

In this example, we have seen how to use a subquery in the where clause.

Let us now discuss about using a sub query in the SELECT clause. Write a query to retrieve the NAME and TOTALQUANTITY sold, using a subquery.
Select [Name],
(Select SUM(QuantitySold) from tblProductSales where ProductId = tblProducts.Id) as TotalQuantity
from tblProducts
order by Name

Query with an equivalent join that produces the same result.
Select [Name], SUM(QuantitySold) as TotalQuantity
from tblProducts
left join tblProductSales
on tblProducts.Id = tblProductSales.ProductId
group by [Name]
order by Name

From these examples, it should be very clear that, a subquery is simply a select statement, that returns a single value and can be nested inside a SELECT, UPDATE, INSERT, or DELETE statement.

It is also possible to nest a subquery inside another subquery.

According to MSDN, subqueries can be nested upto 32 levels.

Subqueries are always encolsed in paranthesis and are also called as inner queries, and the query containing the subquery is called as outer query.

The columns from a table that is present only inside a subquery, cannot be used in the SELECT list of the outer query.

Next Video:
What to choose for performance? Queries that involve a subquery or a join

Text version of the video
http://csharp-video-tutorials.blogspo...

Slides
http://csharp-video-tutorials.blogspo...

All SQL Server Text Articles
http://csharp-video-tutorials.blogspo...

All SQL Server Slides
http://csharp-video-tutorials.blogspo...

All Dot Net and SQL Server Tutorials in English
https://www.youtube.com/user/kudvenka...

All Dot Net and SQL Server Tutorials in Arabic
   / kudvenkatarabic  

Subqueries in sql   Part 59

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Correlated subquery in sql   Part 60

Correlated subquery in sql Part 60

Indexes in sql server   Part 35

Indexes in sql server Part 35

7 простых приемов, которые мгновенно улучшат ваши SQL-запросы

7 простых приемов, которые мгновенно улучшат ваши SQL-запросы

SQL Server tutorial for beginners

SQL Server tutorial for beginners

Stored procedures in sql server   Part 18

Stored procedures in sql server Part 18

Успокаивающая музыка для нервов 🌿 лечебная музыка для сердца и сосудов, релакс, музыка для души #289

Успокаивающая музыка для нервов 🌿 лечебная музыка для сердца и сосудов, релакс, музыка для души #289

Как бы я быстро выучил SQL (если бы мог начать сначала)

Как бы я быстро выучил SQL (если бы мог начать сначала)

Clustered and nonclustered indexes in sql server   Part 36

Clustered and nonclustered indexes in sql server Part 36

Музыка под утренний кофе — зимний джаз и тепло

Музыка под утренний кофе — зимний джаз и тепло

Проверьте свои навыки SQL с помощью этих реальных вопросов для собеседования!

Проверьте свои навыки SQL с помощью этих реальных вопросов для собеседования!

16 AI-инструментов, которые реально работают в 2026 (честный рейтинг)

16 AI-инструментов, которые реально работают в 2026 (честный рейтинг)

ЗАЧЕМ ТРАМПУ ГРЕНЛАНДИЯ? / Уроки истории @MINAEVLIVE

ЗАЧЕМ ТРАМПУ ГРЕНЛАНДИЯ? / Уроки истории @MINAEVLIVE

Обработка ошибок в SQL Server Часть 56

Обработка ошибок в SQL Server Часть 56

Выбрать в SQL Server

Выбрать в SQL Server

Subquery in SQL | Correlated Subquery + Complete SQL Subqueries Tutorial

Subquery in SQL | Correlated Subquery + Complete SQL Subqueries Tutorial

Part 1   How to find nth highest salary in sql

Part 1 How to find nth highest salary in sql

Если у тебя спросили «Как твои дела?» — НЕ ГОВОРИ! Ты теряешь свою силу | Еврейская мудрость

Если у тебя спросили «Как твои дела?» — НЕ ГОВОРИ! Ты теряешь свою силу | Еврейская мудрость

Но что такое нейронная сеть? | Глава 1. Глубокое обучение

Но что такое нейронная сеть? | Глава 1. Глубокое обучение

5 самых популярных вопросов и ответов для собеседования по SQL | Часто задаваемые вопросы на собе...

5 самых популярных вопросов и ответов для собеседования по SQL | Часто задаваемые вопросы на собе...

НЕ ЛОЖИТЕСЬ ПОД НОЖ, пока не посмотрите это (особенно после 55)

НЕ ЛОЖИТЕСЬ ПОД НОЖ, пока не посмотрите это (особенно после 55)

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: infodtube@gmail.com