Data Science Hub
  • Data Science Hub
  • STATISTICS
    • Introduction
    • Fundamentals
      • Data Types
      • Central Tendency, Asymmetry, and Variability
      • Sampling
      • Confidence Interval
      • Hypothesis Testing
    • Distributions
      • Exponential Distribution
    • A/B Testing
      • Sample Size Calculation
      • Multiple Testing
  • Database
    • Database Fundamentals
    • Database Management Systems
    • Data Warehouse vs Data Lake
  • SQL
    • SQL Basics
      • Creating and Modifying Tables/Views
      • Data Types
      • Joins
    • SQL Rules
    • SQL Aggregate Functions
    • SQL Window Functions
    • SQL Data Manipulation
      • String Operations
      • Date/Time Operations
    • SQL Descriptive Stats
    • SQL Tips
    • SQL Performance Tuning
    • SQL Customization
    • SQL Practice
      • Designing Databases
        • Spotify Database Design
      • Most Commonly Asked
      • Mixed Queries
      • Popular Websites For SQL Practice
        • SQLZoo
          • World - BBC Tables
            • SUM and COUNT Tutorial
            • SELECT within SELECT Tutorial
            • SELECT from WORLD Tutorial
            • Select Quiz
            • BBC QUIZ
            • Nested SELECT Quiz
            • SUM and COUNT Quiz
          • Nobel Table
            • SELECT from Nobel Tutorial
            • Nobel Quiz
          • Soccer / Football Tables
            • JOIN Tutorial
            • JOIN Quiz
          • Movie / Actor / Casting Tables
            • More JOIN Operations Tutorial
            • JOIN Quiz 2
          • Teacher - Dept Tables
            • Using Null Quiz
          • Edinburgh Buses Table
            • Self join Quiz
        • HackerRank
          • SQL (Basic)
            • Select All
            • Select By ID
            • Japanese Cities' Attributes
            • Revising the Select Query I
            • Revising the Select Query II
            • Revising Aggregations - The Count Function
            • Revising Aggregations - The Sum Function
            • Revising Aggregations - Averages
            • Average Population
            • Japan Population
            • Population Density Difference
            • Population Census
            • African Cities
            • Average Population of Each Continent
            • Weather Observation Station 1
            • Weather Observation Station 2
            • Weather Observation Station 3
            • Weather Observation Station 4
            • Weather Observation Station 6
            • Weather Observation Station 7
            • Weather Observation Station 8
            • Weather Observation Station 9
            • Weather Observation Station 10
            • Weather Observation Station 11
            • Weather Observation Station 12
            • Weather Observation Station 13
            • Weather Observation Station 14
            • Weather Observation Station 15
            • Weather Observation Station 16
            • Weather Observation Station 17
            • Weather Observation Station 18
            • Weather Observation Station 19
            • Higher Than 75 Marks
            • Employee Names
            • Employee Salaries
            • The Blunder
            • Top Earners
            • Type of Triangle
            • The PADS
          • SQL (Intermediate)
            • Weather Observation Station 5
            • Weather Observation Station 20
            • New Companies
            • The Report
            • Top Competitors
            • Ollivander's Inventory
            • Challenges
            • Contest Leaderboard
            • SQL Project Planning
            • Placements
            • Symmetric Pairs
            • Binary Tree Nodes
            • Interviews
            • Occupations
          • SQL (Advanced)
            • Draw The Triangle 1
            • Draw The Triangle 2
            • Print Prime Numbers
            • 15 Days of Learning SQL
          • TABLES
            • City - Country
            • Station
            • Hackers - Submissions
            • Students
            • Employee - Employees
            • Occupations
            • Triangles
        • StrataScratch
          • Netflix
            • Oscar Nominees Table
            • Nominee Filmography Table
            • Nominee Information Table
          • Audible
            • Easy - Audible
          • Spotify
            • Worldwide Daily Song Ranking Table
            • Billboard Top 100 Year End Table
            • Daily Rankings 2017 US
          • Google
            • Easy - Google
            • Medium - Google
            • Hard - Google
        • LeetCode
          • Easy
  • Python
    • Basics
      • Variables and DataTypes
        • Lists
        • Dictionaries
      • Control Flow
      • Functions
    • Object Oriented Programming
      • Restaurant Modeler
    • Pythonic Resources
    • Projects
  • Machine Learning
    • Fundamentals
      • Supervised Learning
        • Classification Algorithms
          • k-Nearest Neighbors
            • kNN Parameters & Attributes
          • Logistic Regression
        • Classification Report
      • UnSupervised Learning
        • Clustering
          • Evaluation
      • Preprocessing
        • Scalers: Standard vs MinMax
        • Feature Selection vs Dimensionality Reduction
        • Encoding
    • Frameworks
    • Machine Learning in Advertising
    • Natural Language Processing
      • Stopwords
      • Name Entity Recognition (NER)
      • Sentiment Analysis
        • Agoda Reviews - Part I - Scraping Reviews, Detecting Languages, and Preprocessing
        • Agoda Reviews - Part II - Sentiment Analysis and WordClouds
    • Recommendation Systems
      • Spotify Recommender System - Artists
  • Geospatial Analysis
    • Geospatial Analysis Basics
    • GSA at Work
      • Web Scraping and Mapping
  • GIT
    • GIT Essentials
    • Connecting to GitHub
  • FAQ
    • Statistics
  • Cloud Computing
    • Introduction to Cloud Computing
    • Google Cloud Platform
  • Docker
    • What is Docker?
Powered by GitBook
On this page
  • String Operations
  • Aggregations / Functions

Was this helpful?

  1. SQL
  2. SQL Practice

Mixed Queries

String Operations

Show the name of the countries where the capital is the country name + 'City' in the WOLRD table.

SELECT country FROM world
WHERE capital = CONCAT(country,' City')

Extract all the details with a winner whose name is EUGENE O'NEILL (single quote) from NOBEL.

SELECT yr, subject, winner
FROM nobel
WHERE winner = 'EUGENE O''NEILL'

Query the list of CITY names starting with vowels (i.e. a, e, i, o, or u) from STATION. Your result cannot contain duplicates.

SELECT DISTINCT city
FROM station
WHERE city LIKE 'A%' 
    OR city LIKE 'E%' 
    OR city LIKE 'I%' 
    OR city LIKE 'O%' 
    OR city LIKE 'U%';

-- OR

SELECT DISTINCT city
FROM station
WHERE city ~ '^[AEIOU]'; -- Regex like query

Query the list of CITY names from STATION that either do not start with vowels or do not end with vowels. Your result cannot contain duplicates.

SELECT DISTINCT city
FROM station
WHERE NOT (city LIKE 'A%' 
    OR city LIKE 'E%' 
    OR city LIKE 'I%' 
    OR city LIKE 'O%' 
    OR city LIKE 'U%')
AND NOT (city LIKE '%a' 
    OR city LIKE '%e' 
    OR city LIKE '%i' 
    OR city LIKE '%o' 
    OR city LIKE '%u');
    
-- OR

SELECT DISTINCT city
FROM station
WHERE NOT (city ~ '^[AEIOU]') AND NOT (city ~'[aeiou]$');

Query the name of any student in STUDENTS whose marks are higher than 75. Order your output by the last three characters of each name. If two or more students both have names ending in the same last three characters (i.e.: Bobby, Robby, etc.), secondary sort them by ascending ID.

SELECT name
FROM students
WHERE marks > 75
ORDER BY SUBSTRING(name,-3), ID ASC 

Display records of customers who are either from Berlin or Munchen Germany

SELECT * FROM customers
WHERE country='Germany' 
AND (City='Berlin' OR City='München');
-- OR
SELECT * FROM customers
WHERE country='Germany' 
AND (City IN ('Berlin' City='München'));

Aggregations / Functions

Return largest populations per continent from WORLD

SELECT continent, MAX(population) AS max_pop
FROM world
WHERE population != 0
GROUP BY 1
ORDER BY 1;

Return the TOP 3 populations per continent

SELECT *
FROM (
     SELECT 
          continent,
          name, 
          population,
          RANK() OVER (PARTITION BY continent ORDER BY population DESC) AS pop_rank 
     FROM world
     WHERE population <> 0) AS t1
WHERE pop_rank <= 3
ORDER BY continent, pop_rank;

Find all the users who were active for 3 consecutive days or more

SELECT DISTINCT user_id
FROM (
    SELECT t1.*,
        lag(date) OVER (PARTITION BY user_id ORDER BY date) as prev_active_date,
        lag(date, 2) OVER (PARTITION BY user_id ORDER BY date) as prev_Active_date2
    FROM (
        SELECT DISTINCT user_id, date
        FROM sf_events 
        ) t1
    ) t2
WHERE prev_active_date = date - interval '1' day 
AND prev_Active_date2 = date - interval '2' day;

-- OR

SELECT DISTINCT s1.user_id
FROM sf_events s1
JOIN sf_events s2
ON s1.user_id = s2.user_id AND s1.date = s2.date - interval '1' day
JOIN sf_events s3
ON s1.user_id = s3.user_id AND s1.date = s3.date - interval '2' day;

Find Pepsi's Top selling products per day per retailer. Keep in mind one retailer might have ordered the same quantity for different products on a given day

pepsi Table
-- Create Table
CREATE TABLE IF NOT EXISTS pepsi (
	date DATE,
	retailer VARCHAR(50),
	product VARCHAR(50),
	quantity SMALLINT
);

# Add Data to the Table
INSERT INTO pepsi VALUES ('2022-01-01','Walmart', 'Pepsi',10000);
INSERT INTO pepsi VALUES ('2022-01-01','Target', 'Gatorade',10000);
INSERT INTO pepsi VALUES ('2022-01-01','Costco', 'Pepsi',8000);
INSERT INTO pepsi VALUES ('2022-01-01','Walmart', 'PepsiMax',10000);
INSERT INTO pepsi VALUES ('2022-01-01','ACME', 'Pepsi',4500);
INSERT INTO pepsi VALUES ('2022-01-01','Walmart', 'Aquafina',12500);
INSERT INTO pepsi VALUES ('2022-01-01','Walmart', 'PepsiMax',2500);
INSERT INTO pepsi VALUES ('2022-01-01','Target', 'Naked',5000);
INSERT INTO pepsi VALUES ('2022-01-01','Walgreens', 'PepsiMax',7500);
INSERT INTO pepsi VALUES ('2022-01-01','Walmart', 'Aquafina',2500);
INSERT INTO pepsi VALUES ('2022-01-01','CVS', 'Pepsi',3500);
INSERT INTO pepsi VALUES ('2022-01-01','Walmart', 'PepsiMax',1000);
INSERT INTO pepsi VALUES ('2022-01-02','ACME', 'Pepsi',2000);
INSERT INTO pepsi VALUES ('2022-01-02','Walmart', 'Aquafina',12500);
INSERT INTO pepsi VALUES ('2022-01-02','Walmart', 'PepsiMax',2500);
INSERT INTO pepsi VALUES ('2022-01-02','Target', 'Naked',1000);
INSERT INTO pepsi VALUES ('2022-01-02','Walgreens', 'PepsiMax',7500);
INSERT INTO pepsi VALUES ('2022-01-02','Walmart', 'Aquafina',2500);
INSERT INTO pepsi VALUES ('2022-01-02','ACME', 'Tropicana',2000);
INSERT INTO pepsi VALUES ('2022-01-02','Walmart', 'Aquafina',12500);
INSERT INTO pepsi VALUES ('2022-01-02','CVS', 'PepsiMax',2500);
INSERT INTO pepsi VALUES ('2022-01-03','Costco', 'Pepsi',8000);
INSERT INTO pepsi VALUES ('2022-01-03','Walmart', 'PepsiMax',10000);
INSERT INTO pepsi VALUES ('2022-01-03','ACME', 'Tropicana',4500);
INSERT INTO pepsi VALUES ('2022-01-03','Walmart', 'Aquafina',12500);
INSERT INTO pepsi VALUES ('2022-01-03','Walmart', 'PepsiMax',2500);
INSERT INTO pepsi VALUES ('2022-01-03','Target', 'Naked',5000);
INSERT INTO pepsi VALUES ('2022-01-03','Walgreens', 'PepsiMax',7500);
INSERT INTO pepsi VALUES ('2022-01-03','Walmart', 'Aquafina',2500);
INSERT INTO pepsi VALUES ('2022-01-03','CVS', 'Pepsi',3500);
INSERT INTO pepsi VALUES ('2022-01-03','Costo', 'PepsiMax',1000);
SELECT
	tmp.*
FROM (
	SELECT *, 
		DENSE_RANK() OVER (PARTITION BY date,retailer ORDER BY quantity DESC) as qty_rank
	FROM pepsi
) AS tmp
WHERE qty_rank=1;

Last updated 1 year ago

Was this helpful?