SQL querying
SQL lets you ask your layers questions in plain database language, right in your browser. Each layer on your map becomes a table, and CartaTerra runs your query with DuckDB inside your browser, so your layers stay on your device while it runs. SQL opens from the side rail into the bottom dock. It is part of Pro (see plans).
Open SQL
- Sign in with Pro and open your own map.
- Add the layers you want to query. Put them on your map first, from Add layer or with Upload.
- Press SQL on the side rail, in the data tools section. If you've hidden it under + › Show on rail, turn it back on there. It opens as a bottom-dock tab. Press SQL again while that tab is showing to close it.
The SQL window has your layers and their fields as buttons, a box for your query and a Run button. The results show as a table under the box. The first run loads the query engine ("Loading the query engine…"), which can take a moment.
The chips around the box
- Layers: one button per layer, over the box. Tap one to put its table name in your query at the cursor. It also picks that layer (it's highlighted) for the rows below.
- Fields: the picked layer's columns. Tap one to put the column name in your query at the cursor (in double quotes if it needs them). The field you tap last is used by Count by and Top 10.
- Functions: under the box, whole queries for the picked layer: First 10 rows, Area, Length, Distance, Inside, Count by and Top 10. Only the ones that fit the layer show: Area for areas, Length for lines, Inside when another area layer is open, Count by when there's a text field, Top 10 when there's a number field. A chip replaces what's in the box with a query that's ready to go. Nothing runs until you press Run.
See our how-to on SQL querying under the box opens this page.
Tables and columns
Table names. Each table is named after its layer, in lowercase, with every run of spaces and symbols turned into one underscore. Accents are dropped.
- "Hospitals" is hospitals
- "States (Census)" is states_census
- "Mississippi Locks & Dams" is mississippi_locks_dams
- "National Park Service Sites" is national_park_service_sites
A name that would start with a number gets layer_ in front, and two layers with the same name become name and name_2. A name that's also an SQL word gets an underscore at the end. The Layers chip always inserts the exact name, so you don't have to work it out.
Columns. Each field in a layer is a column, named the same way: "notable people" becomes notable_people. Every table also has a last column, geom, which holds the shape of each row: a point, line or area, in longitude and latitude. Numbers, text, true or false and dates come through as those types.
Which layers. Layers from Add from a link (live map services) aren't tables. Very large built-in layers that the map draws in tiles appear as tables with no rows, and they don't get a Layers chip. Your own, uploaded and analysis layers, and built-in layers that load in full, have all their rows.
What you can run. One SELECT at a time. A query can also start with WITH for a named step. You can use WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, JOIN, CASE, text tools such as ILIKE and regexp_extract, and math. Queries that change data or read files are refused.
Worked examples
These use built-in layers. Add them to your map first, then paste a query and press Run.
1. Filter rows (WHERE). Level I trauma centers in Colorado, from Hospitals:
SELECT name, city, beds, trauma FROM hospitals WHERE state = 'CO' AND trauma = 'Level I'
Text goes in single quotes and has to match exactly. For a loose match, use ILIKE with % around the words: WHERE name ILIKE '%children%'.
2. Count by a field (GROUP BY). Power plants by type:
SELECT type, COUNT(*) AS plants FROM power_plants GROUP BY type ORDER BY plants DESC
3. Sort and take the top 10 (ORDER BY, LIMIT). The highest SNOTEL snow stations:
SELECT name, state, elevation_ft FROM snotel_snow_stations ORDER BY elevation_ft DESC LIMIT 10
4. Math on columns. Lock chamber size in square feet, and lift in meters, from Mississippi Locks & Dams:
SELECT name, town, state, main_chamber_length_ft * main_chamber_width_ft AS chamber_sq_ft, ROUND(lift_ft / 3.281, 1) AS lift_m FROM mississippi_locks_dams ORDER BY chamber_sq_ft DESC LIMIT 10
5. Join two layers by a field. Hospitals per state, with the state's full name from States (Census). Hospitals stores the two-letter code, and States (Census) has it as postal_code:
SELECT s.name AS state_name, COUNT(*) AS hospitals, ROUND(AVG(h.beds)) AS avg_beds FROM hospitals h JOIN states_census s ON h.state = s.postal_code GROUP BY s.name ORDER BY hospitals DESC
The short names after each table (h and s) save typing. Use them in front of any column both tables share, like name.
6. Join two layers by location (points inside areas). SNOTEL stations inside national park units, highest first:
SELECT n.name AS park, s.name AS station, s.elevation_ft, s.geom FROM snotel_snow_stations s JOIN national_park_service_sites n ON ST_Within(s.geom, n.geom) ORDER BY s.elevation_ft DESC
Because it keeps s.geom, you can save the result as a layer of just those stations.
7. Count points in each area, and map it. Superfund sites per state, with each state's shape kept so the result can go on the map:
SELECT st.name AS state_name, COUNT(*) AS sites, st.geom FROM states_census st JOIN superfund_sites_npl f ON ST_Within(f.geom, st.geom) GROUP BY st.name, st.geom ORDER BY sites DESC
Save it as a layer, then use Style to color the states by sites.
Area, length, distance and inside
With geom you can measure shapes and compare places. The Functions chips use these same functions on the layer you picked (Distance there measures to the nearest row of another open layer, or to the first row's point, which you can change):
- Area in square miles. The largest park units:
SELECT name, ROUND(ST_Area_Spheroid(ST_FlipCoordinates(geom)) / 2589988, 1) AS sq_mi FROM national_park_service_sites ORDER BY sq_mi DESC LIMIT 10 - Length in miles. The longest 2005 hurricane tracks:
SELECT name, ROUND(ST_Length_Spheroid(ST_FlipCoordinates(geom)) / 1609.344) AS miles FROM hurricane_tracks_north_atlantic WHERE season = 2005 ORDER BY miles DESC LIMIT 10 - Distance in miles from a point. Hospitals within 10 miles of downtown Denver:
SELECT name, city, ROUND(ST_Distance_Sphere(ST_FlipCoordinates(geom), ST_Point(39.7392, -104.9903)) / 1609.344, 1) AS miles, geom FROM hospitals WHERE ST_Distance_Sphere(ST_FlipCoordinates(geom), ST_Point(39.7392, -104.9903)) < 16093 ORDER BY miles - Inside: rows of one layer that fall inside another, as in examples 6 and 7. For lines that cross an area, use ST_Intersects. Hurricane tracks that crossed Florida since 2000:
SELECT h.name, h.season, h.peak_wind, h.geom FROM hurricane_tracks_north_atlantic h JOIN states_census s ON ST_Intersects(h.geom, s.geom) WHERE s.name = 'Florida' AND h.season >= 2000 ORDER BY h.season DESC
Two things to know:
- Latitude first for measuring. The area, length and distance functions read coordinates latitude first, while your layers store longitude first. That's why the templates wrap geom in ST_FlipCoordinates, and why ST_Point takes latitude, then longitude. Leave the flip out and you get wrong numbers or blanks.
- Meters underneath. These functions measure in meters (square meters for area). Divide by 1609.344 for miles, 2589988 for square miles, 1000 for kilometers or 1000000 for square kilometers.
ST_Centroid turns an area into its center point: SELECT name, ST_Centroid(geom) AS geom FROM national_park_service_sites gives a point for each park unit.
Save and export results
- The results table shows up to the first 200 rows. On Free and Basic a query returns up to 5,000 rows, and the window says when it stopped there. Pro does not stop at a row count. A result with very large shapes can stop sooner, so the layer stays a size the map can hold. A query that runs longer than 25 seconds is stopped.
- Save as layer appears under the results when they include a shape, such as geom or a shape you made with a function. It adds a new layer called Query result to your map, opens it as a tab in Tables and zooms to it.
- No shape, no layer. A count or average without a shape column can't be saved. To map one, keep the area's geom in the query, as in example 7.
- Export. Once it's a layer, use Export… at the top of Tables, or Export map… in the map menu under your map's name, to save it as Shapefile, GeoPackage, CSV, Excel, KML/KMZ, GeoJSON or GPX.
- Pro. Saving a result is part of Pro. On another plan, the save is refused with "SQL is a Pro feature."
Common errors
- "Only a single SELECT is allowed." The query doesn't start with SELECT or WITH, has two statements, or uses a word that changes data or reads files (CREATE, INSERT, UPDATE, DELETE, DROP, COPY, read_csv and the like). A typo in SELECT shows this too. Remove the extra parts, or fix the spelling. A column whose name is an SQL word (like comment or update) works in double quotes:
"comment". - "That query names a table that isn't one of your layers." Check the table name, or tap its Layers chip to insert it. If the layer isn't on your map yet, add it, then open SQL again.
- "That query didn't run. Check it and try again. DuckDB says: …" The query engine's own words follow, for example a misspelled function, a missing comma or quote, or text compared to a number. Use the Fields chips for exact column names.
- "That query returned no rows." It ran, but nothing matched. Check spelling and capitals inside quotes, or loosen the filter with ILIKE. A layer the map draws in tiles has no rows to return.
- "That query took too long and was stopped." Add a WHERE or a LIMIT, or join fewer rows.
- "Spatial functions aren't available right now. You can still query the columns." The spatial part of the engine didn't load. Run the query again later. Queries without ST_ functions still work.
- "Couldn't load the query engine. Check your connection and try again." The engine downloads the first time you press Run. Check your connection and run again.
- "SQL opens from the rail or the bottom dock." Press SQL on the rail. "SQL works on your own map." You're viewing a map you can't edit. Open one of your own maps.
Related: Data tools on the map · Upload and export map files · What's in this area? · All guides