SQL
How SQL queries stored data in relational databases to select, filter, join, group and summarize records, and how tables are designed so research data stay consistent and shareable.
What it is
SQL (Structured Query Language, pronounced “sequel” or “S-Q-L”) is the standard language for working with relational databases. Data are stored in tables of rows and columns, and SQL describes what data you want, not how to find it: the database engine plans the search. It was developed at IBM in the 1970s based on Edgar Codd’s relational model and is standardized (ISO/IEC 9075). Common systems are PostgreSQL, MySQL/MariaDB, SQLite (a single-file database built into many applications and Python), Microsoft SQL Server and Oracle, plus cloud warehouses such as BigQuery. Researchers use SQL to manage experimental and survey data, query biological and public databases, analyze large records and prepare data for statistics and machine learning.
It answers questions such as: Which samples meet these conditions? What is the average measurement per group and per month? How do I link measurements to sample, instrument and operator records without duplicating information? How do I keep a large shared dataset consistent as several people add to it? SQL handles datasets much larger than a spreadsheet can and enforces rules that protect data quality.
Fundamentals
Tables, keys and relationships
A relational database splits data into tables, one for each kind of entity (samples, experiments, instruments), with each row a record and each column an attribute with a data type (INTEGER, REAL, TEXT/VARCHAR, DATE, TIMESTAMP, BOOLEAN). A primary key uniquely identifies each row (such as sample_id), and a foreign key in another table refers to it, creating a relationship (each measurement row stores the sample_id it belongs to). Relationships are one-to-many (one sample, many measurements) or many-to-many (via a linking table). Constraints keep data valid: NOT NULL, UNIQUE, CHECK (ph BETWEEN 0 AND 14) and foreign-key constraints, which prevent measurements that point to a non-existent sample. NULL represents a missing or unknown value and behaves specially: NULL = NULL is not true, so use IS NULL.
Querying with SELECT
The main statement is SELECT, with clauses written in a fixed order but processed logically as FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT:
SELECT group_id, AVG(value) AS mean_value, COUNT(*) AS n FROM measurements WHERE date >= '2026-01-01' GROUP BY group_id HAVING COUNT(*) >= 5 ORDER BY mean_value DESC LIMIT 10;
WHERE filters rows before grouping using =, <>, <, BETWEEN, IN, LIKE (pattern matching with %), AND, OR and NOT; HAVING filters groups after aggregation. Aggregate functions are COUNT, SUM, AVG, MIN, MAX (and STDDEV in most systems); aggregates ignore NULLs, except COUNT(*). DISTINCT removes duplicates, CASE WHEN ... THEN ... END gives conditional values, and functions handle text, dates and numbers. ORDER BY sorts; without it, the order of rows is not guaranteed.
Joins, subqueries and window functions
Joins combine tables by matching keys: INNER JOIN keeps only rows with matches in both tables, LEFT JOIN keeps all rows of the left table (with NULLs where nothing matches), and RIGHT and FULL OUTER JOIN are the other variants. Example: SELECT s.name, m.value FROM samples s JOIN measurements m ON m.sample_id = s.sample_id;. A forgotten or wrong join condition produces a Cartesian product with an explosion of rows, and one-to-many joins duplicate the “one” side’s values, which distorts sums unless handled. Subqueries nest a query inside another, and common table expressions (WITH recent AS (SELECT ...) SELECT ...) make complex queries readable. Window functions compute across related rows without collapsing them: AVG(value) OVER (PARTITION BY group_id ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) gives a moving average, and ROW_NUMBER(), RANK(), LAG() and LEAD() support ranking and time comparisons.
Changing data and designing the schema
CREATE TABLE defines a table, and INSERT, UPDATE and DELETE change rows; UPDATE and DELETE without a WHERE clause affect every row, a classic accident. Transactions (BEGIN, COMMIT, ROLLBACK) group changes so they succeed or fail together, following the ACID properties (atomicity, consistency, isolation, durability). Good design applies normalization: store each fact once (first, second and third normal forms), so that updates do not create inconsistencies, while denormalized tables are sometimes used in analytics for speed. Indexes (CREATE INDEX) speed up searches and joins on columns used in WHERE and JOIN, at the cost of storage and slower writes; EXPLAIN shows the query plan. Record units and metadata and document the schema in a data dictionary (see FAIR research data management).
Working with SQL in analysis
SQL is used from many tools: command-line clients (psql, sqlite3), graphical tools (DBeaver, pgAdmin, DB Browser for SQLite) and programming languages: Python (sqlite3, SQLAlchemy, pandas.read_sql), R (DBI, dbplyr, which translates dplyr code into SQL) and others. Always use parameterized queries (placeholders) when a program inserts values, to prevent SQL injection, where malicious text changes the query. Large analyses often do heavy filtering and aggregation in the database and move only results into Python or R.
Typical applications and limits
Used for laboratory information management, clinical and survey databases, bioinformatics resources, sensor and log data, and as a back end for web applications. Limits include rigid schemas for rapidly changing data, difficulty with highly connected graph data or very large unstructured data, performance problems for badly written queries and the need for design skill before data entry begins.
Basic operation
- Choose a database system. Use SQLite for single-user projects or PostgreSQL/MySQL for shared access.
- Design the tables. Define entities, primary and foreign keys, data types and constraints.
- Load the data. Import CSV files or use
INSERT, checking for errors and duplicates. - Write a query. Start with
SELECT ... FROM ... WHEREand inspect a few rows withLIMIT. - Join and aggregate. Combine tables and summarize with
GROUP BYand aggregate functions. - Check the results. Verify row counts, NULL handling and join duplicates against known values.
- Export or connect. Save results to CSV or read them directly into Python or R.
- Collect the output. You obtain query results and a documented database; indexing and query optimization are covered in the video.
Good practice
- Back up before changing data. Test
UPDATEandDELETEwithSELECTfirst. - Use constraints and keys. Let the database enforce valid data.
- Name things clearly. Use consistent table and column names and write comments.
- Check joins. Compare row counts before and after.
- Use transactions. Group related changes.
- Protect data. Use parameterized queries, limited user permissions and encryption for sensitive records, and follow privacy rules for personal or clinical data.
Key terms
- Primary key / foreign key — a unique row identifier, and a column referring to another table’s key.
- Join — an operation that combines rows from tables by matching columns.
- Aggregate function — a function that summarizes many rows, such as
AVGorCOUNT. - Normalization — organizing tables to avoid duplicated data and inconsistencies.
- Index — a structure that speeds up searches on columns.
- Transaction — a group of operations treated as one unit that succeeds or fails together.
- SQL injection — an attack where input text alters a query’s meaning.
Video coming soon
About five minutes on SQL: how it works in detail, how the data is acquired, and how it is analyzed.
More in 4.1 Languages and Environments
