Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql sub-queries

Tags:

sql

subquery

Can anyone help me with the following:

Some countries have populations more than three times that of any of their neighbours (in the same region). Give the countries and regions.

my try:

select x.name, x.region
from bbc x
where x.population >all
(select population*3
from bbc y
where y.region = x.region)

syntax is correct but no records are returned (should return 3 rows)

Find each country that belongs to a region where all populations are less than 25000000. Show name, region and population.

my try:

select name, region, population
from bbc
where region not in 
(select distinct region from bbc 
where population >= 25000000)

I used "not in". Is there a way to use "in" ?

like image 675
Elad Benda Avatar asked Jun 17 '11 12:06

Elad Benda


People also ask

What are sub queries in SQL?

A subquery is a query that is nested inside a SELECT , INSERT , UPDATE , or DELETE statement, or inside another subquery.

What are sub queries for?

A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved. Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.

What is sub query and its types?

They help us target specific rows to perform various operations in SQL. They are used to SELECT, UPDATE, INSERT and DELETE records in SQL. There are different types of SQL subquery, like Single-row subquery, multiple row subquery, multiple column subquery, correlated subquery, and nested subquery.

How many types of sub queries are there in SQL?

There are three broad types of a subquery in SQL. This chapter from OCA Oracle Database 11g: SQL Fundamentals I Exam Guide explains differences between a single-row subquery, multiple-row subquery and correlated subquery .


1 Answers

SELECT name, region 
FROM bbc x 
WHERE population/3 >= ALL
    (SELECT population
     FROM bbc y
     WHERE y.region=x.region
     AND x.name != y.name)
like image 52
Alejandro Mérida Avatar answered Oct 26 '22 14:10

Alejandro Mérida