Python and SQL for AI: Clean Data, Validate Records and Test Your Work

Build practical Python and SQL skills with an original record-cleaning example, a runnable SQL query, three explained exercises and a mini-project with clear completion checks.

AIJobFever Research TeamEditorial research and AI career analysis

Published
17 Oct 2026
Reviewed
17 Oct 2026
Read
7 min
QUICK ANSWER

What you need to know

Build practical Python and SQL skills with an original record-cleaning example, a runnable SQL query, three explained exercises and a mini-project with clear completion checks.

Reliable AI work begins before a model call. You need to read records, distinguish missing information from observed values, preserve identity and explain why a row was accepted or rejected. Python is useful for explicit validation and orchestration; SQL is useful for inspecting and aggregating data at a defined grain. Neither skill is demonstrated by silently cleaning away inconvenient records.

In this guide you will build a small, original job-record fixture, normalize it without inventing fields and answer a question using SQL. The examples run locally without a model, credentials or paid services. They are deliberately small educational examples, not a production ingestion service or a claim about employer hiring demand.

Before you start

You should be able to run Python 3, recognize strings, integers, lists and dictionaries, and understand that a database table contains rows with a defined meaning. The runnable examples use only Python's standard library and a SQLite-compatible SQL query. Google's Python and GoogleSQL references provide background reading; the SQL here is not a BigQuery setup tutorial.

Use fictional records while learning. Do not copy private resumes, access tokens or confidential employer data into a public repository. Keep your original inputs separate from cleaned outputs so you can investigate a mistake without reconstructing what the source might have said.

Learning sequence

  1. Define one record's identity and field meanings. Decide whether a missing city is allowed and whether experience is an integer or a range.
  2. Write pure transformation functions: explicit input, explicit output and no hidden network or database changes.
  3. Add rejection reasons and test normal, missing, malformed and repeated inputs.
  4. Learn SELECT, WHERE, GROUP BY, COUNT and joins using a tiny dataset whose correct answer you can calculate by hand.
  5. Combine the pieces only after each step is independently explainable. Add durable writes and concurrency controls later, rather than confusing an in-memory demonstration with safe production ingestion.

The milestone is not finishing a tutorial. It is being able to explain where every output value came from, what happened to every rejected record and which assumptions would change when the source changes.

Worked example

The policy below accepts an exact integer experience value of zero or greater, preserves a missing city as unknown and identifies duplicates by a stable source ID. It rejects duplicate rows rather than deciding which revision wins. That is a teaching policy, not a universal deduplication rule. A real update feed needs version and correction semantics.

PythonExample code
def clean_records(rows):
    accepted, rejected, seen = [], [], set()
    for row in rows:
        source_id = row.get("source_id")
        title = row.get("title")
        years = row.get("years")
        city = row.get("city")
        reason = None
        if not isinstance(source_id, str) or not source_id.strip():
            reason = "missing source identity"
        elif not isinstance(title, str) or not title.strip():
            reason = "missing title"
        elif type(years) is not int or years < 0:
            reason = "invalid experience"
        elif city is not None and not isinstance(city, str):
            reason = "invalid city"
        if reason:
            rejected.append((source_id, reason))
            continue
        source_id = source_id.strip()
        if source_id in seen:
            rejected.append((source_id, "duplicate source identity"))
            continue
        seen.add(source_id)
        accepted.append({
            "source_id": source_id,
            "title": " ".join(title.split()),
            "years": years,
            "city": (city.strip() or None) if city is not None else None,
        })
    return accepted, rejected

rows = [
    {"source_id": "a", "title": " AI  Engineer ", "years": 0, "city": None},
    {"source_id": "b", "title": "Data Engineer", "years": 2, "city": " Pune "},
    {"source_id": "a", "title": "AI Engineer", "years": 0, "city": None},
    {"source_id": "c", "title": "ML Engineer", "years": True, "city": "Delhi"},
]
accepted, rejected = clean_records(rows)
assert len(accepted) == 2
assert accepted[0]["title"] == "AI Engineer"
assert accepted[0]["city"] is None
assert rejected == [("a", "duplicate source identity"), ("c", "invalid experience")]
assert rows[0]["title"] == " AI  Engineer "
print("accepted=2 rejected=2")
Illustrative example · Review and adapt before use

Notice the exact type check for experience. In Python, a boolean can pass an ordinary integer-instance check; that does not make True a meaningful year of experience in this contract. Also notice that zero is valid. A condition such as if not years would incorrectly reject the fresher record. The function creates new records and leaves the original input unchanged.

Now count records by city. This self-contained query uses a common table expression as a fictional input table. Run it in SQLite; the aliases in the two-column VALUES fixture make the example easy to inspect. COUNT(*) counts rows, while COUNT(city) would ignore the null city.

SQLExample code
WITH jobs(source_id, city) AS (
  VALUES ('a', NULL), ('b', 'Pune'), ('d', 'Pune')
)
SELECT COALESCE(city, 'Unknown') AS city_label,
       COUNT(*) AS job_count
FROM jobs
GROUP BY COALESCE(city, 'Unknown')
ORDER BY city_label;
Illustrative example · Review and adapt before use

The expected result is Pune with 2 records and Unknown with 1. The label Unknown is a display choice, not an inferred location. Do not overwrite source nulls with that text merely to make grouping convenient; presentation and stored meaning are different concerns.

Exercises and solutions

Exercise 1: Preserve zero and unknown

A record has years=0 and city=None. Should it be rejected, and should the city be replaced with the company's headquarters?

Solution: Accept it under the stated contract. Zero is a known experience value; the city is unknown. Headquarters does not prove the work location. Add a test that asserts both values survive unchanged. If your product requires a city, place the record in a review state rather than inventing one.

Exercise 2: Choose a duplicate policy

Two records have the same title but different source IDs. A third record repeats an existing source ID with a changed city. Which rows should the example merge?

Solution: It merges none: different IDs remain distinct, and an already accepted ID is rejected as a duplicate. The changed-city case exposes a limitation. For real updates, obtain a source version or reliable update timestamp and define precedence; title similarity alone cannot decide whether an opening changed or a new opening exists.

Exercise 3: Diagnose a join that multiplies rows

One job has three skill rows. Joining jobs to skills and counting job rows returns three. How would you count unique jobs while still examining skills?

Solution: First state the grain: the joined output is one job-skill relationship, not one job. Use COUNT(DISTINCT job_id) for a unique-job count where that matches the question, or aggregate skills before joining. Do not use DISTINCT as a general repair without checking which values and relationships you need to preserve.

Mini-project

Build a fictional job-data quality report. Supply a local fixture with missing cities, blank titles, invalid types, repeated IDs and legitimate same-title openings. Separate loading, validation, transformation and reporting. Keep rejected records with reasons instead of printing a success message that hides losses.

Deliver a small module, a repeatable test command, an input-contract document and SQL queries answering counts by city and experience. Add a reconciliation: input count equals accepted count plus rejected count for this one-pass policy. Explain that this equation does not yet establish update-feed correctness or cross-run idempotency.

Completion criteria: all supplied fixtures have expected outcomes; raw inputs remain unchanged; zero is not missing; null location is not guessed; duplicate identity is explicit; and the SQL totals match your hand calculation. Include a change request describing how you would support corrected records without claiming that the extension already exists.

Common mistakes

  • Catching every exception and silently skipping the row.
  • Changing a list while iterating through it without a deliberate strategy.
  • Treating a title as a stable identifier or a missing value as zero.
  • Joining tables without checking one-to-many relationships.
  • Building SQL with string-concatenated user input. Real applications should use the database driver's supported parameter binding for values.
  • Claiming an in-memory seen set protects multiple processes or survives a restart.

Self-assessment

Can you trace an accepted value to its source, explain each rejection reason, distinguish null from zero and predict join cardinality? Can another person reproduce the report from your fixture? If not, revisit those gaps before adding a model. A readable data contract and a few reliable tests demonstrate more than a large notebook whose transformations cannot be reconstructed.

Connect this skill to roles and jobs

Read the Data Engineer career guide, practise Data Engineer interview questions and explore jobs mentioning Python. Listings can include adjacent responsibilities, so inspect the employer's requirements. For the broader context, return to AI Skills overview.

HOW THIS WAS PREPARED

Methodology

Editorial synthesis of cited sources

AI-assisted original educational material. Explanations, code, fictional fixtures, exercise solutions and mini-project acceptance criteria were prepared for this site, not reproduced from the references. Official Google references support background concepts, not an endorsement or validation of these projects. Runnable Python examples use the standard library; the SQL fixture is checked with SQLite and is not a BigQuery deployment tutorial. Samples demonstrate bounded concepts, not production-ready systems. Measurements and scenario values are synthetic, not benchmark results. Mini-projects are suggested exercises, not claims of completed deployments. No paid model calls are needed to run the examples. Related jobs use a skill or specialization filter and may include adjacent roles. References checked 17 October 2026. No hiring guarantees or unmeasured demand rankings are implied.

Read our editorial and research policy →
EVIDENCE

Sources

  1. Python Lists

    Google for Developers · Checked 17 October 2026

  2. GoogleSQL query syntax

    Google Cloud · Checked 17 October 2026

LIVE OPPORTUNITIES

2034 matching open roles in the current catalogue.

Apple

Senior Machine Learning Engineer / Senior Applied Scientist, Search & AI

Bengaluru · On-site

AustralianSuper

AI Software Engineer / Senior Engineer AI Software Engineer

Melbourne, Australia · Hybrid

Julius Baer

Machine Learning Engineer

Singapore · On-site

SPH Media Limited

Lead, AI TechOps

Singapore · On-site

Toast

Principal Machine Learning Engineer, Vision AI

Remote, United States · Remote

Shopee

Backend Engineer, Search (2027 Graduate)

Singapore · On-site

KEEP LEARNING

Related career insights.

Career Guides

How to Become a Data Engineer: SQL, Reliable Pipelines and Portfolio Projects

Build data engineering foundations through ingestion, incremental loads, schema contracts and recovery, with three project briefs and explained interview answers.

Read insight →
Interview Preparation

Data Engineer Interview Questions: 10 Detailed Answers and Scenarios

Practise ten Data Engineer interview questions with detailed answers about data contracts, incremental ingestion, duplicates, schema evolution, late events, backfills and recovery.

Read insight →
AI Skills

Top AI Skills Employers Are Looking For

The AI skills that form a durable hiring stack: software engineering, data and ML foundations, LLM evaluation, production operations and human judgment.

Read insight →