CIT 111: Introduction to Databases

Working with Subqueries

The Subquery in a SELECT statement

Basic Subquery Example

SELECT name, population
FROM city
WHERE CountryCode IN
  (SELECT code
  FROM country
  WHERE region = 'Caribbean')
ORDER BY population 

9 LIMIT 5;

SQL Subquery example-1
SELECT name, population 
FROM city
WHERE CountryCode IN 
(SELECT code 
FROM country
WHERE region = 'Caribbean')

The Subquery in an UPDATE statement

UPDATE country 
SET GNPOld = 0.00
WHERE Code IN
(SELECT CountryCode FROM countrylanguage WHERE population = 0)

SQL Subquery example-2

UPDATE country 
SET GNPOld = 0.00 
WHERE Code IN 
(SELECT CountryCode FROM countrylanguage WHERE population = 0) 

Create a Duplicate Table from an Existing Table with a Select Statement

It is often helpful to create a duplicate table from an existing table for testing purposes

You can combine the CREATE TABLE command with a select statement to create a duplicate of a table structure as well as the data in the table.

CREATE TABLE city_bak AS SELECT * FROM city; 

SQL Subquery example-3

CREATE TABLE city_bak AS SELECT * FROM city; 

The Subquery in a DELETE statement

A subquery can be used in a DELETE statement.

Always back up your data and test your DELETE statement before running it on live data.

NOTE: Before you can run a DELETE or UPDATE statement without a WHERE clause, you must uncheck Safe Updates checkbox in MySQL Preference. Please see below.

Safe updates option
USE world;
DELETE FROM city_bak WHERE CountryCode IN
(SELECT code FROM country 
WHERE region = 'Central Africa'); 

Subquery with WHERE clause

USE world; 
DELETE FROM city_bak 
WHERE CountryCode IN 
(SELECT code FROM country
WHERE region = 'Central Africa'); 

Useful Links: