Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
Google SQL Interview Questions
Next article icon

Google SQL Interview Questions

Last Updated : 19 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Google is known for its challenging technical interviews and SQL is a key component of these interviews, especially for roles related to data analysis, database engineering, and backend development.

Google SQL interview questions typically focus on candidates' proficiency in writing complex SQL queries, optimizing database operations, and demonstrating a deep understanding of relational database concepts.

In this article, we'll cover some common SQL interview questions you might encounter in a Google interview, detailed explanations, and sample queries.

Google-SQL-Interview-Questions-copy

Top 15 Google SQL Interview Questions

1. Find the Employees with More Than One Manager

Let's Retrieve the employee_id and employee_name of employees who have more than one manager from the employee_managers table.

Table: employee_managers

employee_idemployee_namemanager_idmanager_name
1Alice101Bob
1Alice102Charlie
2David101Bob
3Eve103Frank
4Grace104Henry
4Grace105Ivy
5Jack106Ken

Query:

SELECT employee_id, employee_name
FROM employee_managers
GROUP BY employee_id, employee_name
HAVING COUNT(DISTINCT manager_id) > 1;

Output:

Qs01

Explanation: This query groups the table by employee_id and employee_name, then filters the groups to include only those where the count of distinct manager_id is greater than one, indicating employees with more than one manager.

2. Write a SQL Query to Find Employees Who Have Worked in All Departments

Given a `works_in` table Find employees who have worked in all departments.

Table: works_in

employee_iddepartment_id
11
12
13
21
22
31
33
42
43
44
51
52
53
54

Query:

SELECT employee_id
FROM works_in
GROUP BY employee_id
HAVING COUNT(DISTINCT department_id)
=
(SELECT COUNT(*) FROM (SELECT DISTINCT department_id FROM works_in) AS departments);

Output:

Department-output

Explanation:This query groups employees by employee_id, counts the distinct department_id values for each employee, and filters to include only those employees whose count matches the total number of distinct departments in the company

3. What is Database Denormalization?

  1. Performance Optimization: Denormalization is used to improve the performance of read operations by reducing the number of joins needed to retrieve data.
  2. Redundant Data: It involves adding redundant copies of data or grouping data together to simplify queries and reduce the need for joins.
  3. Read-Heavy Workloads: Denormalization is most beneficial for databases with read-heavy workloads where the performance gain from simplified queries the cost of increased storage and potential data inconsistency.
  4. Data Maintenance: It can increase the complexity of data maintenance and the risk of inconsistencies, as redundant data needs to be kept in sync with the original data.
  5. Careful Consideration: Denormalization should be carefully considered and implemented based on specific performance needs, as over-denormalization can lead to excessive redundancy and complexity.
  6. Balancing Act: It is a balancing act between improving read performance and maintaining data integrity and consistency.

4. SQL Query to Rank Employees from Different Departments

Given a `employees` table and we have to write a query to Rank employees within each department based on their salaries and rank departments based on their IDs.

Table: employees

employee_iddepartment_idsalary
1160000
2165000
3270000
4272000
5380000
6385000

Query:

WITH RankedEmployees AS (
SELECT
employee_id,
department_id,
salary,
DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS dept_salary_rank,
DENSE_RANK() OVER (ORDER BY department_id) AS dept_name_rank
FROM employees
)
SELECT
employee_id,
department_id,
salary,
dept_salary_rank,
dept_name_rank
FROM RankedEmployees
ORDER BY dept_name_rank, dept_salary_rank;

Output:

Qs04

Explanation:This query uses window functions to assign ranks to employees within each department based on their salaries (dept_salary_rank) and to departments based on their IDs (dept_name_rank). The results are ordered initially by the rank of department names and then by the rank of department salaries.

5. SQL Query to Find the Median Salary in the Company

Given a employee table and we have to Find the median salary in the company. The median should be determined by finding the middle values of the ordered list of search counts

Table: employee

idnamecompanysalary
1AliceGoogle90000
2BobGoogle95000
3CharlieGoogle100000
4DavidGoogle105000
5EveGoogle110000
6FrankGoogle115000

Query:

WITH RankedSalaries AS (
SELECT salary, ROW_NUMBER() OVER (ORDER BY salary) AS row_num,
COUNT(*) OVER () AS total_rows
FROM employee
)
SELECT AVG(salary) AS median_salary
FROM RankedSalaries
WHERE row_num IN ((total_rows + 1) / 2, (total_rows + 2) / 2);

Output:

Qs05

Explanation:This query calculates the median salary by ranking the salaries in ascending order, determining the total number of rows, and then averaging the salaries corresponding to the middle row or rows if the total count is even.

6. Understanding the EXCEPT Operator in SQL Server and the MINUS Operator in Oracle

The EXCEPT operator in SQL Server and MINUS in Oracle is used to return all distinct rows from the first query that are not also returned by the second query. It essentially performs a set difference operation, removing the results of one query from another.

FeatureEXCEPT (SQL Server)MINUS (Oracle)
SyntaxSELECT ... FROM table1 EXCEPT SELECT ... FROM table2;SELECT ... FROM table1 MINUS SELECT ... FROM table2;
ReturnsRows from the first query that are not in the secondRows from the first query that are not in the second
ColumnsNumber and order of columns must match in both queriesNumber and order of columns must match in both queries
Data TypesData types must be compatibleData types must be compatible

7. SQL Query to Analyzing User Clicks

Given a table called user_clicks write a query to Find users who have clicked on more than one page.

Table: user_clicks

user_idtimestamppage_idaction_type
12024-06-18 08:30:00101"click"
22024-06-18 08:31:00102"click"
12024-06-18 08:32:00103"click"
32024-06-18 08:33:00101"click"
12024-06-18 08:34:00101"click"

Query:

SELECT user_id
FROM user_clicks
GROUP BY user_id
HAVING COUNT(DISTINCT page_id) > 1;

Output:

Qs02

Explanation: This query selects user_id from user_clicks, groups the results by user_id, and filters the groups to include only those with more than one distinct page_id, indicating users who have clicked on multiple pages.

8. How to Structure the Tables to Efficiently Store and Query the Survey Responses?

To efficiently store and query survey responses in SQL, you can structure the tables as follows:

1. Survey Table: Contains information about each survey, such as the survey ID, title, description, and any other relevant metadata.

CREATE TABLE Survey (
survey_id INT PRIMARY KEY,
title VARCHAR(255),
description TEXT
);

2. Question Table: Contains information about each question in the survey, including the question ID, text, type (e.g., multiple choice, text), and the survey it belongs to.

CREATE TABLE Question (
question_id INT PRIMARY KEY,
survey_id INT,
text TEXT,
type VARCHAR(50),
FOREIGN KEY (survey_id) REFERENCES Survey(survey_id)
);

3.Response Table: Stores the responses to each question in the survey, with each response linked to a specific respondent and question.

CREATE TABLE Response (
response_id INT PRIMARY KEY,
question_id INT,
respondent_id INT,
response_text TEXT,
FOREIGN KEY (question_id) REFERENCES Question(question_id),
FOREIGN KEY (respondent_id) REFERENCES Respondent(respondent_id)
);

4.Respondent Table: Contains information about each respondent, such as their ID, demographics, and any other relevant information.

CREATE TABLE Respondent (
respondent_id INT PRIMARY KEY,
age INT,
gender VARCHAR(50),
location VARCHAR(255),
-- Other demographic information
);

This structure allows you to efficiently store and query survey responses. You can easily retrieve responses for a specific survey, question, or respondent, and perform analysis or reporting as needed.

9. Write a Query to Find the Number of Pages That are Currently Active and have the Latest Event

Given a table pages with columns page_id, status, and event_date, write a SQL query to count the number of active pages that have the latest event date among all events for each page. An active page is defined as a page with status = 'active'. Consider each row in the pages table as a single event for a page.

Table: pages

page_idpage_namestatusevent_date
1Homeactive2022-06-01
2About Usactive2022-05-30
3Contact Usactive2022-06-02
4Productsactive2022-05-29
5Servicesactive2022-06-03

Query:

SELECT COUNT(*) AS active_pages_with_latest_event
FROM pages p1
WHERE status = 'active'
AND NOT EXISTS (
SELECT 1
FROM pages p2
WHERE p2.page_id = p1.page_id
AND p2.event_date > p1.event_date
);

Output:

Qs9

Explanation:This query counts the number of active pages (`status = 'active'`) that have the latest event date (`event_date`) among all events for each page. It uses a correlated subquery with `NOT EXISTS` to check if there are no other events for the same page (`p2.page_id = p1.page_id`) with a later `event_date`. If there are no such events, the page is considered to have the latest event date.

10. SQL Query to Find Users with High Click Volume

Given a user_clicks table containing users data, the task is to Find users who have clicked more than 3 times.

Table: user_clicks

user_idtimestamppage_idaction_type
12024-06-18 08:30:00101"click"
22024-06-18 08:31:00102"click"
12024-06-18 08:32:00103"click"
32024-06-18 08:33:00101"click"
12024-06-18 08:34:00101"click"
12024-06-18 08:35:00102"click"
22024-06-18 08:36:00103"click"
32024-06-18 08:37:00104"click"
32024-06-18 08:38:00105"click"
32024-06-18 08:39:00106"click"
12024-06-18 08:40:00107"click"
22024-06-18 08:41:00108"click"
12024-06-18 08:42:00109"click"

Query:

SELECT user_id, COUNT(*) AS click_count
FROM user_clicks
GROUP BY user_id
HAVING click_count > 3;

Output:

QS010

Explanation: This query calculates the click count for each user (user_id) in the user_clicks table, grouping the results by user_id. The HAVING clause filters the groups to include only those with a click count (click_count) greater than 3.

11. Determine Overlapping Subscription Date Ranges for Users in a Product Subscriptions Table

Write a query to check if there is any overlap in subscription date ranges among users in the `ProductSubscriptions` table. Return a list of users along with a boolean value indicating if there is an overlap.

Table: ProductSubscriptions

UserIdHasOverlappingSubscription
1True
2True
3True
4True
5True

Query:

SELECT ps1.UserId,
CASE
WHEN EXISTS (
SELECT 1
FROM ProductSubscriptions ps2
WHERE ps2.UserId <> ps1.UserId
AND ps2.StartDate <= ps1.EndDate
AND ps2.EndDate >= ps1.StartDate
) THEN 'True'
ELSE 'False'
END AS HasOverlappingSubscription
FROM ProductSubscriptions ps1;

Output:

Qs11

Explanation:This query checks for overlapping subscription date ranges for each user in the ProductSubscriptions table. It uses a self-join to compare each user's subscription dates (ps1) with those of all other users (ps2). If any overlap is found, it returns 'True'; otherwise, it returns 'False' for each user.

12. Calculate Cumulative Daily New Users with Monthly Reset

Here's an example of what the users table might look like:

UserIdSignUpDate
12024-01-01
22024-01-02
32024-01-05
42024-02-01
52024-02-05
62024-02-10
72024-03-01
82024-03-02
92024-03-03

Query:

SELECT 
SignUpDate,
COUNT(UserId) OVER (PARTITION BY EXTRACT(YEAR FROM SignUpDate), EXTRACT(MONTH FROM SignUpDate) ORDER BY SignUpDate) AS CumulativeUserCount
FROM
users
ORDER BY
SignUpDate;

Output:

Qs12

Explanation:This query calculates the cumulative number of new users added each day, with the count resetting at the beginning of every month. It uses the `COUNT()` window function with `PARTITION BY EXTRACT(YEAR FROM SignUpDate), EXTRACT(MONTH FROM SignUpDate)` to group the data by year and month, and `ORDER BY SignUpDate` to order the rows within each group by the sign-up date. This allows the count to reset for each month, providing a cumulative count of new users.

13. Analyzing Google Ad Campaign Performance with a SQL Query

Given a table google_ad_performance containing data about various Google ad campaigns, write a SQL query to calculate the total clicks, conversions, total cost, total revenue, and profit (revenue - cost) for each campaign. Group the results by campaign_id.

Table: google_ad_performance

datecampaign_idclicksconversionscostrevenue
2024-01-011100550.00100.00
2024-01-012120660.00110.00
2024-01-021110445.0095.00
2024-01-022130765.00120.00

Query:

SELECT
campaign_id,
SUM(clicks) AS total_clicks,
SUM(conversions) AS total_conversions,
SUM(cost) AS total_cost,
SUM(revenue) AS total_revenue,
SUM(revenue) - SUM(cost) AS profit
FROM
google_ad_performance
GROUP BY
campaign_id;

Output:

Qs13

14. Filtering Odd and Even Measurements Using a SQL Query

Given a table `measurements` with a column `value`, write a query to categorize each value in the `value` column as either 'Even' or 'Odd', and return the original value along with its category.

Table: measurements

idvalue
11
22
33
44
55
66
77
88
99
1010

Query:

SELECT
value,
CASE
WHEN value % 2 = 0 THEN 'Even'
ELSE 'Odd'
END AS category
FROM
measurements;

Output:

Qs14

Explanation:This query selects the `value` column from the `measurements` table and uses a `CASE` statement to categorize each value as either 'Even' or 'Odd'. If the value is divisible by 2 (`value % 2 = 0`), it is categorized as 'Even', otherwise it is categorized as 'Odd'. The result set includes the original `value` column and a new `category` column indicating whether each value is odd or even.

15. SQL Query to Find Locations within a Radius in Google Mapped Table

Let's Find locations within a 50 km radius of a specific latitude and longitude coordinate from the Google_mapped table.

Table: Google_mapped

idlocation_namelatitudelongitude
1Location A37.774929-122.419416
2Location B34.052235-118.243683
3Location C40.712776-74.005974
4Location D51.507351-0.127758
5Location E48.8566132.352222

Query:

SELECT
id,
location_name,
latitude,
longitude
FROM
Google_mapped
WHERE
6371 * 2 * ASIN(SQRT(
POWER(SIN((37.774929 - ABS(latitude)) * PI() / 180 / 2), 2) +
COS(37.774929 * PI() / 180) * COS(ABS(latitude) * PI() / 180) *
POWER(SIN((-122.419416 - longitude) * PI() / 180 / 2), 2)
)) <= 50;

Output:

idlocation_namelatitudelongitude
1Location A37.774929-122.419416

Explanation:This query retrieves the `id`, `location_name`, `latitude`, and `longitude` columns from the `Google_mapped` table. It filters the results to include only locations that are within a 50 km radius of the coordinates (37.774929, -122.419416) using the Haversine formula to calculate distances on a spherical Earth model. The `ASIN(SQRT(...))` part calculates the distance between each location and the specified coordinates, and the `WHERE` clause filters the results to include only locations within the specified radius.

Tips & Tricks to Clear SQL Interview Questions

  • Understand the Basics: Ensure you have a solid understanding of fundamental SQL concepts like SELECT statements, WHERE clauses, joins, and aggregate functions.
  • Practice Regularly: Regular practice with a variety of SQL problems is key. Use online platforms or SQL databases to practice writing and optimizing queries.
  • Learn Advanced Concepts: Beyond the basics, familiarize yourself with advanced SQL topics like window functions, CTEs (Common Table Expressions), and subqueries.
  • Optimize Your Queries: Learn how to write efficient queries and understand the importance of indexing and query optimization techniques.
  • Real-World Scenarios: Try to work on real-world datasets and problems. This will help you understand the practical applications of SQL and prepare you for scenario-based questions.
  • Review and Refactor: Regularly review your queries and seek feedback. Refactor your queries for better performance and readability.

Conclusion

In this article, we covered various SQL queries and concepts relevant to Google SQL interviews. Topics included identifying top Google search users, analyzing ad campaign performance, and handling flagged user-generated content. These examples provide a comprehensive overview of common SQL scenarios encountered in Google-related roles.


Next Article
Google SQL Interview Questions

S

satyamgu972h
Improve
Article Tags :
  • SQL
  • Databases

Similar Reads

    Google Bangalore Interview Experience
    Initial HR Discussion: Some recruiter from Singapore contacts through my google mail. She asked basic questions related to sorting algorithms.  Which is better heap sort or merge sort ? Why ?.  In which data structures log n time search is guaranteed  [Binary tree, Hash Map,   BST, Arrays] What is t
    1 min read
    Top 50 Most Asked Google Tricky Interview Questions
    Google is a dream workplace for every software developer to work in, It is one of the best in every aspect, be it the projects their employees work on or work-life balance. So, to be a part of such an awesome workplace one must be adequately prepared for its Technical and behavioral rounds of the hi
    15+ min read
    Google Interview Experience | Set 4
    Though I didn't clear google but I want to share my Google interview experience , so it can help other's . Please find my interview experience below: My Google Interview Experience for Software Developer Position [Android Core Team], London, United Kingdom Like many other enthusiastic engineers, I t
    3 min read
    Google Interview Questions
    As per, the Google Career Page there are two types of interviews, Phone/Hangout interviews, and Onsite Interviews. Below is an excerpt for their official page. For software engineering candidates, we want to understand your coding skills and technical areas of expertise, including tools or programmi
    3 min read
    Google SDE Sheet: Interview Questions and Answers
    Google is an American multinational technology company specializing in search engine technology, online advertising, cloud computing, computer software, quantum computing, e-commerce, and artificial intelligence. It is a dream of many people to work for Google. This sheet will assist you to land a j
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences