Data Cleaning Reps

← All guides

Same question, two tools: SQL vs Excel and Google Sheets

If you're learning data analysis, you'll probably use both SQL and spreadsheets for years. They're not rivals. Spreadsheets are great for looking at data and for quick, visible calculations. SQL is great for repeatable answers on bigger tables. The fastest way to get comfortable with SQL is to translate questions you already know how to answer in a spreadsheet.

Every example below uses this site's tables: quakes (2,628 USGS seismic events from October 2026), vehicles (22,111 FuelEconomy.gov records, model years 2010–2027) and state_population (66 Census rows). Column letters in the CSVs match the formulas: in quakes, F is mag and J is place. In vehicles, B is year, C is make, D is model, K is atv_type, N is comb_mpg and O is co2. In state_population, E is name and J is pop2024. As Guide 1 found, two of the quakes rows aren't earthquakes (a Washington explosion and a Nepal landslide). Neither is magnitude 5 or higher, so the counts below are all earthquakes.

How these were checked. The SQL outputs are real runs against the practice database. The standard Excel formulas (COUNTIF, AVERAGEIFS, XLOOKUP, FILTER, UNIQUE, SORTBY and the rest) were evaluated against the CSV files in LibreOffice Calc 26.8 and gave the same answers as the SQL. The Google Sheets formulas that Excel doesn't have (SORTN and QUERY) follow Google's documented syntax but were not tested in Sheets itself. Treat them as a starting point and compare against the SQL output.

A CSV is not a database. A CSV file doesn't keep SQL column types, and it can't tell NULL from an empty string: both are just an empty field between two commas. A spreadsheet guesses the types again every time you open the file, which is where several of the surprises below come from.

Counting with a condition: COUNTIF vs WHERE

How many events were magnitude 5.0 or higher?

SELECT COUNT(*) AS m5_plus
FROM quakes
WHERE mag >= 5;

Output (real run against the practice database):

m5_plus
226
1 row

Spreadsheet version, with magnitude in column F of quakes.csv:

=COUNTIF(F:F, ">=5")

Both return 226 (63 of those are exactly 5.0). The WHERE clause is the COUNTIF criterion. The header in F1 is text, so it isn't counted. With two conditions, COUNTIFS corresponds to WHERE ... AND ....

Two spellings: COUNTIF + COUNTIF vs OR

How many events were in California, written either as CA or California?

SELECT COUNT(*) AS california
FROM quakes
WHERE place LIKE '%, CA' OR place LIKE '%, California';

Output (real run against the practice database):

california
59
1 row
=COUNTIF(J:J, "*, CA") + COUNTIF(J:J, "*, California")

Both return 59: 56 end in , CA and 3 end in , California, and no place ends in both, so adding the two COUNTIFs doesn't double-count. In spreadsheets, * is the wildcard; in SQL LIKE, it's %. Both patterns must match the whole cell, which is what you want here. Pattern shape matters: a looser *CA* also catches places such as Canada and matches 182 events, not 56. The opposite blind spot exists too. 216 of the 2,628 labels have no comma at all (Fiji region, off the coast of Oregon), so a , CA or , Oregon pattern can never match them. None of those 216 mentions California, so 59 is complete, but the three off the coast of Oregon events are invisible to an Oregon count built this way (Guide 5 covers that blind spot).

That's also the overlap trap. Add COUNTIF(J:J, "*, CA") (56) to COUNTIF(J:J, "*CA*") (182) and you get 238, because every , CA place is also a *CA* place and is counted twice. The events matching either pattern number 182, which is what SQL's OR returns. With overlapping conditions in a spreadsheet, you'd need SUMPRODUCT or a helper column.

Averages that ignore placeholders: AVERAGEIFS vs NULLIF

What's the average CO2 for model year 2011, ignoring the -1 "not available" placeholder?

SELECT ROUND(AVG(NULLIF(co2, -1)), 1) AS avg_co2_2011
FROM vehicles
WHERE year = 2011;

Output (real run against the practice database):

avg_co2_2011
233.8
1 row
=ROUND(AVERAGEIFS(O:O, B:B, 2011, O:O, "<>-1"), 1)

Both return 233.8. Only 14 of the 1,126 rows for 2011 have a real co2 value; the other 1,112 are -1. The SQL version turns -1 into NULL, and AVG skips NULLs. The spreadsheet version needs the extra criterion. Forget it in either tool and you get 1.9, which is almost all placeholders.

Pivot tables vs GROUP BY

How many vehicle records exist per technology type, with blanks labeled "Conventional"?

SELECT COALESCE(NULLIF(atv_type, ''), 'Conventional') AS tech,
       COUNT(*) AS n
FROM vehicles
GROUP BY tech
ORDER BY n DESC;

Output (real run against the practice database):

techn
Conventional16565
Hybrid1837
EV1670
FFV1114
Plug-in Hybrid464
Diesel405
FCV43
CNG9
eFCV2
Bifuel (CNG)2
10 rows

In a spreadsheet, you'd add a helper column, then build a pivot table:

Helper column:  =IF(K2="", "Conventional", K2)
Pivot table:    Rows = helper column, Values = Count of id, sorted descending

The result is Conventional 16,565, Hybrid 1,837, EV 1,670, FFV 1,114, Plug-in Hybrid 464, Diesel 405, FCV 43, CNG 9, eFCV 2 and Bifuel (CNG) 2, which adds up to 22,111. All 16,565 "Conventional" rows are empty strings, not NULLs, so the helper's K2="" test is the right one. (In a spreadsheet, a CSV import makes those cells truly blank, and K2="" is true for a blank cell too.) Pivot "Rows" are the GROUP BY. Pivot "Values" are the aggregates. A pivot filter is a WHERE, and a value filter on the pivot is a HAVING. If pivot tables make sense to you, GROUP BY already does too.

Lookups vs JOIN

What's each state's 2024 population next to its seismic-event count?

In SQL this is a join (the guide on joining messy keys walks through it). In a spreadsheet it's a lookup. If A2 holds the state name:

=XLOOKUP(A2, state_population!E:E, state_population!J:J, "not found")

That returns 740,133 for Alaska, 39,431,263 for California, 587,618 for Wyoming, and not found when the name isn't in the file. The fallback does the job of a LEFT JOIN that you then check for NULLs.

Where the analogy breaks. XLOOKUP returns the first match it finds and stops. A JOIN returns every match. The two are equivalent only when the key is unique. Here it is: all 66 names in state_population are distinct, and the 52 rows with sumlev 040 are the state-level rows (the 50 states plus DC and Puerto Rico), and the other 14 are the nation, regions and divisions. So a state-name lookup is safe. Many-to-one keys aren't. California has 56 events ending in , CA. A join returns 56 rows:

SELECT COUNT(*) AS joined_rows
FROM state_abbrev s
JOIN quakes q ON q.place LIKE '%, ' || s.abbrev
WHERE s.abbrev = 'CA';

Output (real run against the practice database):

joined_rows
56
1 row

A wildcard lookup for the same ending, =XLOOKUP("*, CA", J:J, J:J, "none", 2), returns a single row: 52 km W of Petrolia, CA, the first one in the file. To count matches, use COUNTIF. To list them all, use FILTER. This is the same row-multiplication problem that Guide 5 checks for with joined_rows versus distinct events, only here the spreadsheet hides it by quietly returning one answer.

One warning that applies to this exact data: the Census file stores codes like 040 as text. A default import into LibreOffice Calc (and often into Excel or Sheets) turned every sumlev value into a number, so '040' became 40. Import that column as text. The lookup above uses names, so it still works after a sloppy import; a filter or lookup on sumlev would not. SQL keeps the column type you defined.

Top N with ties: SORT vs ORDER BY ... LIMIT

Which 2024 conventional and non-plug-in hybrid cars have the best combined MPG?

Here "conventional" means a blank atv_type, and "non-plug-in hybrid" means Hybrid. That leaves out plug-in hybrids, EVs, diesel, flex-fuel and the rest. 957 records qualify.

SELECT make, model, comb_mpg
FROM vehicles
WHERE year = 2024 AND atv_type IN ('', 'Hybrid')
ORDER BY comb_mpg DESC, make, model
LIMIT 5;

Output (real run against the practice database):

makemodelcomb_mpg
ToyotaPrius57
HyundaiElantra Hybrid Blue54
ToyotaPrius AWD54
KiaNiro FE53
ToyotaCamry Hybrid LE52
5 rows

Excel 365 or Excel 2024:

=LET(d, FILTER(C2:N22112, (B2:B22112=2024)*((K2:K22112="")+(K2:K22112="Hybrid"))), CHOOSECOLS(TAKE(SORTBY(d, CHOOSECOLS(d,12), -1, CHOOSECOLS(d,1), 1, CHOOSECOLS(d,2), 1), 5), 1, 2, 12))

Google Sheets (follows Google's documented syntax; not tested in Sheets itself):

=CHOOSECOLS(SORTN(FILTER(C2:N22112, (B2:B22112=2024)*((K2:K22112="")+(K2:K22112="Hybrid"))), 5, 0, 12, FALSE, 1, TRUE, 2, TRUE), 1, 2, 12)

Both return Toyota Prius 57, Hyundai Elantra Hybrid Blue 54, Toyota Prius AWD 54, Kia Niro FE 53 and Toyota Camry Hybrid LE 52. The fifth row sits on the edge of a tie at 52 MPG: Toyota Prius XLE/LTD is also 52 and just misses the cut, because the make and model tie-breakers put Camry Hybrid LE first. Drop the tie-breakers and two people can get different top-five lists.

How the Excel formula works. LET names the filtered table d once, so the formula doesn't repeat the FILTER. The range C2:N22112 starts at make in column C and ends at comb_mpg in column N, so inside d column 1 is make, column 2 is model and column 12 is comb_mpg. SORTBY sorts d by MPG descending (-1), then make, then model, TAKE keeps the first 5 rows, and CHOOSECOLS keeps only make, model and MPG. This needs Excel 365 or Excel 2024, because TAKE and CHOOSECOLS aren't in Excel 2021. This one was evaluated in LibreOffice Calc 26.8 and returned the five rows above (and the same 957 qualifying rows).

How the Google Sheets formula works. Google's function list has no TAKE and no SORTBY. SORTN does both jobs: SORTN(range, n, display_ties_mode, sort_column1, is_ascending1, ...) returns the first n rows after sorting. Here 5 is n, and 0 means "show at most the first 5 rows", the same as LIMIT 5. The sort columns are given as positions inside the range (12 is comb_mpg, 1 is make, 2 is model), each followed by FALSE for descending or TRUE for ascending. CHOOSECOLS is on Google's list, so it trims the result to make, model and MPG. We checked the argument order and the tie mode against Google's SORTN page, and replayed those semantics in Python on the CSV: same five rows. We did not run it in Sheets.

Sheets also has QUERY, which Excel does not, and it reads a lot like the SQL:

=QUERY(A2:S22112, "select C, D, N where B=2024 and (K is null or K='' or K='Hybrid') order by N desc, C, D limit 5", 0)

The (K is null or K='' or K='Hybrid') part matters. A blank cell in a CSV import is empty, which QUERY treats as null, so a plain K='' can miss it. Also note how QUERY treats mixed types: each column gets one type (the majority type), and the minority values are treated as null. A numeric column with a few stray text entries such as n/a would silently lose them. Here every column used is clean (B and N are all numbers, K is all text or blank). Replaying this query's logic in Python on the CSV gives the same five rows. Like the SORTN formula, it follows Google's documented syntax and was not tested in Sheets itself. ARRAYFORMULA is Sheets-only as well, and you don't need it around FILTER, UNIQUE or SORT; those already return arrays.

Which functions work where

Not every formula in this guide exists in every spreadsheet. This table was checked against Microsoft's and Google's function pages in December 2026.

Function Excel 365 Excel 2024 Excel 2021 Google Sheets
COUNTIF Yes Yes Yes Yes
AVERAGEIFS Yes Yes Yes Yes
XLOOKUP Yes Yes Yes Yes
FILTER Yes Yes Yes Yes
UNIQUE Yes Yes Yes Yes
SORT Yes Yes Yes Yes
SORTBY Yes Yes Yes No
TAKE Yes Yes No No
CHOOSECOLS Yes Yes No Yes
SORTN No No No Yes
QUERY No No No Yes

LET is in Excel 365, 2024 and 2021, and in Google Sheets. Excel 2019 and earlier have COUNTIF and AVERAGEIFS but none of the other functions in the table.

Counting distinct values: UNIQUE vs COUNT(DISTINCT)

How many different makes have a 2024 record?

SELECT COUNT(DISTINCT make) AS makes_2024
FROM vehicles
WHERE year = 2024;

Output (real run against the practice database):

makes_2024
49
1 row
=COUNTA(UNIQUE(FILTER(C2:C22112, B2:B22112=2024)))

Both return 49. There are no blank 2024 makes, so the empty-string caveat doesn't change the number, but it is still worth stating: COUNT(DISTINCT ...) has been standard SQL for decades and ignores NULLs, yet it does not ignore empty strings. A blank make stored as '' would count as one more "make," and UNIQUE would keep that blank too. Older SUMPRODUCT(1/COUNTIF(...)) tricks break on blanks and are slow on large ranges. UNIQUE and FILTER need Excel 2021 or later, Excel 365, or Google Sheets.

When to use which

A rough rule of thumb from working with both:

Most real work uses both: SQL to produce a clean table, and a spreadsheet to explore, chart and share it.

Practice it

Every exercise on this site has a "Same question in Excel / Google Sheets" note under the editor (all 30 of them), and every table is a CSV on the datasets page. Closest to this guide: Magnitude 5 and up, California, spelled two ways, Average CO2 the right way, Give blanks a real label and Most efficient non-plug-in cars of 2024. When the two tools disagree, the difference usually points at a blank, a placeholder, or a type conversion.

Check your understanding

Six questions on translating between SQL and spreadsheet formulas, using the quakes, vehicles and state_population tables. Pick an answer to get instant feedback.

0 of 6 answered

  • Correct 0
  • Incorrect 0
  • Accuracy —
1. Which spreadsheet formula matches SELECT COUNT(*) FROM quakes WHERE mag >= 5, with magnitude in column F?
2. A teammate counts events that match either pattern with =COUNTIF(J:J, "*, CA") + COUNTIF(J:J, "*CA*"). The first part returns 56 and the second 182. What's wrong with the total of 238?
3. =AVERAGEIFS(O:O, B:B, 2011) returns 1.9, but the correct average CO2 for model year 2011 is 233.8. Why?
4. You build a pivot table of vehicle records by technology type (Conventional 16,565, Hybrid 1,837, EV 1,670, and so on). Which part of the pivot is the GROUP BY?
5. California has 56 events ending in , CA. A join from state_abbrev to quakes on that ending returns 56 rows. What does the wildcard lookup =XLOOKUP("*, CA", J:J, J:J, "none", 2) return?
6. In state_population.csv, sumlev is stored as 040, and WHERE sumlev = '040' returns 52 rows in SQL. After a default spreadsheet import, the column shows 40. What happened, and what's the fix?

CO2 coverage report for model year 2012

Part 1 (graded): write one query that returns a single row for model year 2012 with five columns, in this order: records (all rows), with_co2 (rows with a real co2 value, not the -1 placeholder), missing_co2 (rows where co2 is -1), coverage_pct (with_co2 as a percentage of records, rounded to 1 decimal) and avg_co2 (the average of the real values only, rounded to 1 decimal). Check your result: 1146 records, 20 with a value, 1126 missing, 1.7% coverage and an average of 178.9. Guide 2 worked with model year 2011. Year 2012 has a different shape, so don't copy numbers from that guide.

Part 2 (not graded): reproduce it in a spreadsheet

Open vehicles.csv in Excel or Google Sheets (model year is column B, co2 is column O) and write one formula for each of the five numbers. They should match your SQL result.

Show reference

Reference formulas. These were evaluated against the CSV in LibreOffice Calc 26.8 and returned 1146, 20, 1126, 1.7 and 178.9.

records       =COUNTIFS(B:B, 2012)
with_co2      =COUNTIFS(B:B, 2012, O:O, "<>-1")
missing_co2   =COUNTIFS(B:B, 2012, O:O, -1)
coverage_pct  =ROUND(100*COUNTIFS(B:B, 2012, O:O, "<>-1")/COUNTIFS(B:B, 2012), 1)
avg_co2       =ROUND(AVERAGEIFS(O:O, B:B, 2012, O:O, "<>-1"), 1)

The idea is the same as in the guide: COUNTIFS and AVERAGEIFS take the place of WHERE, and the "<>-1" criterion does the job of NULLIF. Without it, the average over all 2012 rows is 2.1.

Part 3 (not graded): would you publish the average?

Your report says the average CO2 for 2012 is 178.9 grams per mile. In two or three sentences: would you publish that as "the average for 2012 cars"? Look at what kinds of vehicles have a value before you answer. You can group the 20 rows by atv_type to check.

Show reference

Reference answer: No. Only 20 of 1,146 records (1.7%) have a real value, and they aren't a random sample. All 20 are electric vehicles (8, with CO2 of 0), plug-in hybrids (3) or diesels (9). None of the 928 conventional gasoline records has a value. So 178.9 describes a few electrified and diesel models, not 2012 cars in general. Those 20 rows average 52.55 combined MPG, compared with 21.8 across all 2012 rows. Report the coverage next to the average, or say CO2 isn't available for that model year.

Tip: Ctrl+Enter (⌘+Enter on Mac) checks your answer. Everything runs in your browser.

Open in the playground