Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Start free

Debug and Optimize SQL

HardSQL & Data Manipulation00:00
Practice interviewer
In session
5 left
00:00

Whenever you're ready, walk me through how you'd approach this.

Sign up free to chat or submit. Log in

Problem

MITRE tracks open vulnerability findings against internal systems for its own security program. You are handed the query below, printed on paper with no IDE, and asked to say what it is meant to do, find the errors in it, and describe how you would optimize it.

-- findings has an index on (system_id, detected_date)
CREATE TABLE systems (
    system_id INT PRIMARY KEY,
    system_name VARCHAR(200),
    criticality VARCHAR(20)
);

CREATE TABLE vulnerabilities (
    cve_id VARCHAR(20) PRIMARY KEY,
    cvss_score NUMERIC(3,1),
    published_date DATE
);

CREATE TABLE findings (
    finding_id BIGINT PRIMARY KEY,
    system_id INT REFERENCES systems(system_id),
    cve_id VARCHAR(20) REFERENCES vulnerabilities(cve_id),
    detected_date TIMESTAMP,
    status VARCHAR(20)
);

SELECT
    s.system_name,
    COUNT(f.finding_id) AS open_findings,
    AVG(v.cvss_score) AS avg_severity
FROM systems s
LEFT JOIN findings f ON f.system_id = s.system_id
JOIN vulnerabilities v ON v.cve_id = f.cve_id
WHERE f.status = 'open'
  AND s.criticality = 'high'
  AND YEAR(f.detected_date) >= 2023
GROUP BY s.system_name
HAVING COUNT(f.finding_id) > 0
ORDER BY avg_severity DESC;

Explain what this query is meant to do, identify every error you can find in it, and describe how you would optimize it for a findings table with tens of millions of rows.