Home › Developer Tools › SQL Query Builder

SQL Query Builder

Build a SELECT statement without typing it: choose a table, add joins (the ON condition is filled in from your foreign keys), pick columns and aggregates, add WHERE and HAVING filters, sort and limit. The tool writes clean, formatted SQL for MySQL, PostgreSQL, SQLite or SQL Server and explains anything that would fail.

Last updated:

Your tables

FROM

SELECT columns

WHERE (filter rows)

GROUP BY & HAVING

ORDER BY & LIMIT

Your SQL

Advertisement
Advertisement

How to use the SQL Query Builder

  1. Check your tables: open Your tables and paste CREATE TABLE statements, or keep the sample online-store schema.
  2. Pick the FROM table and add joins. The tool suggests a related table and fills in the ON columns from foreign keys; adjust them if needed.
  3. Choose the columns to return, with an optional function such as COUNT or SUM and an alias.
  4. Add filters: WHERE conditions filter rows, HAVING conditions filter groups after aggregation.
  5. Sort and limit, choose your database, then copy or download the SQL.

Anatomy of a SELECT query

The sample query built on load answers a real question: which customers in the US and Canada placed at least two orders, and how much did they spend?

ClauseIn the examplePurpose
SELECTc.id, c.full_name, COUNT(o.id) AS order_count, SUM(o.total) AS total_spentColumns and calculated values to return
FROM / JOINcustomers AS c LEFT JOIN orders AS o ON o.customer_id = c.idWhere the rows come from and how tables match
WHEREc.country IN ('US', 'CA')Filter individual rows
GROUP BYc.id, c.full_nameOne output row per customer
HAVINGCOUNT(o.id) >= 2Filter groups using aggregates
ORDER BYtotal_spent DESCSort the result, here by an alias
LIMITLIMIT 10Return only the first rows

Join types

JoinReturnsTypical use
INNER JOINOnly rows matched in both tablesOrders with their customer
LEFT JOINAll left rows, NULLs where the right side has no matchAll customers, including those with no orders
RIGHT JOINAll right rows, NULLs where the left side has no matchRarely needed; swap the tables and use LEFT JOIN
FULL JOINAll rows from both sidesReconciling two lists (not available in MySQL)
CROSS JOINEvery combination of rowsGenerating a calendar × product grid

Tips for correct, fast queries

  • Filter a LEFT-joined table in the ON clause, not in WHERE: WHERE o.status = 'paid' removes customers without orders and silently turns the LEFT JOIN into an INNER JOIN.
  • COUNT(column) skips NULLs while COUNT(*) counts rows, so with a LEFT JOIN use COUNT(o.id) to get 0 for customers without orders.
  • Always ORDER BY when paging with LIMIT / OFFSET, otherwise rows can move between pages.
  • Index the columns used in JOIN … ON and WHERE, especially foreign keys like orders.customer_id.
  • Use parameters in application code (WHERE email = ?) instead of pasting user input into SQL.

Frequently asked questions

In what order does SQL run the clauses?

Logically a SELECT is evaluated as FROM and JOIN, then WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and finally LIMIT / OFFSET. That is why WHERE cannot use aggregates or column aliases, HAVING can use aggregates, and ORDER BY can use the aliases from SELECT.

What is the difference between WHERE and HAVING?

WHERE filters individual rows before they are grouped, so it cannot use functions like COUNT or SUM. HAVING filters the groups after GROUP BY, for example HAVING COUNT(o.id) >= 2 to keep only customers with at least two orders.

What is the difference between INNER JOIN and LEFT JOIN?

INNER JOIN returns only rows that have a match in both tables. LEFT JOIN returns every row of the left table and fills the right table's columns with NULL where there is no match, so customers without orders still appear with a count of 0.

Why does every non-aggregated column have to be in GROUP BY?

When rows are grouped, each output row stands for many input rows, so a plain column must have one value per group. Standard SQL requires it to be in GROUP BY (PostgreSQL allows columns that depend on a grouped primary key, and MySQL's ONLY_FULL_GROUP_BY mode enforces the rule). The builder adds them automatically.

How is LIMIT written in SQL Server?

SQL Server has no LIMIT. The builder uses SELECT TOP (n) for a plain limit, and ORDER BY … OFFSET n ROWS FETCH NEXT m ROWS ONLY when you also skip rows. OFFSET requires an ORDER BY clause.

How are values in filters quoted?

Numbers compared with numeric columns stay unquoted, other values become string literals with single quotes doubled for safety. IN lists are split on commas. Values like :name, ?, $1 or @param are kept as parameter placeholders, which is what you should use in application code to avoid SQL injection.

Does the builder run the query?

No. It only writes the SQL text in your browser. Run it in your database client, or try it on a CSV file with the Query CSV with SQL tool.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

SQL Formatter & BeautifierFormat, beautify or minify SQL queries for MySQL, PostgreSQL and more.SQL Create Table GeneratorDefine columns, keys, defaults and indexes; get CREATE TABLE SQL for MySQL, Postgres and more.Query CSV with SQLRun SQL on CSV, Excel, JSON and Parquet files in your browser with DuckDB. Join and export.SQLite ViewerOpen .db and .sqlite files in your browser, browse tables and run SQL queries.MongoDB Query TesterTest MongoDB find filters, projections and aggregation pipelines on sample JSON documents.QR Code GeneratorMake QR codes for links, Wi-Fi, email and more.Barcode GeneratorCreate Code 128, EAN-13, UPC-A, EAN-8, Code 39 and ITF-14 barcodes as PNG or SVG.UUID GeneratorGenerate UUID v4 and v7 / GUIDs in bulk and copy or download them.Schema Markup Generator (JSON-LD)Create JSON-LD structured data for FAQ, Product, Article and more.Htaccess & Nginx Redirect GeneratorBuild 301 redirects for .htaccess, Nginx and Netlify or Cloudflare _redirects.Fake Data GeneratorGenerate mock data as JSON, CSV or SQL.Random String GeneratorGenerate secure random strings and tokens in bulk with any length and character set.API Key GeneratorCreate secure API keys and secrets with prefixes, checksums and SHA-256 hashes for storage.MIME Type LookupFind the MIME type for any file extension, or the extensions for a MIME type, in 400+ entries.Cron Expression GeneratorBuild crontab schedules visually, read them in plain English and see the next run times.URL Slug GeneratorTurn titles into clean, SEO-friendly URL slugs: accents, stop words, separators and bulk lines.JSON Schema GeneratorTurn sample JSON into a draft 2020-12 JSON Schema with types, required fields and formats.Gitignore GeneratorBuild a .gitignore from 50+ templates for languages, frameworks, IDEs and OS, merged and deduped.License GeneratorCreate a LICENSE file for MIT, Apache, GPL, BSD, ISC, MPL or Unlicense with your name and year.ULID GeneratorGenerate sortable ULIDs and UUID v7 in bulk, monotonic option, and decode their timestamps.Htpasswd GeneratorCreate .htpasswd entries with bcrypt, APR1-MD5 or SHA-1 for Apache and Nginx basic auth.Placeholder Image GeneratorCreate placeholder images in any size, color and text as PNG, JPG, WebP, SVG or data URI.Ads.txt GeneratorCreate or validate ads.txt and app-ads.txt files: seller lines, cert IDs and variables.Docker Run to Compose ConverterConvert docker run commands to docker-compose.yml, or a compose file back to docker run.Dockerfile GeneratorGenerate a production Dockerfile and .dockerignore for Node, Python, Go or a static nginx site.HTML Boilerplate GeneratorTick the options you need and get a clean HTML5 starter template with meta, OG tags and CSS reset.JSON to Zod SchemaInfer a Zod (or Yup) schema from sample JSON with optional, nullable and z.infer types.Linux Commands Cheat SheetSearchable Linux and bash command reference with flags explained, examples and copy buttons.LLMs.txt GeneratorBuild an llms.txt file for AI crawlers: summary and link sections, import from your sitemap.Nano ID GeneratorGenerate secure Nano IDs with custom alphabet, length and count, plus a collision calculator.Nginx Config GeneratorBuild an nginx server block: static site, SPA, reverse proxy or PHP, with SSL, gzip and redirects.OpenAPI / Swagger ViewerView OpenAPI 2/3 JSON or YAML as interactive API docs with validation and an endpoint list.package.json GeneratorFill a form and get a valid, npm-ready package.json with scripts, dependencies and checks.PKCE Code Challenge GeneratorGenerate an OAuth 2.0 PKCE code_verifier and S256 code_challenge, build auth URLs, verify pairs.README GeneratorFill in a form and get a polished README.md with badges, install, usage and license, live preview.Regex GeneratorBuild regular expressions visually from blocks or presets (email, date, phone) and test them live.Commit Message GeneratorBuild Conventional Commit messages with type, scope, body, breaking change and issue refs.Database Schema DesignerDesign tables and relationships visually, then export SQL for MySQL, PostgreSQL or SQLite.OpenAPI ValidatorValidate OpenAPI 3.0/3.1 and Swagger 2.0 specs: schema errors, broken $refs, line numbers.Pivot Table MakerBuild pivot tables from CSV or Excel by drag and drop: sum, count, average, charts, export.Truth Table GeneratorType a logic expression and get its full truth table, minterms and canonical DNF/CNF.TypeScript PlaygroundWrite TypeScript with live type checking, see the compiled JavaScript and run it in your browser.Article Schema GeneratorCreate Article, BlogPosting or NewsArticle JSON-LD with headline, authors, dates and images.Event Schema GeneratorCreate Event JSON-LD with dates, venue or online location, tickets, organizer and performers.Google Search Query BuilderBuild advanced Google searches with site:, filetype:, intitle:, exact phrases and date operators.HowTo Schema GeneratorCreate HowTo JSON-LD with steps, tools, supplies, total time and cost, then copy it.Htaccess GeneratorBuild an Apache .htaccess file: HTTPS, www, gzip, caching, error pages, IP blocks, hotlinks.HTML Email Template BuilderDrag and drop blocks to build a responsive, table-based HTML email with inline styles.Organization Schema GeneratorCreate Organization JSON-LD with logo, URL, contact points, address and social profiles.PIN GeneratorGenerate random 4, 6 or 8-digit PINs that avoid sequences, repeats, dates and common PINs.Product Schema GeneratorBuild Product JSON-LD with price, availability, brand, GTIN, ratings and reviews.Question Keyword GeneratorFind the questions people ask about a topic, grouped by who, what, why, how, can and more.Recipe Schema GeneratorCreate Recipe JSON-LD with ingredients, steps, prep and cook times, nutrition and ratings.Security Headers GeneratorPick HSTS, CSP, frame, referrer and permissions options and get Apache, Nginx, Netlify or Cloudflare config.SKU GeneratorBuild consistent SKUs from brand, category, size and color, then export every variant as CSV.Typography Scale GeneratorBuild a modular type scale from a base size and ratio, then copy CSS variables or a Tailwind config.WordPress Salt GeneratorGenerate fresh WordPress security keys and salts for wp-config.php, .env or Docker in one click.ANSI Color Code GeneratorStyle terminal text with 16, 256 or RGB colors and get escape codes for bash, Python, JS and C.Apache Virtual Host GeneratorCreate an Apache VirtualHost config with SSL, redirects, reverse proxy or PHP-FPM in seconds.Bash Prompt GeneratorDrag and drop a custom PS1 prompt for bash or zsh with colors, git branch and a live preview.Changelog GeneratorTurn Conventional Commit messages into a grouped Keep a Changelog Markdown file per version.cURL Command BuilderBuild curl commands from a form: method, headers, query, JSON or form body, auth and flags.Docker Compose to KubernetesConvert docker-compose.yml into Kubernetes Deployment, Service, ConfigMap and PVC manifests.Docker Compose ValidatorCheck a docker-compose.yml for YAML errors, schema mistakes, broken references and deprecated keys.Dockerfile LinterLint a Dockerfile for best practices: pinned tags, apt cleanup, non-root USER and layer count.Dockerignore GeneratorBuild a .dockerignore from Node, Python, Go and Java templates, plus your own entries.ESLint Config GeneratorGenerate a flat eslint.config.js for JavaScript, TypeScript, React or Node with rule presets.Git Branch Name GeneratorTurn a ticket ID and title into a clean, valid git branch name like feature/PROJ-12-add-login.
See all 85 Code Generators & Builders →