Checking data with SQL
Write the queries that catch duplicates, coded values and inconsistent categories, turn them into data checks that keep watching, and add or export the checks the profile suggests.
What runs in CodeSplash
- Outliers (univariate) Verified in Python and R
You will be able to
- Find duplicate keys, sentinel values and inconsistent spellings
- Safely convert text to numbers with TRY_CAST
- Turn a check query into a saved data check
- Review suggested checks one by one, and export checks to other tools
Read first
Trust, then verify
ReadBefore you analyze a table, ask whether it's what it claims to be. Insights does this for you, and knowing the queries behind it lets you check what a profiler can't guess: your own rules.
Add the messy customer list. All its awkward columns are stored as text.
Messy customer listIs the key a key?
PredictPredict first
The table has 612 rows, one per customer, it says. What do you expect?
Reveal
A few duplicates: 600 distinct IDs in 612 rows, with 12 IDs appearing twice. A customer counted twice inflates revenue, skews a mean and breaks any join that assumes the key is unique.
Find the duplicates
In the appRun these.
SELECT count(*) AS n, count(DISTINCT customer_id) AS ids
FROM messy_customer_list_sample;
SELECT customer_id, count(*) AS copies
FROM messy_customer_list_sample
GROUP BY customer_id
HAVING count(*) > 1
ORDER BY copies DESC, customer_id
LIMIT 5;
Look at a duplicated customer's two rows. Are they identical, or do they disagree? If they disagree, you need to decide which row is true before any cleanup can be right.
Coded values and spellings
ExploreGroup a column by itself and read what's there.
SELECT age, count(*) AS n
FROM messy_customer_list_sample
GROUP BY age
ORDER BY n DESC
LIMIT 8;
SELECT count(DISTINCT plan) AS spellings,
count(DISTINCT lower(trim(plan))) AS plans
FROM messy_customer_list_sample;
A code like -99 is a number that means "unknown". You'll find it with a query like this, and a mean would happily include it. And plan has 15 spellings of 3 plans: stray spaces and capitals.
Text to numbers
Exploreage is text, so CAST fails on any value that isn't a number. TRY_CAST gives NULL instead, so you can see what didn't convert.
SELECT age, count(*) AS n
FROM messy_customer_list_sample
WHERE age IS NOT NULL AND TRY_CAST(age AS INTEGER) IS NULL
GROUP BY age
ORDER BY n DESC;
SELECT count(*) AS impossible
FROM messy_customer_list_sample
WHERE TRY_CAST(age AS INTEGER) < 0 OR TRY_CAST(age AS INTEGER) > 120;
The first query lists anything that isn't a number. The second applies a rule only you could write: nobody here is below 0 or above 120.
Make the check permanent
In the appA query you ran once protects you once. On a dataset's Checks tab, press Add check. The kinds include Not missing, Unique and Accepted values, plus a custom check: a Query returning the failing rows.
The second query above is one of those already. Add it, press Run checks, and read the failing-rows query it shows. Checks run again as your data changes, and models run them when they build.
Let the profile suggest checks
In the appSuggest checks on the Checks tab reads the table's profile and proposes checks it already meets, such as a key that's unique or a column that's never missing. Each one says why. Tick the ones you want and press the button that counts them, such as Add 2 checks. Nothing is added until you do.
On an Insights finding about missing values, outliers, a shift, a missing-value code or messy categories, Make it a check proposes one check for it.
Export checks writes the enabled checks for Great Expectations, Pandera, R validate or dbt, so the same rules run where the data is built.
Met today, true tomorrow?
PredictPredict first
Suggest checks proposes "discount is between 0 and 40", and today's data passes it. Should you add it?
Reveal
The answer: Only if it's a rule the process must follow
Only if it's a rule. A suggestion describes today's rows, so it passes by construction. If discounts can't exceed 40, the check will catch a bad load. If 40 is only the largest discount so far, it will fail the first time someone offers 45, and that failure means nothing.
Count the gaps yourself
In the appThis one uses the penguins table, which has gaps to count. It opens in a new SQL tab, and Check compares your result with the answer's.
SQL exercise · penguins
Count what's missing
In one row, show how many rows the table has and how many have no sex recorded. Call them row_count and missing_sex.
Hints
- count(*) counts rows; count(sex) counts rows where sex has a value.
- = NULL never matches. To test for missing, use IS NULL.
Show a solution
SELECT count(*) AS row_count, count(*) - count(sex) AS missing_sex
FROM {{table}};In the app this opens in a real SQL tab on the sample table and checks your result.
Check your understanding
CheckpointCheck yourself
How many customer IDs appear more than once?
Show the answer
Answer: 12
612 rows minus 600 distinct IDs leaves 12 extra rows, and here each duplicated ID appears exactly twice.
Check yourself
How many rows have an age of -99? Write the query, and type the count.
Show the answer
Answer: 22
WHERE age = '-99' returns 22 rows. age is text, so the value needs quotes.
Check yourself
Why use TRY_CAST rather than CAST while exploring a dirty column?
Show the answer
Answer: b
CAST stops at the first bad value. For a one-off check, you want to see all the bad values at once.
Check yourself
Your team builds the customer table in dbt. Which way of sharing your checks keeps them running there?
Show the answer
Answer: b
The dbt export writes the checks as that model's data tests, so they run every time the table is built. Pandera suits pandas data frames in Python.
Outliers are a different question
ReflectA value of -99 is an error, and a very high income may be real. What rule could tell these apart in your data? When values are plausible but extreme, investigate them; don't delete them. Statistics can help you find them:
Recap
Recap- Check that keys are unique, read a column's values by grouping, and test your own rules.
TRY_CASTlets you list what doesn't convert.- Turn a check query into a data check, so it keeps watching.
- Add a suggested check only when it's a rule, not a fact about today's rows.
Concepts in this lesson