你的地图在骗你:Snowflake中坏坐标的5个SQL检查
直接阅读原文DataHot 速览
文章指出,经纬度字段非空并不代表坐标可信,可能存在占位值、经纬度颠倒或仅精确到邮编的情况,问题不会在null计数中暴露,而会在配送区域、风险模型聚类、区域报表中显现。作者给出5个可在Snowflake直接运行的只读SQL检查,通过创建统一命名的视图适配不同表结构,并把文本坐标用TRY_TO_DOUBLE转换。这些检查用于在数据分析前评估地理数据的质量。
原收录理由(待核验):地理坐标质量问题直接影响基于位置的分析、风控与配送决策,文章给出可直接复用的SQL检查方法,对做数据质量与语义一致性的数据从业者有实操价值。
本文目录 8 节
原文
Five quick SQL checks that show whether the latitude and longitude in your warehouse can be trusted.
A table with a latitude and longitude on every row looks finished. The columns are full, the map renders, the dashboards load.
But a coordinate can be present and still be wrong. It can be a placeholder, a swapped pair, or a point that only knows the ZIP code, not the building. None of that shows up in a null count. It shows up later, as a delivery zone that is off, a risk model that clusters customers in the wrong place, or a territory report that does not add up.
The good news is that most of these problems leave fingerprints you can find with plain SQL. Here are five checks you can run on any table of coordinates in Snowflake today, whatever tool produced them.
The table we will check
Every table names its columns differently. Yours might say LAT and LNG, or GEO_LAT and ZIP5. The queries below use one set of standard names, shown here:
-- my_schema.customer_locations
-- customer_id VARCHAR
-- address_line VARCHAR
-- city VARCHAR
-- state VARCHAR -- two-letter code, e.g. 'TX'
-- postal_code VARCHAR
-- latitude FLOAT
-- longitude FLOATSo you never have to edit the checks, map your own table to those names once with a view. Change only the left-hand side of each line:
CREATE OR REPLACE VIEW my_schema.customer_locations AS
SELECT
your_id_column AS customer_id,
your_address_column AS address_line,
your_city_column AS city,
your_state_column AS state,
your_zip_column AS postal_code,
your_lat_column AS latitude,
your_lng_column AS longitude
FROM your_schema.your_table;Every query in this post then runs against the view as written. If you store coordinates as text, wrap them in TRY_TO_DOUBLE() inside the view, so the checks treat values that cannot be read as numbers as missing rather than failing.
CREATE OR REPLACE overwrites any existing view with the same name, so pick a name that is not already in use and use it in the queries below.
Apart from creating that view, every check is read-only. Nothing here changes your data.
Check 1: missing and zero coordinates
Start with the obvious. Nulls are easy to spot, but 0, 0 is sneakier. It is a common default when a geocode fails, and it puts your customer in the Atlantic Ocean off the coast of Africa.
SELECT
COUNT(*) AS total_rows,
COUNT_IF(latitude IS NULL OR longitude IS NULL) AS missing,
COUNT_IF(latitude = 0 AND longitude = 0) AS zero_zero
FROM my_schema.customer_locations;If zero_zero is above zero, some process is writing a placeholder instead of leaving the value empty. Those rows can quietly distort distances, averages and maps built on them.
Check 2: swapped latitude and longitude
Almost every US address has a positive latitude and a negative longitude. If a loader or an API client mixes up the order, the signs flip: a negative number lands in the latitude column and a positive one in longitude.
SELECT customer_id, state, latitude, longitude
FROM my_schema.customer_locations
WHERE latitude < 0
AND longitude > 0;This is one of the most common integration bugs in location data, and one of the easiest to fix once you find it. Before correcting anything, compare a sample of the flagged rows with the original source to confirm the order really was reversed.
Check 3: coordinates outside the expected US range
If your customers are all in the US, every point should sit inside a broad US box. The ranges below cover the 50 states, Puerto Rico and the US Virgin Islands. Tighten them if your footprint is smaller, for example to the lower 48 only.
SELECT customer_id, state, latitude, longitude
FROM my_schema.customer_locations
WHERE latitude IS NOT NULL
AND longitude IS NOT NULL
AND ( latitude NOT BETWEEN 17.5 AND 71.5
OR longitude NOT BETWEEN -180 AND -64.5);This is a broad sanity check, not an exact US boundary test. It catches points in the wrong hemisphere, typos and test data, but some points in Canada, Mexico or the Caribbean will still pass. One edge case: the far western Aleutian Islands cross the 180th meridian, so a handful of genuine Alaska addresses can show up here. Guam and other Pacific territories will also flag, so add them back if you serve them.
Check 4: pile-ups on a single coordinate
This is the check most teams have never run, and it is the most revealing.
When a geocoder cannot find a building, it often falls back to a broader location, such as the center of a ZIP code or a city. The address still gets a coordinate, so nothing looks missing. But hundreds of different addresses end up stacked on exactly the same point.
SELECT
latitude,
longitude,
COUNT(*) AS records,
COUNT(DISTINCT address_line, postal_code) AS distinct_addresses,
COUNT(DISTINCT postal_code) AS distinct_zips
FROM my_schema.customer_locations
WHERE latitude IS NOT NULL
GROUP BY latitude, longitude
HAVING COUNT(DISTINCT address_line, postal_code) > 25
ORDER BY distinct_addresses DESC;How to read the results:
- Many distinct addresses, one ZIP: may indicate a ZIP-level fallback. Fine for regional reporting, not for distance or routing.
- Many distinct addresses across several ZIPs: may indicate a city-level fallback. These points can be miles from the real address.
- Many addresses on one street or complex: may be a genuine large site, such as a campus or apartment community. Spot-check a few.
The threshold of 25 is a starting point. Lower it for small tables, raise it for very large ones.
Check 5: coordinates that may have been rounded
Coordinates can lose detail when they are rounded during an export, a spreadsheet step or a transformation. A point that started with five decimal places may arrive with two.
One caution first: decimal places do not prove accuracy. A ZIP code centroid stored with six decimal places is still a ZIP code centroid. What this check can show is precision being lost somewhere in your pipeline.
These are the approximate distances between possible values, not accuracy guarantees. Longitude steps shrink as you move away from the equator.
SELECT
COUNT(*) AS total_rows,
COUNT_IF(latitude = ROUND(latitude, 2)
AND longitude = ROUND(longitude, 2)) AS on_two_decimal_grid
FROM my_schema.customer_locations
WHERE latitude IS NOT NULL
AND longitude IS NOT NULL
AND NOT (latitude = 0 AND longitude = 0);A small share of rows on the two-decimal grid is normal by chance. A large share is worth tracing back through your pipeline.
Put it together: a one-query scorecard
Run the row-level checks in one pass to get a quick health score for any table. It is a useful query to schedule, or to run before a location table feeds a model or a dashboard.
WITH point_stats AS (
SELECT latitude, longitude,
COUNT(DISTINCT address_line, postal_code) AS distinct_addresses
FROM my_schema.customer_locations
WHERE latitude IS NOT NULL
AND longitude IS NOT NULL
AND NOT (latitude = 0 AND longitude = 0)
GROUP BY latitude, longitude
),
flagged AS (
SELECT l.*, p.distinct_addresses
FROM my_schema.customer_locations l
LEFT JOIN point_stats p
ON l.latitude = p.latitude
AND l.longitude = p.longitude
)
SELECT
COUNT(*) AS total_rows,
COUNT_IF(latitude IS NULL OR longitude IS NULL) AS missing,
COUNT_IF(latitude = 0 AND longitude = 0) AS zero_zero,
COUNT_IF(latitude < 0 AND longitude > 0) AS possibly_swapped,
COUNT_IF(latitude NOT BETWEEN 17.5 AND 71.5
OR longitude NOT BETWEEN -180 AND -64.5) AS outside_us_range,
COUNT_IF(NOT (latitude = 0 AND longitude = 0)
AND latitude = ROUND(latitude, 2)
AND longitude = ROUND(longitude, 2)) AS on_two_decimal_grid,
COUNT_IF(distinct_addresses > 25) AS rows_on_shared_points
FROM flagged;The pile-up column uses the same rule as Check 4: more than 25 distinct addresses on one point. It counts the rows sitting on those points, not the number of points. A row can still count in more than one column, so treat the scorecard as a map of where to look, then use the individual checks to dig in.
Fixing it at the source
These checks flag suspicious coordinates. They cannot prove every other point is right, and they do not fix anything. Most of what they surface traces back to how the coordinates were produced in the first place: placeholders written on failure, precision lost in an export, or fallbacks nobody can see.
The fix is a geocoding step that looks for the most precise match first, falls back to a broader match only when it has to, and runs where your data already lives, so there is no export and re-import step to lose precision along the way.
At Service Objects we built Address Geocode US as a Snowflake Native App for exactly this. You call it from SQL on any table, and it writes coordinates, Census geography and jurisdiction data back to a table in your account. It is on the Snowflake Marketplace with a free 90-day trial.
Whatever you use, run the scorecard first. It tells you how much of your map you can actually trust.
Your Map is Lying to You: 5 SQL Checks for Bad Coordinates in Snowflake was originally published in Snowflake Builders Blog: Data Engineers, App Developers, AI, & Data Science on Medium, where people are continuing the conversation by highlighting and responding to this story.
阅读记录仅保存在当前浏览器,用于「为你」推荐。管理阅读记录
这篇内容对你有用吗?
反馈只用于改善内容筛选,不等同于收藏