SQL
From a first SELECT and the relational model to execution plans, dialects and database testing, SQL as told through the free samples of the Leanpub books about the language and the databases that speak it.
Created from the free samples of 17 Leanpub books and the descriptions and tables of contents of 12 more, with every source cited.
SQL is the language in which relational databases are queried and changed. A statement describes the rows that are wanted, and the database decides how to find them. One of the sources shows the whole idea in a first example of a few lines, a query that joins customers to their orders, groups the result by customer, totals each group and sorts from the highest spender down, and it counts six separate concepts of the language in that one statement.[1] The language is declarative: the same source describes it as saying what is wanted and leaving the database to work out how to deliver it efficiently.[1]
The language is more than fifty years old and has widened its reach instead of losing it. Document stores, key-value stores, graph databases and columnar analytical engines have all appeared since, and yet the large cloud warehouses use SQL as their main interface and many non-relational systems now offer a language that resembles it, because developers expect one.[1] There is an international standard, and every major database departs from it in its own way, so that a working knowledge of SQL is in practice knowledge of the standard core and of one or two dialects.[1]
This article covers the history of the language, the relational model beneath it, the writing of queries, the dialects, how a database executes a statement and why some statements are slow, the administration of the main database systems, the use of SQL from application code, and the testing and review of SQL. Its sources are the free samples of 17 Leanpub books and the public descriptions and tables of contents of 12 more. Several of the samples hold front matter and a contents list only, and the article says so where a book is cited for its plan and not its text.
Where to start
A reader with no background has several starting points, and the sample of one of them is long enough to judge. The Complete SQL Guide: From Beginner to Advanced (2026) assumes little or no experience of databases and no programming, and runs in seven parts from the relational model to performance and production practice, with two sample databases used for every example.[1] SQL 101 Crash Course (2026) also asks for nothing and works up to joins, subqueries, views and stored procedures in a desktop tool for SQLite, though its sample shows only the contents and preface.[12] MySQL Explained (2016) is written for people outside information technology and gives several chapters to database design before it reaches the language,[15] and Introduction to SQL (2023) is aimed at developers and operations engineers who expect to need SQL in their work.[17]
A working developer who can already write a query has a different set of books. SQL Problem Solving (2026) has no theory chapters at all: it is eighty-four problems in seven volumes of rising difficulty, each with an input table, the expected output, a solution and a short explanation, and its sample contains the whole first volume.[4] Mastering SQL Performance Optimization (2026) expects working SQL and a database to experiment on, and can be read in order or used as a reference.[2] SQL and Database Testing: Query Your Way to Quality (2026) teaches the language from the first SELECT to testers, who need it to check what an application has really stored.[3]
The specialist is served by books that assume one system and teach another. Thinking in PostgreSQL (2025) is for engineers who already run MySQL in production and have been handed PostgreSQL,[22] The Entity Framework Core & PostgreSQL Handbook (2026) for .NET developers who use an object-relational mapper and want to see the SQL it produces,[7] and High-Performance Java Persistence (2024) for Java developers tuning data access across four database systems.[6]
History
Before relational databases, organisations kept data in flat files or in hierarchical structures. A flat file serves while there is one kind of record; once customers must be related to orders, the data is either duplicated across files or reached through custom programs that follow pointers and file offsets. Hierarchical databases arranged records as trees, in which each child record had exactly one parent, which suited an organisation chart and failed for a product with several suppliers or an employee on several projects.[1]
The relational model was proposed in 1970 in an eleven-page paper by a researcher at a large computer manufacturer. It organised data mathematically, as relations in the sense of set theory, and not by the path a program would take to reach it: data would sit in simple tables of rows and columns and be queried in a mathematical language.[1] His employer, which earned revenue from a hierarchical product, resisted the idea. The prototype query language was first called SEQUEL and later renamed SQL, and another company built a commercial database around it.[1]
The language has been an international standard since 1987, and the standard has gone through nine editions. Recursive queries arrived with the edition of 1999, window functions in 2003, temporal tables in 2011 and support for JSON in 2016. The standard defines a core that a conforming implementation must support and leaves the rest optional.[1]
The relational model
A relational database holds data in tables. A table imposes a structure on its records, each row is one record, and each column is a field of a declared type such as an integer, a date or text.[8] Tables are related through keys: a primary key is a column whose value is unique for every row, and a foreign key is a column whose values refer to the primary key of another table.[8] Three kinds of relationship follow. One-to-one joins a single record on each side, as a country to its capital; one-to-many joins a department to its many employees; many-to-many has several records on both sides.[8]
The model carries principles that have practical effects whenever a query is written. Physical storage is hidden from the user, so a query does not change when the database stores its data differently, and an index can be added to speed a query without touching the application that sends it.[1] The definition of the tables is kept apart from the programs that use them, so a column can be added without rewriting every program.[1] Missing information has its own representation, NULL, which stands for unknown or not applicable and is not the same as zero or an empty string.[1] The first volume of the problem book ends on the consequence that catches beginners: NULL cannot be compared with an equals sign, since any comparison or arithmetic involving it yields NULL and never true, and a test for it has to be written as IS NULL.[4]
A schema is a named container for related tables, views and functions. In PostgreSQL, SQL Server and Oracle one database can hold several schemas, each with its own tables, which prevents clashes of names and allows access to be granted schema by schema; in MySQL a schema has traditionally been the same thing as a database, and SQLite has no schemas at all.[1]
Two of the books are about design more than about the language. MySQL Explained works through normalisation and two complete example designs,[15] and The Oracle database in modern IT architectures (2023) gives its first part to unique identifiers, primary and unique keys, foreign keys and the kinds of relationship, and its second to rules of data integrity enforced by the database itself. Its description holds that the relational database remains the better choice in most cases despite the alternatives that have emerged. The author calls the book a work in progress, and the sample shows its plan and not its chapters.[11]
Writing queries
The beginner books teach the statements in much the same order. Introduction to SQL goes from tables and basic syntax through selecting, filtering, ordering and grouping to inserts, updates and deletes, and then to joins, subqueries and unions, on MySQL.[17] MySQL for Beginners (2020) covers similar ground in forty-nine pages, from creating a database to joins, indexes and views.[18] The Fundamentals of Database Administration (2021) was built from its author's study notes for a certification examination and introduces relational concepts, the language and SQL Server together, assuming nothing.[19]
Beyond the basics lie the techniques that the longer books treat as the mark of an advanced user: subqueries, common table expressions, recursive queries over hierarchies, set operations and window functions. A window function computes a running total, a ranking, a moving average or a comparison between one row and the next in a single query, where procedural code would otherwise be needed.[1] The problem book shows how such techniques combine. Its sample includes one expert problem, turning a long table of sales into one row per product with a column per month, and solves it by conditional aggregation: each output column is a sum over a CASE expression that keeps only the rows of its month. Some engines have a dedicated pivot operator, the explanation notes, but the conditional form is portable, and it fails only when the columns are not known in advance.[4]
Two books teach querying for a purpose. Database and sql for data science (2026) arranges the language around the work of a data scientist, with chapters on cleaning data, exploratory analysis, window functions and common table expressions, and on calling SQL from Python.[20] Mastering Business Data with SQL (2025) is for analysts of business data on SQL Server and pairs querying with the work of compliance: row-level security, data masking, pseudonymisation and audit trails.[21]
Dialects
No database implements the standard exactly. One source characterises the main systems in a paragraph: PostgreSQL follows the standard closely and adds extensions of its own, MySQL historically put speed and simplicity ahead of strict compliance, SQL Server and Oracle each have a procedural language with its own conventions, and SQLite gives up some standard features for its embedded, single-file design.[1] That book teaches standard SQL and sets the differences apart in notes of their own.[1]
A small example shows the size of the differences. A column that numbers its own rows is declared differently in each system, and the Java book's sample sets the four declarations side by side: Oracle for many years required a sequence and a trigger and later added identity columns, SQL Server offered identity columns and later added sequences, and PostgreSQL, at the version described, emulated an identity column with a serial type.[6] The versions that sample refers to are now old.
The larger differences are below the syntax. Thinking in PostgreSQL lists the changes of habit an engineer has to make in moving between two open-source systems: from threads in one server process to a process per connection, with connection pooling close to mandatory; from a table stored inside its primary key to a heap with separate indexes; and from automatic row numbering and replace statements to sequences and a conflict clause.[22] The Entity Framework Core & PostgreSQL Handbook does the same for readers arriving from SQL Server, flagging the places where their habits mislead at the point where each arises.[7]
How a database runs a query
A statement begins as text and passes through five phases before any row comes back, in the account Mastering SQL Performance Optimization gives. The parser breaks the text into tokens and builds a tree. Semantic analysis checks that every table and column exists and that the types in each comparison are compatible. A rewriting phase transforms the query into an equivalent form that is easier to optimise, for instance by pushing a filter as deep into the tree as it will go. The optimiser then chooses a plan, and the execution engine carries it out.[2] The book's premise is that tuning is not a collection of tricks: every technique either changes how a query enters this pipeline or influences a decision made along it.[2]
The optimiser is cost-based. It estimates the processor time, disk reads and memory each possible plan would need and picks the cheapest, deciding which indexes to use, the order in which to join the tables and the algorithm for each join.[2] The number of possibilities grows very fast, since a join of several tables can be ordered in as many ways as the tables can be arranged, so optimisers search with dynamic programming and heuristics instead of trying everything.[2] Their estimates rest on statistics about the data, and stale statistics produce bad plans: the book's example is a status column whose distribution has shifted since the statistics were gathered, so that the optimiser expects a few rows and receives most of the table.[2]
Two habits of query writing follow directly. Selecting every column reads more from disk than the query needs and prevents an index that holds only the wanted columns from answering it alone.[2] A comparison that forces a conversion of the column itself, and not of the value it is compared with, is where an implicit type conversion begins to cost.[2] A condition written so that an index can serve it is called sargable, a subject both the long tutorial and the expert volume of the problem book list among their contents.[1][4]
The classic execution engine works one row at a time. Each operator in the plan asks the operator beneath it for the next row, so that rows flow upward as soon as they are available; a sort must see all its input before it can return anything, and a limit can stop the work early.[2] Pages read from disk are kept in a buffer pool, so that a second request for the same page costs no disk read.[2] Build a SQL Database Engine in C++ (2026) has the reader construct these parts in C++, from pages and a B+tree index through a buffer pool to a tokenizer, a parser and an executor that runs three kinds of statement, and prints a benchmark for each claim about performance.[23]
Analytical engines
The row-at-a-time model has an overhead that matters when a query reads millions of rows: every operator is called once per row. The DuckDB Handbook (2026) describes the alternative its subject uses. DuckDB passes fixed batches of about two thousand values between operators, so a filter over a million rows is evaluated a few hundred times and not a million, and each evaluation can use processor instructions that work on several values at once.[5] It stores each column separately, so a query that averages one column of twenty reads that column alone, and values of one column compress well because they resemble each other.[5] Minimum and maximum values kept for each segment of a column let a filter skip segments that cannot match.[5]
The design has a price, which the book states: columnar storage is less efficient for fetching or inserting single rows, and the system is not a replacement for a transactional database such as PostgreSQL or MySQL.[5] The SQL is the same language, and the book's central chapters cover joins, aggregations, window functions and common table expressions.[5]
Database systems and their administration
Three of the sources are books of recipes or practices for one system. PostgreSQL 15 Cookbook (2026) holds about a hundred recipes in thirteen chapters for administering and troubleshooting PostgreSQL 15, with chapters of their own on provisioning in the cloud and on migrating into the system.[13] MySQL 8 Cookbook (2026) covers MySQL 8 on Linux in nine chapters: configuration, storage engines, security, query optimisation, replication, high availability, maintenance, troubleshooting and monitoring.[14] The samples of both contain the contents and front matter and no recipe.
Thinking in PostgreSQL treats operation as a change of mental model. Its four parts cover how PostgreSQL lays data out and why tables bloat, how to read its locks and design its indexes, monitoring and replication through the built-in statistics views, and the configuration settings and surprises that matter most to an engineer from MySQL; in place of a slow query log it teaches the reader to ask the database for a plan with the measured timings and buffer use attached.[22]
For Oracle, How to build an Oracle database application (2023) is about the tools and process around a database application and not about the language. Its author deploys with an open-source migration tool on the reasoning that it rests on one simple idea, running migration scripts automatically and recording in a history table what has been installed, and advises never running such scripts by hand again.[10] Database tuning also appears as one tier among several in The Art Of Performance Engineering (2021), a short guide to finding bottlenecks across the client, the web server, the application server and the database.[24]
SQL from application code
Most SQL is sent by programs. High-Performance Java Persistence is about the cost of that traffic, and its sample is on batching. Sending statements one at a time costs a round trip to the database for each; grouping them into batches reduces the round trips, and even a small batch shortens response time. The gain does not grow in proportion to the batch size, a very large batch can hurt, and the author's advice is to measure, there being no formula for the right size.[6] Drivers differ as well: the MySQL driver for Java does not by default send a batch in a single request, and a connection property has to be set before it will.[6]
An object-relational mapper writes the SQL on the programmer's behalf, and The Entity Framework Core & PostgreSQL Handbook starts from what that hides: which statement a query became, and why the same code is fast against one table and slow against the next. It is a book of twenty-one chapters on one mapper and PostgreSQL, and it is not an introduction to either.[7]
Many of the books under this topic are project books in which a database is the storage layer of one application. PHP & MYSQL : Course and corrected exercises (2025) is a beginner's course in PHP that reaches MySQL after forms, files and sessions,[25] and PHP & MYSQL: 200 Solved Exercises and Projects for Practice (2025), by the same author, is a workbook of two hundred solved exercises.[26] Mastering Ionic: Working with PHP & MySQL (2024) connects a mobile front end to a PHP and MySQL back end and says plainly that it is not an in-depth guide to the database.[8] Two project books by one author build desktop applications, a student-management program in Java over MySQL and a customer-management program in Python over SQLite.[27][28] Full-Stack Data Engineering with Node.js (2024) collects short recipes for reaching the main database systems from Node.js on the way to a reporting stack.[29]
One rule recurs wherever SQL is assembled in code: values are passed as parameters and never pasted into the text of the statement. The testing book applies it even to test code, on the grounds that a surname with an apostrophe breaks an interpolated query and that the habit, once copied into production code, is an injection vulnerability.[3]
Testing and reviewing SQL
SQL and Database Testing: Query Your Way to Quality uses the language as an instrument of verification. A response from an application is not proof that anything was stored, so after an operation that changes state the tester queries the database directly and checks that the row exists, that defaults were applied and that the timestamps are sane.[3] The book's characteristic query is written to return rows only when something is wrong: line items whose order does not exist, found with an outer join and a test for NULL; email addresses that occur more than once, found by grouping and counting; required fields left empty.[3] It also gives a tester's reason for naming columns instead of selecting them all, which is that a test reading results by position breaks when a migration adds a column.[3]
Database testing practical tips (2021) is a shorter guide for manual testers moving into automation. It divides database testing into structural testing of the elements that store data, functional testing of the operations users perform, and non-functional testing such as load and stress, and then compares Java libraries for reaching a database from test code.[9]
SQL Code Review Mastery (2025) organises practice around what a reviewer checks. Its contents list nine principles, among them consistent naming and formatting, small and focused procedures, explicit schemas and column names, set-based operations in preference to loops, protection against injection, least privilege, and tests before deployment.[16] It is forty pages long and its sample yielded no text, so it is cited here from its contents alone.
Questions about SQL
Which SQL book should I start with?
The Complete SQL Guide: From Beginner to Advanced assumes no experience of databases and its sample includes the history, a first query and the start of the chapter on the relational model.[1] A reader who already writes basic queries and wants practice can take the twelve problems in the sample of SQL Problem Solving.[4]
Is SQL the same in MySQL, PostgreSQL, SQL Server and Oracle?
Why is SELECT * discouraged?
Why can't NULL be compared with an equals sign?
Why is my SQL query slow?
The database's optimiser chooses a plan from statistics about the data, and when those statistics are stale it can choose a plan suited to a few rows for a query that returns most of a table.[2] Selecting unneeded columns and forcing a type conversion on a column are two common causes in the query itself.[2]
How do I pivot rows into columns in SQL?
Sources
Every source is a Leanpub book or course. The note after each says which part of it was read; where no sample was available, only the public description and table of contents were used.
- 1.The Complete SQL Guide: From Beginner to Advanced, Steve Publications: Master Structured Query Language for Database Development, Data Analysis, and Performance Engineering Free sample: the introduction (history, the plan of the seven parts, the standard and its dialects, a first query) and the opening of chapter 1 on the relational model and schemas. 2026. Free sample: PDF · EPUB
- 2.Mastering SQL Performance Optimization, Steve Publications: From Query Fundamentals to Production-Grade Tuning Across Database Platforms Free sample: the introduction and chapter 1 on the phases of query processing, the optimiser, statistics and the execution engine. 2026. Free sample: PDF · EPUB
- 3.SQL and Database Testing: Query Your Way to Quality, Yuri Syuganov: From First SELECT to Schema Migrations, NoSQL, and GDPR Compliance Free sample: the introduction, chapter 1 on SELECT as a verification tool, with exercises, and the start of chapter 2. 2026. Free sample: PDF
- 4.SQL Problem Solving, Hatem M.: A Hands-On Workbook with 84 Real SQL Challenges Free sample: the twelve problems of the first volume and one problem from the sixth. 2026. Free sample: PDF
- 5.The DuckDB Handbook, Steve Publications: A Comprehensive Guide to In-Memory Analytical Processing Free sample: the introduction and the part of chapter 1 on vectorised execution and columnar storage. 2026. Free sample: PDF · EPUB
- 6.High-Performance Java Persistence, Vlad Mihalcea: Get the most out of your persistence layer Free sample: sections on batching statements and on identity columns and sequences in four database systems. 2024. Free sample: PDF · EPUB
- 7.The Entity Framework Core & PostgreSQL Handbook, Rachid DAHIR: Mastering EF Core 10 with PostgreSQL 18 for Production-Grade Applications Free sample: the preface and introduction, on who the book is for and how it is organised. 2026. Free sample: PDF
- 8.Mastering Ionic: Working with PHP & MySQL, James Griffiths Free sample: the introduction, a glossary and the start of a summary of database concepts. The sample carries a 2017 copyright; last published 2024. Free sample: PDF
- 9.Database testing practical tips, Anton Smirnov: Database testing: A practical guide to applying manual and automatic database testing skills. Free sample: the introduction, chapter 1 on the kinds of database testing and the start of chapter 2. 2021. Free sample: PDF
- 10.How to build an Oracle database application, Gert-Jan Paulissen: Quick but not dirty; with or without a front-end built with Oracle APEX or a Node.js framework like React, Angular or Vue. Free sample: the foreword, preface and introduction, with the author's reasons for his choice of tools. 2023. Free sample: PDF · EPUB
- 11.The Oracle database in modern IT architectures, Peter de Vaal: Intelligent Persistence for applications, microservices, business processes, data analytics, documents and more Free sample: the preface and the headings of the chapters, whose content is withheld; cited from those and the description. 2023. Free sample: PDF · EPUB
- 12.SQL 101 Crash Course, GitforGits | Asian Publishing House: Comprehensive Guide to SQL Fundamentals and Practical Applications Free sample: the table of contents, preface and prologue, with no teaching text. First printed 2023; last published 2026. Free sample: PDF
- 13.PostgreSQL 15 Cookbook, GitforGits | Asian Publishing House: 100+ expert solutions across scalability, performance optimization, essential commands, cloud provisioning, backup, and recovery Free sample: the table of contents and preface, with no recipe text. 2026. Free sample: PDF
- 14.MySQL 8 Cookbook, GitforGits | Asian Publishing House: Ready solutions to achieve highest levels of enterprise database scalability, security, reliability, and uptime Free sample: a prologue and the table of contents, with no recipe text. 2026. Free sample: PDF
- 15.MySQL Explained, OSTraining, Andrew Comeau: Your step-by-step guide to database design The sample yielded no text: from the description and table of contents. 2016. Free sample: PDF
- 16.SQL Code Review Mastery, Luis Martin Espino Rivera: Write Clean, Secure, High-Performance SQL That Passes Every Review The sample yielded no text: from the description and table of contents. 2025. Free sample: PDF
- 17.Introduction to SQL, Bobby Iliev: For Developers No sample: from the description and table of contents. 2023.
- 18.
- 19.The Fundamentals of Database Administration, Sean Dunn No sample: from the description and table of contents. 2021.
- 20.Database and sql for data science, Anshuman Mishra No sample: from the description and table of contents. 2026.
- 21.Mastering Business Data with SQL, Agus Kurniawan: A Practical Guide to Querying, Modeling, and Compliance Using SQL Server 2025 No sample: from the description only. 2025.
- 22.Thinking in PostgreSQL, Nick Vyzas: A field guide to PostgreSQL for MySQL engineers No sample: from the description only. 2025.
- 23.Build a SQL Database Engine in C++, Hatem M.: Through Challenges --- Storage, Query Processing, Joins, Indexes, Vectorized Execution, and Crash Recovery (Complete, Units 1-14) No sample: from the description, which lists the eight units. 2026. Free sample: PDF
- 24.The Art Of Performance Engineering, Vineeta Vashistha & Amit Vashistha: Learn Performance Optimization techniques to ensure high performance of your application. No sample: from the description and table of contents. 2021.
- 25.PHP & MYSQL : Course and corrected exercises, Maximilien Lambert: Master dynamic web development Free sample: front matter and the opening on how websites work and on installing a local environment; cited for the book's plan. 2025. Free sample: EPUB
- 26.PHP & MYSQL: 200 Solved Exercises and Projects for Practice, Maximilien Lambert: Master dynamic web development Free sample: front matter, contents and preface only. 2025. Free sample: EPUB
- 27.Java GUI Programming with MySQL: Build Real Student management App Step by Step - CERTIFICATE INCLUDED, Roberto Stepic: A Hands-On Project-Based Guide to Java, Swing, JDBC, and MySQL Integration for Beginners No sample: from the description only. 2025.
- 28.Building Customer Management Apps with Python & Tkinter, Roberto Stepic: Design, Build, and Ship a Real-World Desktop Application Using Tkinter, ttkbootstrap, and SQLite No sample: from the description only. 2026.
- 29.Full-Stack Data Engineering with Node.js, Kevin Languedoc: How to build a Data Engineering and Business Intelligence Stack using Node.js and Npm modules Free sample: short recipes for connecting to database systems and data services from Node.js. 2024. Free sample: PDF
Further reading
Other books in the library on the same ground, not cited above.
- Embedded Graph Databases, Steve Publications: Building the SQLite of Graph Data Building a single-file graph database engine in Rust, with an account of why relational tables suit graph traversal poorly. 2026. Free sample: PDF · EPUB
- Data Warehousing Concepts For Data Professionals, Kavinda Sandaruwan Rajapaksha A nine-page summary of data warehousing, from dimensional modelling to slowly changing dimensions. 2026.
- Spark 4.0 from Scratch, Ritesh Modi: Foundations: From Your First DataFrame to Production-Ready Joins and Aggregations PySpark from a first session to joins and aggregations, with a chapter on Spark SQL. 2026.
- DATABRICKS FOR PRACTITIONERS: Volume 1, Ritesh Modi: The Production Lakehouse Playbook: Platform, Governance, and Data Engineering Running one lakehouse platform in production, where SQL appears through query plans, system tables and clustering. 2026.
- Medior PHP - The Missing Step, Joseph Kanyo Building a server-rendered PHP application piece by piece, with one chapter on a MySQL persistence layer. 2025. Free sample: PDF · EPUB
- Building a Data Driven Chatbot (RAG) using Python 3 LangChain, OpenAI and MySQL 8.x, Binit Datta: Using GenAI LangChain to Solve Real World Use Cases A chatbot in Python that works against order data held in a MySQL 8 database. 2025. Free sample: PDF
- MB-820 Exam Cram: Tables and Table Extensions in Business Central, Silviu Virlan Tables, keys and indexes in one business application platform, as preparation for a certification examination. 2026.
- Power BI Report Server Architecture, Components and Basics, Dr. Vishal Pawar, Ph.D. Installing and adopting an on-premises reporting server that sits beside SQL Server. 2022.
