{"url": "https://use-the-index-luke.com/", "titulek": "SQL Indexing and Tuning e-Book for developers: Use The Index, Luke covers Oracle, MySQL, PostgreSQL, SQL Server, ...", "h1": "SQL Indexing and Tuning e-Book", "popis": "SQL indexing and tuning tutorial for developers. No unnecessary database details—just what developers need to know. Covers all major SQL databases.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/", "jazyk": "en", "robots_meta": "", "og": {"og:title": "SQL Indexing and Tuning e-Book for developers: Use The Index, Luke covers Oracle, MySQL, PostgreSQL, SQL Server, ...", "og:description": "SQL indexing and tuning tutorial for developers. No unnecessary database details—just what developers need to know. Covers all major SQL databases.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "SQL Indexing and Tuning e-Book"}, {"uroven": 2, "text": "SQL Indexing in MySQL, Oracle, SQL Server, etc."}, {"uroven": 2, "text": "Table of Contents"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# SQL Indexing and Tuning e-Book\n\n---\n\nA site explaining SQL indexing to developers—no crap about administration.\n\nSQL indexing is the most effective tuning method—yet it is often neglected during development. *Use The Index, Luke* explains SQL indexing from grounds up and doesn’t stop at ORM tools like Hibernate.\n\n*Use The Index, Luke* is the free web-edition of [my book **SQL Performance Explained** (from Є9.95)](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=front&utm_medium=web). Be sure to [subscribe my **free newsletter**](https://winand.at/lists).\n\n## SQL Indexing in MySQL, Oracle, SQL Server, etc.\n\n*Use The Index, Luke* presents indexing in a vendor agnostic fashion. Product specific notes are provided like here:\n\nDb2 (LUW)\n\n*Use The Index, Luke* covers SQL indexing for IBM Db2. Tests were conducted with Db2 for Linux, UNIX and Windows, (LUW) V10.5 through 12.1.\n\nMySQL\n\n*Use The Index, Luke* covers SQL indexing for MySQL. Tests were conducted with MySQL 5.5 through 26.7.0.\n\nOracle\n\n*Use The Index, Luke* covers SQL indexing for the Oracle database. Tests were conducted with Oracle 11g through 26ai (23.26.2).\n\nPostgreSQL\n\n*Use The Index, Luke* covers SQL indexing for PostgreSQL. Tests were conducted with PostgreSQL 9.0 through 17.\n\nSQL Server\n\n*Use The Index, Luke* covers SQL indexing for Microsoft SQL Server. Tests were conducted with SQL Server 2008R2 through 2025.\n\nHave more questions about SQL indexing or tuning? No problem—have a look at my training and tuning services at [winand.at](https://winand.at/).\n\n## Table of Contents\n\n1. *[Preface](/sql/preface)* — Why is indexing a development task?\n2. *[Anatomy of an Index](/sql/anatomy)* — What does an index look like?\n 1. *[The Leaf Nodes](/sql/anatomy/the-leaf-nodes)* — A doubly linked list\n 2. *[The B-Tree](/sql/anatomy/the-tree)* — It’s a balanced tree\n 3. *[Slow Indexes, Part I](/sql/anatomy/slow-indexes)* — Two ingredients make the index slow\n3. *[The Where Clause](/sql/where-clause)* — Indexing to improve search performance\n 1. *[The Equals Operator](/sql/where-clause/the-equals-operator)* — Exact key lookup\n 1. *[Primary Keys](/sql/where-clause/the-equals-operator/primary-keys)* — Verifying index usage\n 2. *[Concatenated Keys](/sql/where-clause/the-equals-operator/concatenated-keys)* — Multi-column indexes\n 3. *[Slow Indexes, Part II](/sql/where-clause/the-equals-operator/slow-indexes-part-ii)* — The first ingredient, revisited\n 2. *[Functions](/sql/where-clause/functions)* — Using functions in the `where` clause\n 1. *[Case-Insensitive Search](/sql/where-clause/functions/case-insensitive-search)* — `UPPER` and `LOWER`\n 2. *[User-Defined Functions](/sql/where-clause/functions/user-defined-functions)* — Limitations of function-based indexes\n 3. *[Over-Indexing](/sql/where-clause/functions/over-indexing)* — Avoid redundancy\n 3. *[Bind Variables](/sql/where-clause/bind-parameters)* — For security and performance\n 4. *[Searching for Ranges](/sql/where-clause/searching-for-ranges)* — Beyond equality\n 1. *[Greater, Less and `BETWEEN`](/sql/where-clause/searching-for-ranges/greater-less-between-tuning-sql-access-filter-predicates)* — The column order revisited\n 2. *[Indexing SQL `LIKE` Filters](/sql/where-clause/searching-for-ranges/like-performance-tuning)* — `LIKE` is not for full-text search\n 3. *[Index Combine](/sql/where-clause/searching-for-ranges/index-merge-performance)* — Why not using one index for every column?\n 5. *[Partial Indexes](/sql/where-clause/partial-and-filtered-indexes)* — Indexing selected rows\n 6. *[`NULL` in the Oracle Database](/sql/where-clause/null)* — An important curiosity\n 1. *[`NULL` in Indexes](/sql/where-clause/null/index)* — Every index is a partial index\n 2. *[`NOT NULL` Constraints](/sql/where-clause/null/not-null-constraint)* — affect index usage\n 3. *[Emulating Partial Indexes](/sql/where-clause/null/partial-index)* — using function-based indexing\n 7. *[Obfuscated Conditions](/sql/where-clause/obfuscation)* — Common anti-patterns\n 1. *[Dates](/sql/where-clause/obfuscation/dates)* — Pay special attention to `DATE` types\n 2. *[Numeric Strings](/sql/where-clause/obfuscation/numeric-strings)* — Don’t mix types\n 3. *[Combining Columns](/sql/where-clause/obfuscation/concatenation)* — use redundant `where` clauses\n 4. *[Smart Logic](/sql/where-clause/obfuscation/smart-logic)* — The smartest way to make SQL slow\n 5. *[Math](/sql/where-clause/obfuscation/math)* — Databases don’t solve equations\n4. *[Testing and Scalability](/sql/testing-scalability)* — About hardware\n 1. *[Data Volume](/sql/testing-scalability/data-volume)* — Sloppy indexing bites back\n 2. *[System Load](/sql/testing-scalability/system-load)* — Production load affects response time\n 3. *[Response Time and Throughput](/sql/testing-scalability/response-time-throughput-scaling-horizontal)* — Horizontal scalability\n5. *[The Join Operation](/sql/join)* — Not slow, if done right\n 1. *[Nested Loops](/sql/join/nested-loops-join-n1-problem)* — About the N+1 selects problem in ORM\n 2. *[Hash Join](/sql/join/hash-join-partial-objects)* — Requires an entirely different indexing approach\n 3. *[Sort-Merge Join](/sql/join/sort-merge-join)* ‌— Like a zipper on two sorted sets\n6. *[Clustering Data](/sql/clustering)* — To reduce IO\n 1. *[Index Filter Predicates Intentionally Used](/sql/clustering/index-filter-predicates)* — to tune `LIKE`\n 2. *[Index-Only Scan](/sql/clustering/index-only-scan-covering-index)* — Avoiding table access\n 3. *[Index-Organized Table](/sql/clustering/index-organized-clustered-index)* — Clustered indexes without tables\n7. *[Sorting and Grouping](/sql/sorting-grouping)* — Pipelined `order by`: the third power\n 1. *[Indexed Order By](/sql/sorting-grouping/indexed-order-by)* — `where` clause interactions\n 2. *[`ASC`/`DESC` and `NULL FIRST`/`LAST`](/sql/sorting-grouping/order-by-asc-desc-nulls-last)* — changing index order\n 3. *[Indexed Group By](/sql/sorting-grouping/indexed-group-by)* — Pipelining `group by`\n8. *[Partial Results](/sql/partial-results)* — Paging efficiently\n 1. *[Selecting Top-N Rows](/sql/partial-results/top-n-queries)* — if you need the first few rows only\n 2. *[Fetching The Next Page](/sql/partial-results/fetch-next-page)* — The offset and seek methods compared\n 3. *[Window-Functions](/sql/partial-results/window-functions)* — Pagination using analytic queries\n9. *[Insert, Delete and Update](/sql/dml)* — Indexing impacts on DML statements\n 1. *[Insert](/sql/dml/insert)* — cannot take direct benefit from indexes\n 2. *[Delete](/sql/dml/delete)* — uses indexes for the `where` clause\n 3. *[Update](/sql/dml/update)* — does not affect all indexes of the table\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 7168, "slov": 942, "odkazu": 97, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:33", "sha256": "e44f917a9a95902f52b4301fe60e843b83c40e1fad4fd5fdf88b08176857d025", "hloubka": 0, "zdroj_objevu": "seed", "ze_seznamu": true, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://sql-performance-explained.com/", "https://winand.at/lists", "https://winand.at/", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/3-minute-quiz", "titulek": "3-Minute Quiz: What do you know about SQL performance?", "h1": "The 3-Minute SQL Indexing Quiz That 60% Fail", "popis": "Just 5 questions to see how much you know about SQL performance. Never make these mistakes again.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/3-minute-quiz", "jazyk": "en", "robots_meta": "", "og": {"og:title": "3-Minute Quiz: What do you know about SQL performance?", "og:description": "Just 5 questions to see how much you know about SQL performance. Never make these mistakes again.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "The 3-Minute SQL Indexing Quiz That 60% Fail"}, {"uroven": 2, "text": "60% Fail?"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\nCan you spot the five most common SQL indexing mistakes?\n\n# The 3-Minute SQL Indexing Quiz That 60% Fail\n\n---\n\n```\n“SQL-Tuning is black magic\nlike alchemy:\nit consists of obscure rules,\nunderstood only by a handful\nof insiders.”\n```\n\nThat is a myth. SQL engines use well-known algorithms to deliver predictable performance. It is, however, easy to write SQL queries that cannot use the most efficient algorithm and thus deliver unexpected performance.\n\nThe following questions provide examples that might make you believe that SQL tuning is black magic. The explanations at the end are just a few sentences long and reveal that the black magic is pure science.\n\nChoose a system\n\n[Db2 (LUW)](/3-minute-quiz/db2-luw)[MySQL](/3-minute-quiz/mysql)[Oracle](/3-minute-quiz/oracle)[PostgreSQL](/3-minute-quiz/postgresql)[SQL Server](/3-minute-quiz/sql-server)[SQLite](/3-minute-quiz/sqlite)\n\n## 60% Fail?\n\nI checked 28,000 results: only 40% answered more than three of the five questions correctly.\n\n“*You consider three correct answers to five questions as failed?*”\n\nYes, because most questions have only two options. That gives you a 12.5% chance to pass the quiz by guessing. Accepting three correct answers would give you a chance of 29% to pass by guessing. That would be unreasonable, I think.\n\nMore about the results in [this blog post](/blog/2014-02/results-three-minutes-sql-performance-quiz). But remember to take the quiz first.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2063, "slov": 298, "odkazu": 58, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:35", "sha256": "611c055729995bed7584175b31df205a53d9847c02dcc6e8e0cd3b99f981f0a1", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/3-minute-quiz/db2-luw", "titulek": "3-Minute Quiz: How Much do You Know About Db2 (LUW) Indexing?", "h1": "How Much do You Know About Db2 (LUW) Indexing?", "popis": "Just 5 questions to see how much you know about Db2 (LUW) performance. Never get these things wrong again.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/3-minute-quiz/db2-luw", "jazyk": "en", "robots_meta": "", "og": {"og:title": "3-Minute Quiz: How Much do You Know About Db2 (LUW) Indexing?", "og:description": "Just 5 questions to see how much you know about Db2 (LUW) performance. Never get these things wrong again.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "How Much do You Know About Db2 (LUW) Indexing?"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# How Much do You Know About Db2 (LUW) Indexing?\n\n---\n\nMost questions ask whether the index is the right one for the query (*good fit*) or not (*bad fit*).\n\nIf you think about changing a query to improve performance, the new query must still return the same result. That includes all columns if `select *` is used.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 955, "slov": 138, "odkazu": 52, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:35", "sha256": "4938fde0487e175bd33bf543b35ad4caac913022573b5e0e797355b42ff002b2", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/3-minute-quiz/mysql", "titulek": "3-Minute Quiz: How Much do You Know About MySQL Indexing?", "h1": "How Much do You Know About MySQL Indexing?", "popis": "Just 5 questions to see how much you know about MySQL performance. Never get these things wrong again.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/3-minute-quiz/mysql", "jazyk": "en", "robots_meta": "", "og": {"og:title": "3-Minute Quiz: How Much do You Know About MySQL Indexing?", "og:description": "Just 5 questions to see how much you know about MySQL performance. Never get these things wrong again.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "How Much do You Know About MySQL Indexing?"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# How Much do You Know About MySQL Indexing?\n\n---\n\nMost questions ask whether the index is the right one for the query (*good fit*) or not (*bad fit*).\n\nIf you think about changing a query to improve performance, the new query must still return the same result. That includes all columns if `select *` is used.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 951, "slov": 137, "odkazu": 52, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:36", "sha256": "c06ae359364875bb7de4c6478de7965a3828623570a5eecf1cea960af8755a68", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/3-minute-quiz/oracle", "titulek": "3-Minute Quiz: How Much do You Know About Oracle Indexing?", "h1": "How Much do You Know About Oracle Indexing?", "popis": "Just 5 questions to see how much you know about Oracle performance. Never get these things wrong again.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/3-minute-quiz/oracle", "jazyk": "en", "robots_meta": "", "og": {"og:title": "3-Minute Quiz: How Much do You Know About Oracle Indexing?", "og:description": "Just 5 questions to see how much you know about Oracle performance. Never get these things wrong again.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "How Much do You Know About Oracle Indexing?"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# How Much do You Know About Oracle Indexing?\n\n---\n\nMost questions ask whether the index is the right one for the query (*good fit*) or not (*bad fit*).\n\nIf you think about changing a query to improve performance, the new query must still return the same result. That includes all columns if `select *` is used.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 952, "slov": 137, "odkazu": 52, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:37", "sha256": "4a7ad054689445b5ff640ce53b80ba40380f0f546bcd08ad96842733e4223cae", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/3-minute-quiz/postgresql", "titulek": "3-Minute Quiz: How Much do You Know About PostgreSQL Indexing?", "h1": "How Much do You Know About PostgreSQL Indexing?", "popis": "Just 5 questions to see how much you know about PostgreSQL performance. Never get these things wrong again.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/3-minute-quiz/postgresql", "jazyk": "en", "robots_meta": "", "og": {"og:title": "3-Minute Quiz: How Much do You Know About PostgreSQL Indexing?", "og:description": "Just 5 questions to see how much you know about PostgreSQL performance. Never get these things wrong again.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "How Much do You Know About PostgreSQL Indexing?"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# How Much do You Know About PostgreSQL Indexing?\n\n---\n\nMost questions ask whether the index is the right one for the query (*good fit*) or not (*bad fit*).\n\nIf you think about changing a query to improve performance, the new query must still return the same result. That includes all columns if `select *` is used.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 956, "slov": 137, "odkazu": 52, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:38", "sha256": "301fbaee377b29faf7d69890586f5998ed1ea9f0e3a64005b7d2a04c061794ab", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/3-minute-quiz/sql-server", "titulek": "3-Minute Quiz: How Much do You Know About SQL Server Indexing?", "h1": "How Much do You Know About SQL Server Indexing?", "popis": "Just 5 questions to see how much you know about SQL Server performance. Never get these things wrong again.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/3-minute-quiz/sql-server", "jazyk": "en", "robots_meta": "", "og": {"og:title": "3-Minute Quiz: How Much do You Know About SQL Server Indexing?", "og:description": "Just 5 questions to see how much you know about SQL Server performance. Never get these things wrong again.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "How Much do You Know About SQL Server Indexing?"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# How Much do You Know About SQL Server Indexing?\n\n---\n\nMost questions ask whether the index is the right one for the query (*good fit*) or not (*bad fit*).\n\nIf you think about changing a query to improve performance, the new query must still return the same result. That includes all columns if `select *` is used.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 956, "slov": 138, "odkazu": 52, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:39", "sha256": "999c78dc03caea8cb4d1d3889891829d419842949ebb08a9ff8d534ed2bba291", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/3-minute-quiz/sqlite", "titulek": "3-Minute Quiz: How Much do You Know About SQLite Indexing?", "h1": "How Much do You Know About SQLite Indexing?", "popis": "Just 5 questions to see how much you know about SQLite performance. Never get these things wrong again.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/3-minute-quiz/sqlite", "jazyk": "en", "robots_meta": "", "og": {"og:title": "3-Minute Quiz: How Much do You Know About SQLite Indexing?", "og:description": "Just 5 questions to see how much you know about SQLite performance. Never get these things wrong again.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "How Much do You Know About SQLite Indexing?"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# How Much do You Know About SQLite Indexing?\n\n---\n\nMost questions ask whether the index is the right one for the query (*good fit*) or not (*bad fit*).\n\nIf you think about changing a query to improve performance, the new query must still return the same result. That includes all columns if `select *` is used.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 952, "slov": 137, "odkazu": 52, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:40", "sha256": "c36254d65907b500804c17136d94c8f368941888009a1020d6719ecc286b06e5", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/404", "titulek": "Page Not Found", "h1": "404 - Page Not Found", "popis": "Error 404: Page not found", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/404", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Page Not Found", "og:description": "Error 404: Page not found", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "404 - Page Not Found"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# 404 - Page Not Found\n\n---\n\n```\nSQL*Plus>\nno rows selected\n```\n\n```\nmysql>\nEmpty set (0.00 sec)\n```\n\n```\npostgres=#\n(0 rows)\n```\n\n```\ndb2 =>\n 0 record(s) selected.\n```\n\n```\nsqlite>\nsqlite>\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 813, "slov": 103, "odkazu": 52, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:41", "sha256": "c9d10a9e6c2c2de2db597a0378efe0bd75e1e047e68574188727910356ce8355", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog", "titulek": "The Use The Index, Luke! Blog Archive: SQL, Performance and the like", "h1": "Blog Archive", "popis": "Database performance blog for developers. Covering all major SQL databases: MySQL, PostgreSQL, Oracle, SQL Server, …", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog", "jazyk": "en", "robots_meta": "", "og": {"og:title": "The Use The Index, Luke! Blog Archive: SQL, Performance and the like", "og:description": "Database performance blog for developers. Covering all major SQL databases: MySQL, PostgreSQL, Oracle, SQL Server, …", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Blog Archive"}, {"uroven": 2, "text": "2024-12-10 Automatic Rewrite of Date and Time Ranges"}, {"uroven": 2, "text": "2019-04-30 A Close Look at the Index Include Clause"}, {"uroven": 4, "text": "Translations"}, {"uroven": 2, "text": "2018-07-31 Upcoming Training: SQL Performance Kick-Start and modern SQL"}, {"uroven": 2, "text": "2017-11-13 Spanish Anyone?"}, {"uroven": 2, "text": "2017-11-06 Big News In Databases — Fall 2017"}, {"uroven": 2, "text": "2017-05-11 Big News In Databases — Spring 2017"}, {"uroven": 2, "text": "2016-11-28 Big News In Databases"}, {"uroven": 2, "text": "2016-07-29 On Uber’s Choice of Databases"}, {"uroven": 4, "text": "Translations"}, {"uroven": 2, "text": "2015-02-02 Modern SQL in PostgreSQL [and other databases]"}, {"uroven": 2, "text": "2014-11-03 2017-11-02 Seven Surprising Findings About Db2 (LUW)"}, {"uroven": 2, "text": "2014-10-15 Meta-Post: New Mascot, New Language, New Database"}, {"uroven": 2, "text": "2014-08-06 2023-09-08 We need tool support for keyset pagination"}, {"uroven": 4, "text": "Translations"}, {"uroven": 2, "text": "2014-07-09 Finding All the Red M&Ms: A Story of Indexes and Full‑Table Scans"}, {"uroven": 2, "text": "2014-05-25 What I learned about SQLite…at a PostgreSQL conference"}, {"uroven": 2, "text": "2014-04-25 What’s left of NoSQL?"}, {"uroven": 2, "text": "2014-04-01 Thank You MySQL, We’ll Miss You!"}, {"uroven": 2, "text": "2014-02-20 Results of the SQL Performance Quiz: 60% fail"}, {"uroven": 4, "text": "Note"}, {"uroven": 2, "text": "2014-01-17 Unreasonable Defaults: Primary Key as Clustering Key"}, {"uroven": 2, "text": "2013-10-01 MongoDB is to NoSQL like MySQL to SQL — in the most harmful way"}, {"uroven": 4, "text": "Translations"}, {"uroven": 2, "text": "2013-08-25 Don’t ask for what you don’t need"}, {"uroven": 2, "text": "2013-08-13 Try it online!"}, {"uroven": 2, "text": "2013-07-26 2017-10-25 About Optimizer Hints: Prefer supportive and avoid restrictive SQL hints"}, {"uroven": 2, "text": "Combined Selectivity Example"}, {"uroven": 2, "text": "2013-07-18 Pagination Done the Right Way"}, {"uroven": 2, "text": "2013-07-10 Indexes: The neglected performance all-rounder"}, {"uroven": 2, "text": "2013-07-02 Afraid of SSD? Will SSD kill the profession of database and SQL tuning specialists?"}, {"uroven": 2, "text": "2013-05-21"}, {"uroven": 2, "text": "2013-04-23 The two top performance problems caused by ORM tools"}, {"uroven": 2, "text": "2013-04-22 I need your help!"}, {"uroven": 2, "text": "2013-03-04"}, {"uroven": 2, "text": "2013-02-22"}, {"uroven": 2, "text": "2013-02-05 Top Tweets January 2013"}, {"uroven": 2, "text": "2013-02-05 FOSDEM Impressions"}, {"uroven": 2, "text": "2013-01-08 I’m speaking at FOSDEM PGDay 2013"}, {"uroven": 2, "text": "2012-12-28 Top Tweets December 2012"}, {"uroven": 2, "text": "2012-12-19 French anybody? Use The Index, Luke is now available in French."}, {"uroven": 2, "text": "2012-12-06 Instant What?"}, {"uroven": 2, "text": "2012-11-15"}, {"uroven": 2, "text": "2012-11-13 PG.Conf EU 2012 — Summary"}, {"uroven": 2, "text": "2012-10-12"}, {"uroven": 2, "text": "2012-10-08 My PGConf.EU 2012 Schedule"}, {"uroven": 2, "text": "2012-08-13 Second Anniversary"}, {"uroven": 2, "text": "2012-08-13 Convinced"}, {"uroven": 2, "text": "2012-08-12"}, {"uroven": 2, "text": "2012-08-08 Finally: Almost World-Wide Free Shipping"}, {"uroven": 2, "text": "2012-05-25 Done! Or What?"}, {"uroven": 2, "text": "2011-08-13 One Year and Three Minutes"}, {"uroven": 2, "text": "2011-07-30 MySQL Row Generator"}, {"uroven": 4, "text": "Update 2017-05-23"}, {"uroven": 4, "text": "Update 2018-04-19"}, {"uroven": 2, "text": "2011-07-16 Planning For Reuse"}, {"uroven": 2, "text": "2011-06-24"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Blog Archive\n\n---\n\n## [2024-12-10 Automatic Rewrite of Date and Time Ranges](/blog/2024-12/date-time-prefix-rewrite)\n\nThe following chart shows which DBMS rewrites `where` clause expressions that access the year part of a `date` or `timestamp` (or the like) into a range expression such as `ts >= DATE'2024-01-01' AND ts < DATE'2025-01-01'`. This enables the use of a sort-based index on the `ts` column.\n\nThe yellow check marks mean that the rewrite is always done—even if there was a function-based index on the original expression in the `where` clause.\n\n[(Read more)](https://use-the-index-luke.com/blog/2024-12/date-time-prefix-rewrite)\n\n## [2019-04-30 A Close Look at the Index `Include` Clause](/blog/2019-04/include-columns-in-btree-indexes)\n\n#### Translations\n\n中文 [对索引Include子句的深入分析](http://www.postgres.cn/v2/news/viewone/1/521)\n\nفارسی[نگاهی عمقی به ؚباعت include ŘŻŘą ایندکس‌ها](https://davat.dev/%d9%86%da%af%d8%a7%d9%87%db%8c-%d8%b9%d9%85%d9%82%db%8c-%d8%a8%d9%87-%d8%b9%d8%a8%d8%a7%d8%b1%d8%aa-include-%d8%af%d8%b1-%d8%a7%db%8c%d9%86%d8%af%da%a9%d8%b3%d9%87%d8%a7/)\n\nSome database—namely Microsoft SQL Server, IBM Db2, and also PostgreSQL since release 11—offer an `include` clause in the `create index` statement. The introduction of this feature to PostgreSQL is the trigger for this long overdue explanation of the `include` clause.\n\nBefore going into the details, let’s start with a short recap on how (non-clustered) B-tree indexes work and what the all-mighty index-only scan is.\n\n1. [Recap: B-tree Indexes](https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes#btree)\n2. [Recap: Index-Only Scan](https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes#ios)\n3. [The Include Clause](https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes#include)\n4. [Filtering on Include Columns](https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes#filtering)\n5. [Unique Indexes with Include Clause](https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes#unique)\n6. [Compatibility](https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes#compatibility)\n7. [PostgreSQL: No Filtering Before Visibility Check](https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes#postgresql-limitations)\n\n[(Read more)](https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes)\n\n## [2018-07-31 Upcoming Training: SQL Performance Kick-Start and modern SQL](/blog/2018-07/upcoming-advanced-sql-training)\n\nI haven’t blogged here in a while. It doesn’t mean *Use The Index, Luke!* is abandoned or anything the like. Au contraire, I’m having some topics in the pipeline I’m hoping to blog soon about. Furthermore, *Use The Index, Luke!* is regularly updated to reflect changes in newer databases releases.\n\nThe last updates were done a few weeks back when MySQL 8.0 was released (see my blog posts “[One Giant Leap For SQL: MySQL 8.0 Released](https://modern-sql.com/blog/2018-04/mysql-8.0)” and “[Big News In Databases — Summer 2018](https://winand.at/newsletter/2018-07/sql-over-the-cloud-fsyncgate)”). Feel free to subscribe my [modern SQL](https://modern-sql.com/) blog too ([RSS](https://modern-sql.com/feed), [EMail](https://winand.at/lists)) so you don’t miss any news.\n\nBut what I actually wanted to tell you about is my upcoming **[advanced SQL training](https://winand.at/sql-training/5-day-training/aug-sept-2018) in Vienna (Austria) from September 17 to 21 2018**. Yes, that’s full week of SQL goodness.\n\nThe training covers the full content of my book “[SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-2018-07-training)” and a lot of the “[modern SQL](https://modern-sql.com/)” topics I’m currently writing and [talking](https://winand.at/events) about (window functions, recursion, …) but also barely known basics like the [three-valued logic of SQL](https://modern-sql.com/concept/three-valued-logic). You can find [all details and register (without obligation) at my “commercial” website winand.at](https://winand.at/sql-training/5-day-training/aug-sept-2018).\n\n[(Read more)](https://use-the-index-luke.com/blog/2018-07/upcoming-advanced-sql-training)\n\n## [2017-11-13 Spanish Anyone?](/blog/2017-11/spanish-anyone)\n\nThe Spanish translation of my book [*SQL Performance Explained*](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-201711-spanish) has just been published. It’s the fifth language so far … now there’s a [German](https://sql-performance-explained.de?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-201711-spanish), [English](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-201711-spanish), [French](https://sql-au-coeur-des-performances.fr/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-201711-spanish), [Japanese](https://sql-performance-explained.jp/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-201711-spanish) and [Spanish](https://rendimiento-sql-explicado.es/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-201711-spanish) version of the book!\n\nYou can buy it directly from the [book website](https://rendimiento-sql-explicado.es/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-201711-spanish) (PDF or paperback), and some it’s also [available through some European Amazon stores](https://rendimiento-sql-explicado.es/r/local-amazon?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-201711-spanish) (paperback only). The prices are the same as for the other languages: **€9.95 for the PDF**, €29.95 for the hard copy, **€34.95 for PDF+paperback**. If you order from the [book website, you get **free shipping (worldwide!)**](https://rendimiento-sql-explicado.es/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-201711-spanish)\n\nAs for the other languages, all of the Spanish **content is available for free at [https://use-the-index-luke.com/es/](https://use-the-index-luke.com/es)**.\n\n[(Read more)](https://use-the-index-luke.com/blog/2017-11/spanish-anyone)\n\n[(Read more)](https://use-the-index-luke.com/blog/2017-11/spanish-anyone)\n\n## [2017-11-06 Big News In Databases — Fall 2017](/blog/2017-11/cloud-wars-ibm-db2-renaming-major-database-releases)\n\nDon’t fall behind: Here’s the most important database news from the last six months.\n\n1. [SQL on The Rise](https://use-the-index-luke.com/blog/2017-11/cloud-wars-ibm-db2-renaming-major-database-releases#sql-on-the-rise)\n2. [The Cloud War Continues](https://use-the-index-luke.com/blog/2017-11/cloud-wars-ibm-db2-renaming-major-database-releases#cloud-war)\n3. [IBM’s Renaming Insanity](https://use-the-index-luke.com/blog/2017-11/cloud-wars-ibm-db2-renaming-major-database-releases#db2-renaming)\n4. [New Database Releases](https://use-the-index-luke.com/blog/2017-11/cloud-wars-ibm-db2-renaming-major-database-releases#new-database-releases)\n5. [News on my Sites](https://use-the-index-luke.com/blog/2017-11/cloud-wars-ibm-db2-renaming-major-database-releases#news-on-my-sites)\n6. [From Twitter, in Great Brevity (follow me on Twitter)](https://use-the-index-luke.com/blog/2017-11/cloud-wars-ibm-db2-renaming-major-database-releases#twitter)\n\n[(Read more)](https://use-the-index-luke.com/blog/2017-11/cloud-wars-ibm-db2-renaming-major-database-releases)\n\n## [2017-05-11 Big News In Databases — Spring 2017](/blog/2017-05/new-sql-standard-oracle-122-acidrain)\n\nHere is the most noteworthy news since [my last “Big News In Databases” post from November 2016](https://use-the-index-luke.com/blog/2016-11/big-news-in-databases).\n\n1. [A new SQL standard was released (SQL:2016)](https://use-the-index-luke.com/blog/2017-05/new-sql-standard-oracle-122-acidrain#new-standard)\n2. [Oracle Database 12.2 on premises, cloud prices double for AWS and Azure](https://use-the-index-luke.com/blog/2017-05/new-sql-standard-oracle-122-acidrain#oracle-122)\n3. [Database of the year](https://use-the-index-luke.com/blog/2017-05/new-sql-standard-oracle-122-acidrain#db-of-the-year)\n4. [ACIDRain: Study highlights security risk of wrong transaction use](https://use-the-index-luke.com/blog/2017-05/new-sql-standard-oracle-122-acidrain#acidrain)\n5. [From my Twitter timeline](https://use-the-index-luke.com/blog/2017-05/new-sql-standard-oracle-122-acidrain#twitter)\n\n[(Read more)](https://use-the-index-luke.com/blog/2017-05/new-sql-standard-oracle-122-acidrain)\n\n## [2016-11-28 Big News In Databases](/blog/2016-11/big-news-in-databases)\n\nThere’s been a lot of big news in 2016, also when it comes to databases. Let’s have a look at the really BIG news.\n\n1. [MySQL and MariaDB Become Modern](https://use-the-index-luke.com/blog/2016-11/big-news-in-databases#modern-mysql)\n2. [Parallel Execution in PostgreSQL 9.6](https://use-the-index-luke.com/blog/2016-11/big-news-in-databases#parallel-postgresql)\n3. [SQL Server on Linux (Beta)](https://use-the-index-luke.com/blog/2016-11/big-news-in-databases#sql-server-on-linux)\n4. [Oracle 12cR2 Currently Cloud Only](https://use-the-index-luke.com/blog/2016-11/big-news-in-databases#oracle-122-cloud-only)\n5. [DB2 Learns OFFSET…Unfortunately](https://use-the-index-luke.com/blog/2016-11/big-news-in-databases#db2-learns-offset)\n6. [SQLite Gets Row-Values](https://use-the-index-luke.com/blog/2016-11/big-news-in-databases#sqlite-row-values)\n\n[(Read more)](https://use-the-index-luke.com/blog/2016-11/big-news-in-databases)\n\n## [2016-07-29 On Uber’s Choice of Databases](/blog/2016-07-29/on-ubers-choice-of-databases)\n\n#### Translations\n\nA Japanese translation of this article is available [here](https://pgsqldeepdive.blogspot.com/2016/08/on-ubers-choice-of-databases-uber.html).\n\nA Chinese translation of this article is available [here](https://www.infoq.cn/article/the-database-selection-of-uber/).\n\nA few days ago Uber published the article “[Why Uber Engineering Switched from Postgres to MySQL](https://www.uber.com/blog/postgres-to-mysql-migration/)”. I didn’t read the article right away because my inner nerd told me to do some home improvements instead. While doing so my mailbox was filling up with questions like “Is PostgreSQL really that lousy?”. Knowing that PostgreSQL is not generally lousy, these messages made me wonder what the heck is written in this article. This post is an attempt to make sense out of Uber’s article.\n\nIn my opinion Uber’s article basically says that they found MySQL to be a better fit for *their environment* as PostgreSQL. However, the article does a lousy job to transport this message. Instead of writing “PostgreSQL has some limitations for `update`-heavy use-cases” the article just says “Inefficient architecture for writes,” for example. In case you don’t have an *update-heavy* use-case, don’t worry about the problems described in Uber’s article.\n\nIn this post I’ll explain why I think Uber’s article must not be taken as general advice about the choice of databases, why MySQL might still be a good fit for Uber, and why success might cause more problems than just scaling the data store.\n\n1. [On UPDATE](https://use-the-index-luke.com/blog/2016-07-29/on-ubers-choice-of-databases#update)\n2. [On SELECT](https://use-the-index-luke.com/blog/2016-07-29/on-ubers-choice-of-databases#select)\n3. [On Index Rebalancing](https://use-the-index-luke.com/blog/2016-07-29/on-ubers-choice-of-databases#index-rebalancing)\n4. [On Physical Replication](https://use-the-index-luke.com/blog/2016-07-29/on-ubers-choice-of-databases#physical-replication)\n5. [On Developers](https://use-the-index-luke.com/blog/2016-07-29/on-ubers-choice-of-databases#developers)\n6. [On Success](https://use-the-index-luke.com/blog/2016-07-29/on-ubers-choice-of-databases#success)\n7. [On Uber’s Choice of Databases](https://use-the-index-luke.com/blog/2016-07-29/on-ubers-choice-of-databases#choice-of-databases)\n\n[(Read more)](https://use-the-index-luke.com/blog/2016-07-29/on-ubers-choice-of-databases)\n\n## [2015-02-02 Modern SQL in PostgreSQL [and other databases]](/blog/2015-02/modern-sql)\n\nSQL has gone out of fashion lately—partly due to the NoSQL movement, but mostly because SQL is often still used like 20 years ago. As a matter of fact, the SQL standard continued to evolve during the past decades resulting in the current release of 2011. In this session, we will go through the most important additions since the widely known SQL-92, explain how they work and how PostgreSQL supports and extends them. We will cover common table expressions and window functions in detail and have a very short look at the temporal features of SQL:2011 and the related features of PostgreSQL.”\n\nThis is the abstract for the talk I’ve given at [FOSDEM](https://archive.fosdem.org/2015/schedule/event/modern_sql_in_postgresql/) in Brussels on Saturday. The PostgreSQL community was so kind to host this talk in their ([way too small](https://x.com/beschl/status/561858608619864064)) devroom—thus the references to PostgreSQL. However, the talk is build upon standard SQL and covers features that are commonly available in Db2 (LUW), Oracle, SQL Server and SQLite. MySQL does not yet support any of those features except [`OFFSET`, which is evil](https://use-the-index-luke.com/no-offset).\n\nOne last thing before going on to the slides: [*Use The Index, Luke* has a shop](https://use-the-index-luke.com/shop). Stickers, coasters, books, mugs. [Have a look](https://use-the-index-luke.com/shop).\n\n[(Read more)](https://use-the-index-luke.com/blog/2015-02/modern-sql)\n\n## [2014-11-03 2017-11-02 Seven Surprising Findings About Db2 (LUW)](/blog/2014-11/seven-surprising-findings-about-DB2)\n\nI’ve just completed IBM Db2 for Linux, Unix and Windows (LUW) coverage here on [Use The Index, Luke](https://use-the-index-luke.com/) as preparation for an upcoming [training I’m giving](https://winand.at/sql-training/inhouse). This blog post describes the major differences I’ve found compared to the other databases I’m covering (Oracle, SQL Server, PostgreSQL and MySQL).\n\n1. [Free & Easy](https://use-the-index-luke.com/blog/2014-11/seven-surprising-findings-about-DB2#blog-db2into-freeeasy)\n2. [No Easy Explain](https://use-the-index-luke.com/blog/2014-11/seven-surprising-findings-about-DB2#blog-db2intro-explain)\n3. [Emulating Partial Indexes is Possible](https://use-the-index-luke.com/blog/2014-11/seven-surprising-findings-about-DB2#blog-db2intro-partialidx)\n4. [INCLUDE Clause Only for Unique Indexes](https://use-the-index-luke.com/blog/2014-11/seven-surprising-findings-about-DB2#blog-db2intro-include)\n5. [Almost No NULLS FIRST/LAST Support until 11.1](https://use-the-index-luke.com/blog/2014-11/seven-surprising-findings-about-DB2#blog-db2intro-nulls)\n6. [SQL:2008 FETCH FIRST but not OFFSET (until 11.1)](https://use-the-index-luke.com/blog/2014-11/seven-surprising-findings-about-DB2#blog-db2intro-fetchfirst)\n7. [Decent Row-Value Predicates Support](https://use-the-index-luke.com/blog/2014-11/seven-surprising-findings-about-DB2#blog-db2intro-rowvalues)\n\n[(Read more)](https://use-the-index-luke.com/blog/2014-11/seven-surprising-findings-about-DB2)\n\n## [2014-10-15 Meta-Post: New Mascot, New Language, New Database](/blog/2014-10/meta-post-mascot-japanese-db2)\n\nIt has been quiet here at the *Use The Index, Luke* blog lately. But that’s not because I’ve run out of topics to write about — in fact, my blog backlog seems to be ever growing — the recent silence is just because there are some more demanding projects happening at the moment.\n\nFirst of all, *Use the Index, Luke* got a [new mascot](https://use-the-index-luke.com/blog/2014-10/meta-post-mascot-japanese-db2)—not exactly breaking news. However, I’m currently preparing give-aways and merchandise products featuring the new mascot. Stay tuned.\n\nNext, *Use The Index, Luke* gets translated to Japanese! The first two chapters have [just been published](https://use-the-index-luke.com/ja/sql/preface). Insiders will remember that chapter 1 and 2 make up half of the book. The translation is done by [Hayato Matsuura](https://x.com/dblmkt), [Takuto Matsuu](https://x.com/matsuu) has a second look over it. As far as I can tell both are making a great job and I’d like to be the first to thank them! Please help spreading the word about this in the Japanese community.\n\nFinally, I’m just adding Db2 (LUW) as a first-class citizen to *Use The Index, Luke* because a client wanted to get [my SQL performance training](https://winand.at/sql-training/inhouse) based on Db2 (LUW) Express-C (which is free, by the way). Like the Japanese translation, this work is not yet finished. However, the [appendix on execution plans](https://use-the-index-luke.com/sql/explain-plan/db2) is already there. Again, please help spreading the word about this in the Db2 community.\n\n[(Read more)](https://use-the-index-luke.com/blog/2014-10/meta-post-mascot-japanese-db2)\n\n## [2014-08-06 2023-09-08 We need tool support for keyset pagination](/no-offset)\n\n#### Translations\n\n[ [Deutsch](https://use-the-index-luke.com/de/no-offset), [Français](https://use-the-index-luke.com/fr/no-offset), [PortuguĂŞs](https://rafael.bernard-araujo.com/precisamos-de-apoio-das-ferramentas-para-a-paginacao-por-conjunto-de-chaves.php), [Russian](https://habr.com/ru/companies/tbank/articles/485036/)]\n\n[(Read more)](https://use-the-index-luke.com/no-offset)\n\n1. [Life Without OFFSET](https://use-the-index-luke.com/no-offset#life-without-offset)\n2. [But the Frameworks…](https://use-the-index-luke.com/no-offset#frameworks)\n\n[(Read more)](https://use-the-index-luke.com/no-offset)\n\n## [2014-07-09 Finding All the Red M&Ms: A Story of Indexes and Full‑Table Scans](/blog/2014-07/finding-all-the-red-mms)\n\n> *In this guest post, [Chris Saxon](https://www.chrissaxon.co.uk/) explains a very important topic using an analogy with chocolates: When does a database use an index and when is it better not using it. Although Chris explanation has the Oracle database in mind, the principles apply to other databases too.*\n\nA common question that comes up when people start tuning queries is “why doesn’t this query use the index I expect?”. There are a few myths surrounding when database optimizers will use an index. A common one I’ve heard is that an index will be used when accessing 5% or less of the rows in a table. This isn’t the case however - the basic decision on whether or not to use an index comes down to its cost.\n\n1. [How do databases determine the cost of an index?](https://use-the-index-luke.com/blog/2014-07/finding-all-the-red-mms#costing)\n2. [What have M&M’s got to do with databases?](https://use-the-index-luke.com/blog/2014-07/finding-all-the-red-mms#applied-to-databases)\n3. [When does an index scan become more efficient than a FTS?](https://use-the-index-luke.com/blog/2014-07/finding-all-the-red-mms#crossing-lines)\n4. [Bringing it all together](https://use-the-index-luke.com/blog/2014-07/finding-all-the-red-mms#conclusio)\n\n[(Read more)](https://use-the-index-luke.com/blog/2014-07/finding-all-the-red-mms)\n\n## [2014-05-25 What I learned about SQLite…at a PostgreSQL conference](/blog/2014-05/what-i-learned-about-sqlite-at-a-postgresql-conference)\n\nSo, I’ve been to [PgCon 2014 in Ottawa](https://www.pgcon.org/2014/) to give a short version of my [SQL performance training](https://winand.at/sql-training/inhouse). However, I think I ended up learning more about [SQLite](https://sqlite.com/) than about PostgreSQL there. Here is how that happened and what I actually learned.\n\n[(Read more)](https://use-the-index-luke.com/blog/2014-05/what-i-learned-about-sqlite-at-a-postgresql-conference)\n\n## [2014-04-25 What’s left of NoSQL?](/blog/2013-04/whats-left-of-nosql)\n\n*This is my own and very loose translation of an article I wrote for the Austrian newspaper [derStandard.at](https://www.derstandard.at/consent/tcf/1381368486902/Was-bleibt-von-NoSQL) in October 2013. As this article was very well received and the SQL vs. NoSQL discussion is currently hot again, I though it might be a good time for a translation.*\n\nBack in 2013 [The Register](https://www.theregister.com/software/2013/08/30/google-goes-back-to-the-future-with-sql-f1-database/937689) reported that Google sets its bets on SQL again. On the first sight this might look like a surprising move because it was of all things Google’s publications about [MapReduce](https://research.google/pubs/mapreduce-simplified-data-processing-on-large-clusters/) and [BigTable](https://research.google/pubs/bigtable-a-distributed-storage-system-for-structured-data/) that gave the NoSQL movement a big boost in the first place. On a second sight it turns out that there is a trend to use SQL or similar languages to access data from NoSQL systems—and that’s not even a new trend. However, it raises a question: What remains of NoSQL if we add SQL again? To answer this question, I need to start with a brief summary about the history of databases.\n\n1. [Top Dog SQL](https://use-the-index-luke.com/blog/2013-04/whats-left-of-nosql#top-dog-sql)\n2. [And Then: NoSQL](https://use-the-index-luke.com/blog/2013-04/whats-left-of-nosql#raise-of-nosql)\n3. [Nevertheless: Back to SQL](https://use-the-index-luke.com/blog/2013-04/whats-left-of-nosql#back-to-sql)\n4. [What’s left of NoSQL?](https://use-the-index-luke.com/blog/2013-04/whats-left-of-nosql#whats-left)\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-04/whats-left-of-nosql)\n\n## [2014-04-01 Thank You MySQL, We’ll Miss You!](/blog/2014-04-01/thank-you-mysql-we-will-miss-you)\n\nDear MySQL,\n\nThank you for introducing me to SQL. It must have been 1998 when we first met I and fell in love with the simplicity of SQL immediately. Before that I’ve been using [C structs](https://en.wikipedia.org/wiki/Struct_(C_programming_language)) all the time; I had to do my joins programmatically and also create and maintain my indexes manually. It was even hard to combine several search conditions via `and` and `or`. But then there was the shiny new world of SQL you were showing me…\n\nEverything was easily. Just write a `where` clause, no matter how complex, you found the right rows. Joins were equally easy to write and you took all the effort to combine the data from several tables as I needed them. I also remember how easy it became to manage the schema. Instead of writing a program to copy my data from one C struct to another, I just say `alter table` now—in the meanwhile it even works online in many cases! I didn’t take long until I used SQL for stuff I wouldn’t have thought a database could do for me. So I was quickly embracing `group by` and co.\n\nBut I haven’t spent a lot of time with you lately. It’s not because I was too busy. I’m still practicing what you have shown me! And I’ve moved on. Now I’m using [common table expressions](https://en.wikipedia.org/wiki/Hierarchical_and_recursive_queries_in_SQL#Common_table_expression) to organize complex queries and I use [window functions](https://www.postgresql.org/docs/current/tutorial-window.html) to calculate running totals or just do a ranking. I’m also using joins more efficiently because I know about [hash](https://use-the-index-luke.com/sql/join/hash-join-partial-objects) and [sort/merge joins](https://use-the-index-luke.com/sql/join/sort-merge-join). A while ago I was wondering why you didn’t tell me about these things. But then I realized that you don’t know them.\n\n[(Read more)](https://use-the-index-luke.com/blog/2014-04-01/thank-you-mysql-we-will-miss-you)\n\n## [2014-02-20 Results of the SQL Performance Quiz: 60% fail](/blog/2014-02/results-three-minutes-sql-performance-quiz)\n\nIn 2011, I’ve launched the “[The 3-Minute Test: What do you know about SQL performance.](https://use-the-index-luke.com/3-minute-quiz)” It consists of five questions that follow a simple pattern: each question shows a query/index pair and asks if it demonstrates proper indexing or not. Till today, this test has become one of the most popular features on [Use The Index, Luke](https://use-the-index-luke.com/) and has been completed more than 28,000 times.\n\n#### Note\n\nJust in case you got curious, please be aware that this article is a spoiler. You might want to [do the quiz yourself](https://use-the-index-luke.com/3-minute-quiz) before continuing.\n\nAlthough the quiz was created for educational purposes, I was wondering if I could get some interesting figures out of these 28,000 results. And I think I could. However, there are several things to keep in mind when looking at these figures. First, the quiz uses the surprise factor to catch attention. That means, three questions show cases that look fine, but aren’t. One question does it the other way around and shows an example that might look dangerous, but isn’t. There is only one question where the correct answer is in line with the first impression. Another effect that might affect the significance of the results is that there was no representative selection of participants. Everybody can take the quiz. You can even do it multiple times and will probably get a better result the second time. Just keep in mind that the quiz was never intended to be used for scientific research upon the indexing knowledge in the field. Nevertheless, I think that the size of the dataset is still good enough to get an impression.\n\nBelow I’ll show two different statistics for each question. First, the average rate at which this question was correctly answered. Second, how this figure varies for users of MySQL, Oracle, PostgreSQL and SQL Server databases. In other word, it says if e.g. MySQL users are more knowledgeable about indexing as PostgreSQL users. Spoiler: It’s the other way around. The only reason I’m in the lucky position to have this data is that the test sometimes uses vendor specific syntax. For example, what is `LIMIT` in MySQL and PostgreSQL is `TOP` in SQL Server. Therefore, the participants have to select a database at the beginning so that the questions are shown in the native syntax of that product.\n\n1. [Question 1: Functions in the WHERE Clause](https://use-the-index-luke.com/blog/2014-02/results-three-minutes-sql-performance-quiz#results-q1)\n2. [Question 2: Indexed Top-N Queries](https://use-the-index-luke.com/blog/2014-02/results-three-minutes-sql-performance-quiz#results-q2)\n3. [Question 3: Index Column Order](https://use-the-index-luke.com/blog/2014-02/results-three-minutes-sql-performance-quiz#results-q3)\n4. [Question 4: LIKE Searches](https://use-the-index-luke.com/blog/2014-02/results-three-minutes-sql-performance-quiz#results-q4)\n5. [Question 5a: Index-Only Scan](https://use-the-index-luke.com/blog/2014-02/results-three-minutes-sql-performance-quiz#results-q5a)\n6. [Question 5b: Index Column Order and Range Operators](https://use-the-index-luke.com/blog/2014-02/results-three-minutes-sql-performance-quiz#results-q5b)\n7. [Overall Score: How Many Passed the Test?](https://use-the-index-luke.com/blog/2014-02/results-three-minutes-sql-performance-quiz#overall)\n\n[(Read more)](https://use-the-index-luke.com/blog/2014-02/results-three-minutes-sql-performance-quiz)\n\n## [2014-01-17 Unreasonable Defaults: Primary Key as Clustering Key](/blog/2014-01/unreasonable-defaults-primary-key-clustering-key)\n\nAs you might have noticed—at least if you have read [*SQL Performance Explained*](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-2014-clustering-key-default)—I don’t think clustered indexes are as useful as most people believe. That is mainly because it is just too darn difficult to choose a good clustering key. As a matter of fact, choosing a good—the “right”—clustering key is almost impossible if there are more than one or two indexes on the table. The result is that most people just stick to the default—which is the primary key. Unfortunately, this is almost always the worst possible choice.\n\nIn this article I explain the beast named clustered index and all it’s downsides. Although this article uses SQL Server as demo database, the article is equally relevant for MySQL/MariaDB with InnoDB and the Oracle database when using index-organized tables.\n\n1. [The costs of an extra level of indirection](https://use-the-index-luke.com/blog/2014-01/unreasonable-defaults-primary-key-clustering-key#extra-level-of-indirection)\n2. [How bad is it?](https://use-the-index-luke.com/blog/2014-01/unreasonable-defaults-primary-key-clustering-key#logical-io)\n3. [Who cares about logical reads anyway](https://use-the-index-luke.com/blog/2014-01/unreasonable-defaults-primary-key-clustering-key#cpu)\n4. [What was the upside of clustered indexes again?](https://use-the-index-luke.com/blog/2014-01/unreasonable-defaults-primary-key-clustering-key#pro-clustered-index)\n5. [Concluding: How many clustered indexes can a SQL Server table have?](https://use-the-index-luke.com/blog/2014-01/unreasonable-defaults-primary-key-clustering-key#trick-question)\n\n[(Read more)](https://use-the-index-luke.com/blog/2014-01/unreasonable-defaults-primary-key-clustering-key)\n\n## [2013-10-01 MongoDB is to NoSQL like MySQL to SQL — in the most harmful way](/blog/2013-10/mysql-is-to-sql-like-mongodb-to-nosql)\n\n#### Translations\n\nA Japanese translation of this article is available [here](https://yakst.com/ja/posts/74).\n\nYesterday evening I tweeted: “[MongoDB seems to be as Bad for NoSQL as MySQL is for SQL.](https://x.com/MarkusWinand/status/384739280465043456)” Unfortunately, I tweeted without context. But I guess I couldn’t have given all the required context in a single tweet anyway, so I’m dedicating this post to it. I hope this answers [some](https://x.com/tomtom62/status/384892908123717632) [of the](https://x.com/HuttHuttnDaButt/status/384900662418358272) [questions](https://x.com/lexachebara/status/384923601834496000) I’ve got in response to the tweet.\n\nFirst of all, I think everybody should know that I’m not a NoSQL fanboy, yet I’m open to the [polyglot persistence](https://www.martinfowler.com/bliki/PolyglotPersistence.html) idea. This distinction doesn’t seem to make sense if you read NoSQL as “not only SQL” (as you are supposed to do). However, I believe there are NoSQL systems out there that greatly benefit from the idea that SQL is bad and not using SQL is good. On other words, they offer “not using SQL” as their main advantage. MongoDB seems to be one of them. Just my perception.\n\nBut if I don’t like NoSQL, then I should like MySQL? Not exactly. In my eyes, MySQL has done great harm to SQL because many of the problems people associate with SQL are in fact just MySQL problems. One of the more important examples is that MySQL is rather poor at joining because is only supports [nested loops joins](https://use-the-index-luke.com/sql/join/nested-loops-join-n1-problem). Most other SQL database implement the [hash join](https://use-the-index-luke.com/sql/join/hash-join-partial-objects) and [sort/merge join](https://use-the-index-luke.com/sql/join/sort-merge-join) algorithms too—both deliver better performance for non-tiny data sets. Considering the wide adoption of MySQL (“The most popular open source database”) and the observation that many people move away from SQL because “joins are slow,” it isn’t far-fetched to say that an implementation limitation of MySQL pushes people towards NoSQL.\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-10/mysql-is-to-sql-like-mongodb-to-nosql)\n\n## [2013-08-25 Don’t ask for what you don’t need](/blog/2013-08/its-not-about-the-star-stupid)\n\n`select *` has a bad reputation. Most people think it is because changes in the table definition cause hard-to-detect bugs. Listing all columns in the desired order solves that problem, right? Yes, but that doesn’t solve the second problem of `select *`.\n\nThe other problem is that asking for more columns causes more work for the database. The surprise is that the performance impact can be huge.\n\nUp to 100x slower when preventing an Index-Only Scan\n\nBroadly speaking, the less columns you ask for, the less data must be loaded from disk when processing your query. However, this relationship is *non-linear*.Quite often, selecting from a table involves two steps: (1) use an index to find the address where the selected rows are stored; (2) load the selected rows from the table. Now imagine that you are just selecting columns that are present in the index. Why should the database still perform the second step? In fact, most databases don’t. They can process your query just with the information stored in the index—hence [index-only scan](https://use-the-index-luke.com/sql/clustering/index-only-scan-covering-index).But why should an index-only scan be 100 times faster? Simple: an ideal index stores the selected rows next to each other. It’s not uncommon that each index page holds about 100 rows—a ballpark figure; it depends on the size of the indexed columns. Nonetheless, it means that one IO operation might fetch 100 rows. The table data, on the other hand, is not organized like that ([exceptions](https://use-the-index-luke.com/sql/clustering/index-organized-clustered-index)). Here it is quite common that a page just contains one of the selected rows—along with many other rows that are of no interest for the particular query. So, the reason an Index-Only Scan can be 100 times faster is that an index access can easily deliver 100 rows per IO while the table access typically just fetches a few rows per IO.If you select a single column that’s not in the index, the database cannot do an index-only scan. If you select all columns, … , well I guess you know the answer.Further, some databases store large objects in a separate place (e.g., LOBs in Oracle). Accessing those causes an extra IO too.\n\nUp to 5x slower when bloating server memory footprint\n\nAlthough databases avoid storing the result in the server’s main memory—instead they deliver each row after loading and forget about it again—it is sometimes inevitable. Sorting, for example, needs to keep all rows—and all selected columns—in memory to do the job. Once again, the more columns you select, the more memory the database needs. In the worst case, the database might even need to do an external sort on disk.However, most database are extremely well tuned for this kind of workload. Although I’ve seen a sorting speed-up of factor two quite often—just by removing a few unused columns—I cannot remember having got more than factor five. However, it’s not just sorting, [hash joins](https://use-the-index-luke.com/sql/join/hash-join-partial-objects) are rather sensitive to memory bloat too. Don’t know what that is? Please read [this article](https://use-the-index-luke.com/sql/join/hash-join-partial-objects).\n\nThese are just the two top issues from database perspective. Remember that the network suffers too and that the client needs to process the data as well—which might put a considerable pressure on garbage collection.\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-08/its-not-about-the-star-stupid)\n\n## [2013-08-13 Try it online!](/blog/2013-08/try-online-at-sqlfiddle)\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-08/try-online-at-sqlfiddle)\n\n## [2013-07-26 2017-10-25 About Optimizer Hints: Prefer supportive and avoid restrictive SQL hints](/blog/2013-07/about-query-optimizer-hints)\n\nQuite often I’m asked what I think about query hints. The answer is more lengthy and probably also more two-fold than most people expect it to be. However, to answer this question once and forever, I though I should write it down.\n\nThe most important fact about query hints is that not all query hints are born equally. I distinguish two major types:\n\nRestricting Hints\n\nMost query hints are restricting hints: they limit the optimizers’ freedom to choose an execution plan. “Hint” is an incredibly bad name for these things as they *force* the optimizer to do what it has been told—probably the reason MySQL uses the [`FORCE`](https://dev.mysql.com/doc/refman/8.0/en/index-hints.html) keyword for those.I do not like restricting hints, yet I use them sometimes to test different execution plans. It usually goes like this: when I believe a different execution plan could (should?) give better performance, I just hint it to see if it really gives better performance. Quite often it becomes slower and sometimes I even realize that the execution plan I though of does not work at all—at least not with the database I’m working on at that moment.Typical examples for restricting query hints are hints that force the database to use or not to use a particular index (e.g., [`INDEX` and `NO_INDEX`](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Comments.html#GUID-EC0D9F8A-20E7-4281-A16A-6B9C993F2930) in the Oracle database, [`USE INDEX` and `IGNORE INDEX`](https://dev.mysql.com/doc/refman/8.0/en/index-hints.html) in MySQL, or [`INDEX`, `FORCESEEK` and the like](https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table) in SQL Server).So, what’s wrong with them? Well, the two main problems are that they (1) restrict the optimizer and that they (2) often need volatile object names as parameters (e.g., index names). Example: if you use a hint to use index `ABC` for a query, the hint becomes ineffective when somebody changes the name of the index to `ABCD`. Further, if you restrict the optimizer you can no longer expect it to adjust the execution plan if you add another index that servers the query better. Of course there are ways around these problems. The Oracle database, for example, offers [“index description” hints](https://jonathanlewis.wordpress.com/2013/06/23/index-hints-2/) to avoid both issues: instead of specifying the index name, it accepts a description of the ideal index (column list) and it selects the index that matches this definition best.Nevertheless, I strongly recommend against using restricting query hints in production. Instead you should find out why the optimizer does “the wrong thing”™ and fix the root cause. Restricting hints fix the symptom, not the cause. That being said, I know that there is sometimes no other reasonable choice.\n\nSupporting Hints\n\nThe second major type of query hints are supporting hints: they support the optimizer by providing information it doesn’t have otherwise. Supporting hints are rare—I’m only aware of a few good examples and the most useful one has already become obsolete: it’s [`FAST` *number_rows*](https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-query) (SQL Server) and [`FIRST_ROWS(n)`](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Comments.html#GUID-CEA66568-0168-4AE2-AD3B-FE86CDD73894) (Oracle). They tell the optimizer that the application plans to fetch only that many rows of the result. Consequently, the optimizer can prefer using indexes and nested loop joins that would be inefficient when fetching the full result (see [Chapter 7, Partial Results](https://use-the-index-luke.com/sql/partial-results) for more details). Although being kind-of obsolete, I’m still using these hints as the defining example for supporting hints because they provide information the optimizer cannot have otherwise. This particular example is important enough that it was worth defining new keywords in the ISO SQL:2008: `FETCH FIRST ... ROWS ONLY` and `OFFSET`. That’s why this hint is a very good, yet obsolete example for supporting query hints.Another example for supporting hints is the (undocumented) `CARDINALITY` hint of the Oracle database. It basically overwrites the row count estimate of sub-queries. This hint was often used if the combined selectivity of two predicates was way off the product of the selectivity of each individual predicate (see [*Combined Selectivity Example*](https://use-the-index-luke.com/blog/2013-07/about-query-optimizer-hints#sb-combined-selectivity)). But this hint is also outdated since Oracle database 11g introduced [extended statistics](https://blogs.oracle.com/optimizer/extended-statistics) to cope with issues like that. SQL Server’s [filtered statistics](https://learn.microsoft.com/en-us/archive/blogs/psssql/case-of-using-filtered-statistics) serve the same purpose. If your database cannot reflect data correlation in it’s statistics, you’ll need to fall back to restricting hints.The Oracle hint `OPT_ESTIMATE` is somehow the successor of the `CARDINALITY` hint for cases when the estimations are still off. Pythian wrote a [nice article about `OPT_ESTIMATE`](https://www.pythian.com/blog/oracles-opt_estimate-hint-usage-guide).Combined Selectivity ExampleLet’s say we have two Y/N columns and each has a 50:50 distribution. When you select using both columns most optimizers estimate that the query matches 25% of the table (by multiplying two times 50%). That means that the optimizer assumes there is no correlation between those two columns.Column 1Column 2count(*)YY25YN25NY25NN25If there is a correlation, however, so that most rows that have Y in one column also have Y in the other column, then the estimate is way off.Column 1Column 2count(*)YY49YN1NY1NN49If you query one of the rare Y/N combinations, the optimizer might refrain from using an index due to the high cardinality estimate. Nevertheless, it would be better to use the index because this particular combination is very selective.\n\nIt think supporting hints are not that bad: they are just a way to cope with known limitations of the optimizer. That’s probably why they tend to become obsolete when the optimizers evolve.\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-07/about-query-optimizer-hints)\n\n## [2013-07-18 Pagination Done the Right Way](/blog/2013-07/pagination-done-the-postgresql-way)\n\nHere is another slide deck for my “Pagination Done the Right Way” talk that I’ve given at many occasions.\n\nPlease also have a look at this blog post by Cary Millsap about “[The Ramp](https://carymillsap.blogspot.com/2010/04/ramp.html)”. Do you see how using OFFSET implements this anti-pattern?\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-07/pagination-done-the-postgresql-way)\n\n## [2013-07-10 Indexes: The neglected performance all-rounder](/blog/2013-07/indexes-the-neglected-performance-all-rounder)\n\nI think I’ve actually never shared the slides of my talk given in Paris at [Dalibo’s](https://dalibo.com/) PostgreSQL Session about Performance. So, here they are.\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-07/indexes-the-neglected-performance-all-rounder)\n\n## [2013-07-02 Afraid of SSD? Will SSD kill the profession of database and SQL tuning specialists?](/blog/2013-07/afraid-of-ssd)\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-07/afraid-of-ssd)\n\n## [2013-05-21](/blog/2013-05/training-and-conference-dates)\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-05/training-and-conference-dates)\n\n## [2013-04-23 The two top performance problems caused by ORM tools](/blog/2013-04/the-two-top-performance-problems-caused-by-ORM-tools)\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-04/the-two-top-performance-problems-caused-by-ORM-tools)\n\n## [2013-04-22 I need your help!](/blog/2013-04/i-need-your-help)\n\nHi!\n\nWould you please spare me a few minutes and help me a little bit?\n\nAs you might know—or maybe not—I’m making my living as an *independent* trainer and consultant. Up till now I’ve only delivered on-site training at the clients’ site, but I though it makes sense to offer open trainings as well so that singe participants can also join. For that I’d need to know how many people would like to join such a training, where they are physically located, and which database they are using. So, I’ve set up a short survey:\n\n[http://winand.at/services/sql-performance-training/survey](https://winand.at/sql-training/inhouse)\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-04/i-need-your-help)\n\n## [2013-03-04](/blog/2013-03/Party-Time)\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-03/Party-Time)\n\n## [2013-02-22](/blog/2013-02/better-performance-with-postgresql-conference)\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-02/better-performance-with-postgresql-conference)\n\n## [2013-02-05 Top Tweets January 2013](/blog/2013-02/top-tweets)\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-02/top-tweets)\n\n## [2013-02-05 FOSDEM Impressions](/blog/2013-02/fosdem-impressions)\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-02/fosdem-impressions)\n\n## [2013-01-08 I’m speaking at FOSDEM PGDay 2013](/blog/2013-01/fosdem-pgday)\n\n[(Read more)](https://use-the-index-luke.com/blog/2013-01/fosdem-pgday)\n\n## [2012-12-28 Top Tweets December 2012](/blog/2012-12/top-tweets)\n\n[(Read more)](https://use-the-index-luke.com/blog/2012-12/top-tweets)\n\n## [2012-12-19 French anybody? Use The Index, Luke is now available in French.](/blog/2012-12/french-anybody)\n\n[(Read more)](https://use-the-index-luke.com/blog/2012-12/french-anybody)\n\n## [2012-12-06 Instant What?](/blog/2012-12/instant-what)\n\nYou might guess it, but I’m not making my living from this site nor are the book sales paying all the bills—although the books pays some bills, thank you! However, to pay the remaining bills I’m doing coaching, training and consulting. You can find all the details on my professional site [http://winand.at/](https://winand.at/) but I’d like to highlight one service here: [Instant Coaching](https://winand.at/sql-expert-teammate-on-demand).\n\nAfter googling and trying many ways to solve a problem, have you ever got that feeling of resignation where you just want to ask somebody who should know the answer? Well, that’s Instant Coaching—at least if your problem is about performance and/or databases.\n\nInstant Coaching is remarkably easy and efficient: we just arrange an online meeting where you present your problem or question to me. We’ll use a desktop sharing tool ([TeamViewer](https://www.teamviewer.com/en/)) so that I can see your screen and—if you like—show you something on your computer (control your mouse/keyboard). Instant Coaching needs virtually no preparation: it often starts just a few minutes after you faced the problem—hence “Instant”!\n\nAnother critical success factor for Instant Coaching is that we can put our knowledge and experiences together: you bring the know-how about your application and your data while I’m adding a little database and performance know-how to the mix. Instead of guessing about things I don’t know about your application or you don’t know about databases, we can just ask each other! I’m usually getting asked a lot: you don’t just get the “magic” solution, but you learn about the rational behind it so that can solve similar problems on your own the next time—hence “Coaching”!\n\n[(Read more)](https://use-the-index-luke.com/blog/2012-12/instant-what)\n\n## [2012-11-15](/blog/2012-11/joe-celko-reviews-sql-performance-explained)\n\n[(Read more)](https://use-the-index-luke.com/blog/2012-11/joe-celko-reviews-sql-performance-explained)\n\n## [2012-11-13 PG.Conf EU 2012 — Summary](/blog/2012-11/pgconfeu2012-summary)\n\nWith a little delay of just three weeks, I’m writing something about this years PostgreSQL conference Europe.\n\nIncluding the training day, it was four days full of database stuff—in other terms: an awesome time, if you love databases :) But let’s start from the beginning.\n\nI booked the full day training with [Joe Celko](https://www.postgresql.eu/events/pgconfeu2012/schedule/speaker/119-joe-celko/) on the first day. And I must say that was the best part of the conference—mostly because Joe is great. If you never meet Joe Celko, or don’t even know who the heck he is, you should definitely look for an opportunity to meet him.\n\nThe training he gave (“A day of SQL with Celko”) was a mixture of SQL related topics like keys, naming (e.g., plurals for tables), metadata, rollup (`group by grouping sets`, `group by cube`) and trees. Due to my day to day work, I’ve already seen some of the “rarely known features” he mentioned. It was still very valuable because he presented good examples for them. The “[nested sets model](https://en.wikipedia.org/wiki/Nested_set_model)” is particularly noteworthy. I hope to write about some of these topics soon.\n\n[(Read more)](https://use-the-index-luke.com/blog/2012-11/pgconfeu2012-summary)\n\n## [2012-10-12](/blog/2012-10/discount_codes_you_missed_without_twitter)\n\n[(Read more)](https://use-the-index-luke.com/blog/2012-10/discount_codes_you_missed_without_twitter)\n\n## [2012-10-08 My PGConf.EU 2012 Schedule](/blog/2012-10/PGConf.EU_2012_Schedule)\n\nAs mentioned before, I’ll be at [this year PostgreSQL Conference in Prague](https://2012.pgconf.eu/). Still two weeks to go, but I just had a few minutes “free” time and prepared my personal schedule.\n\nAs usual, I plan to attend as many sessions as possible. As usual, I’ll skip some in favour of a nice chat and/or change my mind in the last moment.\n\n[(Read more)](https://use-the-index-luke.com/blog/2012-10/PGConf.EU_2012_Schedule)\n\n## [2012-08-13 Second Anniversary](/blog/2012-08/second-anniversary)\n\n“Use The Index, Luke!” celebrates its second anniversary today. Unfortunately, I was not able to prepare anything for this anniversary like I did last year when I presented the [3-minute quiz.](https://use-the-index-luke.com/3-minute-quiz) The test is still very popular, by they way, it is taken about 20 times a day. However, all I have for this years anniversary is a promise.\n\nDo you know [http://sqlfiddle.com/](https://sqlfiddle.com)? You should ;) It’s an online tool to test SQL queries with five different databases (SQL Server, MySQL, Oracle, PostgreSQL and SQLite). It is not a cloud database that you could use for building applications. SQLFiddle is a tool for collaborative online work on SQL problems. It was built to improve asking and solving SQL related questions on Q/A sites like Stackoverflow.\n\nFor me, SQL Fiddle is interesting because of the “View Execution Plan” Button. As said before, it is not a cloud DB that we could use for performance tests, but we can have a look at executions plans. I believe it would be very convenient to have prepared fiddles for the examples from “Use The Index, Luke!” so that you can easily test them online without needing your own database.\n\nAnd this is exactly what will come—although I don’t have a time line yet. Stay tuned. **UPDATE in 2015**: SQLFiddle integration will be removed again because it it hardly used but causes a lot of overhead on my side.\n\n[(Read more)](https://use-the-index-luke.com/blog/2012-08/second-anniversary)\n\n## [2012-08-13 Convinced](/blog/2012-09/convinced-pdf-and-bundle-sales)\n\nAfter publishing the English edition of “SQL Performance Explained” there was a huge demand for an ebook edition. After a few days answering these queries, I though it’s probably easier to offer an e-book than to explain why there isn’t one. Well, I must admit that I don’t read ebooks very much. My wife has an e-ink device, but is hardly using it (probably in lack of German content). I’ve uploaded the ePUB pre-release from 2011 (not available anymore) and must say it works, but isn’t nice. However, many people told me they would be fine with a PDF, because they are anyway using tablets or smartphones to read their ebooks. Fast forward a few weeks: since Monday I can offer a PDF download for just EUR 9.95 (English, German [update] or French, you choose).\n\nAfterwards there was a huge demand—again—for a bundle discount when purchasing both, the PDF and the hard copy. That caught me by surprise. Not that people want a discount, but that people would like to buy both editions. So I asked, and listened, and learned something about my own business.\n\nSure there were usual suspected like “I’d just like the PDF for searching” “to have it with me when being on the road” and so forth. But the interesting point was “I’d like the hard copy, but would also like to start reading immediately.” Well, I didn’t think of that (shame on me). Although I’m offering free shipping to 150+ countries, it takes its time because I’m shipping from Europe only [once a week](https://use-the-index-luke.com/blog/2012-08/finally-almost-world-wide-free-shipping). Instead of express delivery, I just need to offer a bundle.\n\nIt took another day to tweak my accounting software because there are different VAT rates applied to real books and PDF downloads—but the accounting software could do only one VAT rate for each invoice. After all I’m just a geek like most of you, so I hacked a day and made it work. [The bundle is on sale for EUR 34.95](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-2012-ebook) since yesterday evening—that’s a EUR 4.95 discount.\n\n[(Read more)](https://use-the-index-luke.com/blog/2012-09/convinced-pdf-and-bundle-sales)\n\n## [2012-08-12](/blog/2012-08/customs-and-well-errata)\n\n[(Read more)](https://use-the-index-luke.com/blog/2012-08/customs-and-well-errata)\n\n## [2012-08-08 Finally: Almost World-Wide Free Shipping](/blog/2012-08/finally-almost-world-wide-free-shipping)\n\nThe English edition of “[SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-2012-free-shipping)” is finally available. It has its own website [http://sql-performance-explained.com/](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-2012-free-shipping) where you can find a [PDF preview](https://sql-performance-explained.com/img/9783950307825_preview.pdf?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-2012-free-shipping) and order information. The cover price is EUR 29.95 or GBP 26.99.\n\nIf you order it from outside the EU, you must also consider that you might be required to pay import duties in the destination country.\n\nKnowing that I have readers all over the world, I’ve spent a fair amount of time to make world-wide free shipping possible. I almost succeeded. If you use the [direct order form](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-2012-free-shipping) I’ll be able to offer free shipping to 150+ countries. However, this is only possible when using a volume discount offered by the Austrian postal service. Therefore, I’ll dispatch international orders only once a week.\n\n[SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-2012-free-shipping)\n\n[(Read more)](https://use-the-index-luke.com/blog/2012-08/finally-almost-world-wide-free-shipping)\n\n## [2012-05-25 Done! Or What?](/blog/2012-05-25/done-or-what)\n\nDuring the last few weeks, it has become a little silent here at *Use The Index, Luke!* Today, I’d like to tell you the news that caused the silence and give a short outlook about the future of *Use The Index, Luke!*\n\n[(Read more)](https://use-the-index-luke.com/blog/2012-05-25/done-or-what)\n\n## [2011-08-13 One Year and Three Minutes](/blog/2011-08-13/one-year-and-three-minutes)\n\nUse The Index, Luke! was one today.\n\nThere was quite some progress during this year. Besides the steadily growing content, I am particularly happy that the appendices about [execution plans](https://use-the-index-luke.com/sql/explain-plan) and the [example schema](https://use-the-index-luke.com/sql/example-schema) cover MySQL, PostgreSQL and SQL Server in addition to Oracle.\n\nBut what’s next?\n\nThe content will be completed until early 2012 (final outline in the [Preface](https://use-the-index-luke.com/sql/preface)). The second volume of [SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=&utm_medium=web&utm_content=blog-one-year)—the e-book edition—will be published at that time as well. Additionally, Use The Index, Luke! will be translated gradually into German.\n\n[(Read more)](https://use-the-index-luke.com/blog/2011-08-13/one-year-and-three-minutes)\n\n## [2011-07-30 MySQL Row Generator](/blog/2011-07-30/mysql-row-generator)\n\n#### Update 2017-05-23\n\nMariaDB 10.2 introduced support for common table expressions.\n\n#### Update 2018-04-19\n\nMySQL 8.0 introduced support for common table expressions.\n\nA row generator is a method to generate numbered rows on demand. It is possible to build a row generator with pure standard SQL—using recursive [common table expressions (CTE)](https://modern-sql.com/feature/with), the `with` clause. If you never heard of the `with` clause, it’s probably because MySQL doesn’t implement that specific part of the SQL-99 standard ([feature request from 2006](https://bugs.mysql.com/bug.php?id=16244)). This article introduces generator views for MySQL. Not as powerful as recursive CTEs, but good enough in most cases. But before going into the implementation details, I’ll show you a use case for a row generator.\n\nRow generators are useful to fill gaps in results. Consider the following query:\n\n[(Read more)](https://use-the-index-luke.com/blog/2011-07-30/mysql-row-generator)\n\n## [2011-07-16 Planning For Reuse](/blog/2011-07-16/planning-for-reuse)\n\n[(Read more)](https://use-the-index-luke.com/blog/2011-07-16/planning-for-reuse)\n\n## [2011-06-24](/blog/2011-06-24/dear-database-vendors)\n\n[(Read more)](https://use-the-index-luke.com/blog/2011-06-24/dear-database-vendors)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 58518, "slov": 8282, "odkazu": 284, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:43", "sha256": "0ecd37fb44b831d41b3375c5fb397c304fa927fbcc7ab449c422dd179252dba6", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "http://www.postgres.cn/v2/news/viewone/1/521", "https://davat.dev/%D9%86%DA%AF%D8%A7%D9%87%DB%8C-%D8%B9%D9%85%D9%82%DB%8C-%D8%A8%D9%87-%D8%B9%D8%A8%D8%A7%D8%B1%D8%AA-include-%D8%AF%D8%B1-%D8%A7%DB%8C%D9%86%D8%AF%DA%A9%D8%B3%D9%87%D8%A7/", "https://modern-sql.com/blog/2018-04/mysql-8.0", "https://winand.at/newsletter/2018-07/sql-over-the-cloud-fsyncgate", "https://modern-sql.com/", "https://modern-sql.com/feed", "https://winand.at/lists", "https://winand.at/sql-training/5-day-training/aug-sept-2018", "https://sql-performance-explained.com/", "https://winand.at/events", "https://modern-sql.com/concept/three-valued-logic", "https://sql-performance-explained.de/", "https://sql-au-coeur-des-performances.fr/", "https://sql-performance-explained.jp/", "https://rendimiento-sql-explicado.es/", "https://rendimiento-sql-explicado.es/r/local-amazon", "https://pgsqldeepdive.blogspot.com/2016/08/on-ubers-choice-of-databases-uber.html", "https://www.infoq.cn/article/the-database-selection-of-uber/", "https://www.uber.com/blog/postgres-to-mysql-migration/", "https://archive.fosdem.org/2015/schedule/event/modern_sql_in_postgresql/", "https://x.com/beschl/status/561858608619864064", "https://winand.at/sql-training/inhouse", "https://x.com/dblmkt", "https://x.com/matsuu", "https://rafael.bernard-araujo.com/precisamos-de-apoio-das-ferramentas-para-a-paginacao-por-conjunto-de-chaves.php", "https://habr.com/ru/companies/tbank/articles/485036/", "https://www.chrissaxon.co.uk/", "https://www.pgcon.org/2014/", "https://sqlite.com/", "https://www.derstandard.at/consent/tcf/1381368486902/Was-bleibt-von-NoSQL", "https://www.theregister.com/software/2013/08/30/google-goes-back-to-the-future-with-sql-f1-database/937689", "https://research.google/pubs/mapreduce-simplified-data-processing-on-large-clusters/", "https://research.google/pubs/bigtable-a-distributed-storage-system-for-structured-data/", "https://en.wikipedia.org/wiki/Struct_(C_programming_language)", "https://en.wikipedia.org/wiki/Hierarchical_and_recursive_queries_in_SQL", "https://www.postgresql.org/docs/current/tutorial-window.html", "https://yakst.com/ja/posts/74", "https://x.com/MarkusWinand/status/384739280465043456", "https://x.com/tomtom62/status/384892908123717632", "https://x.com/HuttHuttnDaButt/status/384900662418358272", "https://x.com/lexachebara/status/384923601834496000", "https://www.martinfowler.com/bliki/PolyglotPersistence.html", "https://dev.mysql.com/doc/refman/8.0/en/index-hints.html", "https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Comments.html", "https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table", "https://jonathanlewis.wordpress.com/2013/06/23/index-hints-2/", "https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-query", "https://blogs.oracle.com/optimizer/extended-statistics", "https://learn.microsoft.com/en-us/archive/blogs/psssql/case-of-using-filtered-statistics", "https://www.pythian.com/blog/oracles-opt_estimate-hint-usage-guide", "https://carymillsap.blogspot.com/2010/04/ramp.html", "https://dalibo.com/", "https://winand.at/", "https://winand.at/sql-expert-teammate-on-demand", "https://www.teamviewer.com/en/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/speaker/119-joe-celko/", "https://en.wikipedia.org/wiki/Nested_set_model", "https://2012.pgconf.eu/", "https://sqlfiddle.com/", "https://sql-performance-explained.com/img/9783950307825_preview.pdf", "https://modern-sql.com/feature/with", "https://bugs.mysql.com/bug.php?id=16244", "https://bsky.app/profile/winand.at", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2011-06-24/dear-database-vendors", "titulek": "Dear Database Vendors: Please fix these issues in your product", "h1": "Dear Database Vendors", "popis": "Wrong NULL handling, writers blocking readers, unnecessary table access and slow joins.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2011-06-24/dear-database-vendors", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Dear Database Vendors: Please fix these issues in your product", "og:description": "Wrong NULL handling, writers blocking readers, unnecessary table access and slow joins.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Dear Database Vendors"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Dear Database Vendors\n\n---\n\nI have one wish for each database. Some of them are big wishes, so I thought I’ll better send them early. Only six month until Christmas, you know ;)\n\nOracle\n\n[`'' IS NULL?`](/sql/where-clause/null) Are you serious? I know, it [has always been that way](/sql/where-clause/null), but does that mean it will stay so forever?\n\nSQL Server\n\nCould you please enable [`READ_COMMITTED_SNAPSHOT`](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms177404(v=sql.105)) per default? Or, at least, make it a mandatory question during database creation? That could prevent so many [locking problems](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms177404(v=sql.105)).\n\nPostgreSQL\n\nCould you please implement [index-only scans](/sql/clustering/index-only-scan-covering-index) (aka “covering indexes”)? It’s a great performance feature, which I really miss in PostgreSQL.**UPDATE**: This one became true with [PostgreSQL 9.2](https://www.postgresql.org/docs/9.2/release-9-2.html).\n\nMySQL\n\nCould you please implement the [hash join](/sql/join/hash-join-partial-objects) algorithm? So many applications suffer from poor join performance, just because MySQL doesn’t have hash joins.**UPDATE**: This one became true with [MySQL 8.0.18](https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-18.html).\n\nFrom today’s perspective, it looks like my PostgreSQL wish is the only one that might come true. But I’ll keep hoping for the others as well.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2104, "slov": 277, "odkazu": 57, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:54", "sha256": "a5f6de9cc0e1a21c04752450966a2feb049a9a7b61e3be0282d687722b187ba5", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms177404(v=sql.105)", "https://www.postgresql.org/docs/9.2/release-9-2.html", "https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-18.html", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2011-07-16/planning-for-reuse", "titulek": "Planning For Reuse: Plan Caches vs bind-peeking and parameter sniffing.", "h1": "Planning For Reuse", "popis": "FAQ on execution plan caches in Oracle, SQL Server, PostgreSQL, Db2 (LUW) and MySQL. Bind-peeking and parameter sniffing.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2011-07-16/planning-for-reuse", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Planning For Reuse: Plan Caches vs bind-peeking and parameter sniffing.", "og:description": "FAQ on execution plan caches in Oracle, SQL Server, PostgreSQL, Db2 (LUW) and MySQL. Bind-peeking and parameter sniffing.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Planning For Reuse"}, {"uroven": 4, "text": "If you like this page, you might also like …"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Planning For Reuse\n\n---\n\nThere was a discussion about bind parameters and execution plan caching in a recent [reddit thread](https://www.reddit.com/r/programming/comments/ij0px/the_smartest_way_to_make_sql_slow/) about my “[Avoid Smart Logic for Conditional `WHERE` clauses](/sql/where-clause/obfuscation/smart-logic)” page. My article mentions that bind variables make the actual values “invisible” for the optimizer resulting in a generic plan that can be cached and re-used later on. [Jeff Davis](http://thoughts.davisjeff.com/about/) emphasized that using bind parameters and the caching of execution plans are two distinct concepts and provided a [PostgreSQL/Ruby example](http://thoughts.davisjeff.com/2011/07/09/building-sql-strings-dynamically-in-2011//) for that.\n\nIt took a week, but I can finally present my findings on that topic. The original article is already updated, but I think it is worth presenting it in a different form as well—like a FAQ:\n\nWhat is an execution plan cache?\n\nAn execution plan cache reduces load by caching prepared execution plans. If the same statement is executed later on, the plan can be re-used without the optimization overhead.\n\nWhich databases use an execution plan cache?\n\nDb2 (LUW), Oracle and SQL Server use shared execution plan caches. That means an execution plan used in one session can be re-used by another sessions.PostgreSQL potentially caches query plans as long as the prepared statement is open. See: [PREPARE in the PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-prepare.html#SQL-PREPARE-NOTES).MySQL has no execution plan cache (don’t confuse with [Query [Result] Cache)](https://dev.mysql.com/doc/refman/8.0/en/mysql-nutshell.html#mysql-nutshell-removals).\n\nWhat has that to do with bind parameters?\n\nThe shared execution plan caches of Db2 (LUW), Oracle and SQL Server use a hash value of the literal SQL string as key to the cache. Cached plans are not found if the SQL contains literal values that vary with each execution.Place holders (bind parameters) unify the statement so that the SQL string is identical when executed with different values—thus, increasing the cache-hit rate.\n\nLiteral values in SQL kind of disable execution plan re-use?\n\nIn principle yes. However, there are so many applications that don’t use bind variables that database vendors built a workaround: they can turn literal values to placeholder expressions.That means that there is a thin layer in the database that looks at every SQL string, checks for literals and transforms them to bind parameters before checking the execution plan cache. This feature is called [`PARAMETERIZATION`](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175037(v=sql.105)) in SQL Server. It defaults to simple—only the “simple” statements are automatically transformed to use bind parameters. The corresponding Oracle feature is [`CURSOR_SHARING`](https://docs.oracle.com/en/database/oracle/oracle-database/19/refrn/CURSOR_SHARING.html). It defaults to `EXACT` which means that no magic is applied to the SQL strings.\n\nWhat’s the downside of execution plan re-use?\n\nExecution plan caches use the SQL string as key. Same SQL string, same execution plan. That means that the optimizer must plan for re-use. It cannot assume anything about the bind values used for later executions. The smart logic approach makes that quite obvious. The following cannot optimized “away” when planning for re-use:`(last_name = :name OR :name IS NULL)`Besides that, the optimizer doesn’t consider column histograms when planning for re-use.\n\nWhat are the vendors doing about it?\n\nOracle uses *bind peeking* and introduced [adaptive cursor sharing](/sql/where-clause/bind-parameters#sb-cursorsharing) with 11g. SQL Server uses *parameter sniffing* and [query hints](/sql/where-clause/obfuscation/smart-logic#smart_logic_affected). Db2 (LUW) has the [re-optimizing hint `REOPT`](/sql/where-clause/obfuscation/smart-logic#smart_logic_affected).The hint based approaches will essentially disable execution plan re-use for the respective statement. Oracle’s adaptive cursor sharing supports multiple execution plans per SQL string and learns from slow executions.\n\nCan we have both: plan re-use and well optimized queries?\n\nSure. Disable parametrization magic, use bind parameters and write dynamic SQL for conditional filters.Explicitly using bind parameters solves three problems at once: (1) SQL injection, (2) execution plan cache-hit rate and (3) having manual control to utilize histograms—the [exception for bind parameters](/sql/where-clause/bind-parameters#tip-literals-for-histograms). Dynamic SQL will automatically lead to well optimized execution plans for conditional filters.\n\nBut concatenating SQL fragments is ugly!?!\n\nYes, it is—especially when using bind parameters. It is often not possible to provide bind values before the SQL string was passed to the database abstraction layer. That means that all the conditions need to be repeated.Many ORM tools have a query builder that simplifies dynamic SQL a little. Some [examples are available in the appendix](/sql/myth-directory/dynamic-sql-is-slow#myth-dynamic-sql-sample).\n\n#### If you like this page, you might also like …\n\n… to [subscribe my **mailing lists**](https://winand.at/lists), [get **free stickers**](https://use-the-index-luke.com/shop), [buy **my book**](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-planning-for-reuse&utm_medium=web) or [join a **training**](https://winand.at/sql-training/open-online-class).\n\nShould we [Build SQL Strings Dynamically in 2011](http://thoughts.davisjeff.com/2011/07/09/building-sql-strings-dynamically-in-2011/), as Jeff Davis asked?\n\nThere is, in theory, no benefit from dynamic SQL if the optimizer doesn’t plan for re-use. But it won’t hurt either—except if code gets ugly. However, the problem is that there is no standard way to put an optimizer into a “*disposal mode*” that doesn’t plan for re-use. PostgreSQL has a [proprietary API solution](/sql/explain-plan/postgres/concrete-planning), SQL Server has a hint that was [buggy even in 2008 R2](https://www.sommarskog.se/dyn-search-2008.html#SPandCUs). Db2 (LUW) has a different hint seems to work since years. Oracle doesn’t give control over “execution plan recycling” ([workaround](https://oracle-randolf.blogspot.com/2009/02/how-to-force-hard-parse.html)), MySQL never plans for re-use.\n\nHowever, all of that is irrelevant if you use dynamic SQL for conditional filters. That just works. Always.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 7134, "slov": 988, "odkazu": 70, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:55", "sha256": "6888def76ca47adf60895441db3a458c631ca25415f991459c6fb3eb9bfaf2c7", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://www.reddit.com/r/programming/comments/ij0px/the_smartest_way_to_make_sql_slow/", "http://thoughts.davisjeff.com/about/", "http://thoughts.davisjeff.com/2011/07/09/building-sql-strings-dynamically-in-2011//", "https://www.postgresql.org/docs/current/sql-prepare.html", "https://dev.mysql.com/doc/refman/8.0/en/mysql-nutshell.html", "https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175037(v=sql.105)", "https://docs.oracle.com/en/database/oracle/oracle-database/19/refrn/CURSOR_SHARING.html", "https://winand.at/lists", "https://sql-performance-explained.com/", "https://winand.at/sql-training/open-online-class", "http://thoughts.davisjeff.com/2011/07/09/building-sql-strings-dynamically-in-2011/", "https://www.sommarskog.se/dyn-search-2008.html", "https://oracle-randolf.blogspot.com/2009/02/how-to-force-hard-parse.html", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2011-07-30/mysql-row-generator", "titulek": "MySQL Row Generator like generate_series in PostgreSQL — just a simple view compatible with all MySQL versions.", "h1": "MySQL Row Generator", "popis": "Generating rows in MySQL pre 8.0 like GENERATE_SERIES in PostgreSQL", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2011-07-30/mysql-row-generator", "jazyk": "en", "robots_meta": "", "og": {"og:title": "MySQL Row Generator like generate_series in PostgreSQL — just a simple view compatible with all MySQL versions.", "og:description": "Generating rows in MySQL pre 8.0 like GENERATE_SERIES in PostgreSQL", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "MySQL Row Generator"}, {"uroven": 4, "text": "Update 2017-05-23"}, {"uroven": 4, "text": "Update 2018-04-19"}, {"uroven": 4, "text": "If you like this page, you might also like …"}, {"uroven": 4, "text": "Warning"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# MySQL Row Generator\n\n---\n\n#### Update 2017-05-23\n\nMariaDB 10.2 introduced support for common table expressions.\n\n#### Update 2018-04-19\n\nMySQL 8.0 introduced support for common table expressions.\n\nA row generator is a method to generate numbered rows on demand. It is possible to build a row generator with pure standard SQL—using recursive [common table expressions (CTE)](https://modern-sql.com/feature/with), the `with` clause. If you never heard of the `with` clause, it’s probably because MySQL doesn’t implement that specific part of the SQL-99 standard ([feature request from 2006](https://bugs.mysql.com/bug.php?id=16244)). This article introduces generator views for MySQL. Not as powerful as recursive CTEs, but good enough in most cases. But before going into the implementation details, I’ll show you a use case for a row generator.\n\nRow generators are useful to fill gaps in results. Consider the following query:\n\n```\nSELECT COUNT(*), sale_date\n FROM sales\n WHERE sale_date > CURDATE() - INTERVAL 1 MONTH\n GROUP BY sale_date\n ORDER BY sale_date;\n```\n\nThe result will not contain rows for days where no sales record exists at all. You can complete the result with a row generator.\n\nImagine a view, `GENERATOR`, that returns numbered rows like this:\n\n```\nSELECT n\n FROM generator\n WHERE n < 31;\n\n+-----+\n| n |\n+-----+\n| 0 | \n| 1 | \n. . . .\n| 29 | \n| 30 | \n+-----+\n31 rows in set (0.00 sec)\n```\n\nThis is the basic functionality of a row generator. Having that, it is quite simple to list all days since a month ago:\n\n```\nSELECT CURDATE() - INTERVAL n DAY dt\n FROM generator\n WHERE CURDATE() - INTERVAL n DAY \n > CURDATE() - INTERVAL 1 MONTH;\n\n+------------+\n| dt |\n+------------+\n| 2011-07-29 | \n| 2011-07-28 | \n. . . . . . . \n| 2011-07-01 |\n| 2011-06-30 | \n+------------+\n30 rows in set (0.00 sec)\n```\n\nFinally, we can use an outer join to combine the original result with the generated dates:\n\n```\nSELECT IFNULL(sales, 0) sales, dt sale_date\n FROM\n ( SELECT CURDATE() - INTERVAL n DAY dt\n FROM generator\n WHERE CURDATE() - INTERVAL n DAY \n > CURDATE() - INTERVAL 1 MONTH\n ) dates\n LEFT OUTER JOIN\n ( SELECT COUNT(*) sales, sale_date\n FROM sales\n WHERE sale_date > CURDATE() - INTERVAL 1 MONTH\n GROUP BY sale_date\n ) sales\n ON (sales.sale_date = dates.dt)\n ORDER BY dt;\n```\n\nThe left side of the join has all the generated dates so that the outer join pads the right wide with `NULL`, if there were no sale on that day. The `IFNULL` turns the missing sales count into a zero.\n\n#### If you like this page, you might also like …\n\n… to [subscribe my **mailing lists**](https://winand.at/lists), [get **free stickers**](https://use-the-index-luke.com/shop), [buy **my book**](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=mysql-row-generator&utm_medium=web) or [join a **training**](https://winand.at/sql-training/open-online-class).\n\nSo far, so good. But the problem is that MySQL has no row generator that produces an arbitrary number of rows as needed. Still there is a technique that is good enough in most cases.\n\nIt starts with something rather ridiculous:\n\n```\nCREATE OR REPLACE VIEW generator_16\nAS SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL \n SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL\n SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL\n SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL\n SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL \n SELECT 15;\n```\n\nIt is a generator to produces 16 rows. You can use the same technique for larger generators as well. E.g., to produce one million rows, like shown at the end of this article. Just kidding. There is, of course, a better way:\n\n```\nCREATE OR REPLACE VIEW generator_256\nAS SELECT ( hi.n * 16 + lo.n ) AS n\n FROM generator_16 lo\n , generator_16 hi;\n```\n\nThis view builds the cross join (Cartesian product) of the previous view with itself. That means it pairs every row from the “lo” side with all rows from the “hi” side of the join. The result has 256 rows (16x16).\n\nConsidering the introductory example, it is not only important to generate an arbitrary number of rows, we need *numbered rows* to make use of it. For that purpose, I threat the two sides of the cross join like digits in a hexadecimal number. The “lo” side building the least significant, the “hi” side the most significant digit. Explained by SQL:\n\n```\nSELECT CONCAT(LPAD(hi.n,2,' '), ' * 16 + '\n , LPAD(lo.n,2,' '), ' = '\n , LPAD(hi.n*16+lo.n, 3,' '))\n AS \"HI LO SEQ\"\n FROM generator_16 lo, generator_16 hi;\n\n+--------------------+\n| HI LO SEQ |\n+--------------------+\n| 0 * 16 + 0 = 0 | \n| 0 * 16 + 1 = 1 | \n| 0 * 16 + 2 = 2 | \n| 0 * 16 + 3 = 3 | \n| 0 * 16 + 4 = 4 | \n| 0 * 16 + 5 = 5 | \n| 0 * 16 + 6 = 6 | \n| 0 * 16 + 7 = 7 | \n| 0 * 16 + 8 = 8 | \n| 0 * 16 + 9 = 9 | \n| 0 * 16 + 10 = 10 | \n| 0 * 16 + 11 = 11 | \n| 0 * 16 + 12 = 12 | \n| 0 * 16 + 13 = 13 | \n| 0 * 16 + 14 = 14 | \n| 0 * 16 + 15 = 15 | \n| 1 * 16 + 0 = 16 | \n| 1 * 16 + 1 = 17 | \n. . . . . . . . . . .\n| 15 * 16 + 14 = 254 | \n| 15 * 16 + 15 = 255 | \n+--------------------+\n256 rows in set (0.00 sec)\n```\n\nI guess you know how to build a larger generator now?\n\nThere are, of course, some limitations:\n\n- The views are bounded They cannot produce an arbitrary number of rows. But you can prepare views that generate large number of rows (see below).\n- The views will always build the full Cartesian product Although you can limit the result with the `where` clause, the work to produce all rows is still done. It’s just filtering the unneeded. That means, it is very inefficient to use a large generator view if you need just a few rows.\n\nAnother aspect is that the result order is undefined—although the example above produces the numbers is ascending order. That’s just because the way MySQL joins the two views. If you build another meta view, e.g., `GENERATOR_64K`, you’ll note that the order is not ascending anymore—because of MySQLs Block Nested-Loop Join. But that doesn’t mean that the generator doesn’t work, each number is still generated exactly once. If you need a particular order, just use the `ORDER BY` clause on the outermost `select`.\n\n#### Warning\n\nDon’t use `LIMIT` to cut the view as needed because you might receive unexpected numbering. Please note that using `ORDER BY` and `LIMIT` in combination returns the correct result, but requires the intermediate result to be stored temporarily.\n\nUse `where` to filter on the returned numbers. There is no need to store the intermediate result in that case.\n\nFinally, here are some handy generator views up to 1 “mega-row”. They use a minor improvement: bit-shift operations instead of arithmetics.\n\n```\nCREATE OR REPLACE VIEW generator_16\nAS SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL \n SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL\n SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL\n SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL\n SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL \n SELECT 15;\n\nCREATE OR REPLACE VIEW generator_256\nAS SELECT ( ( hi.n << 4 ) | lo.n ) AS n\n FROM generator_16 lo, generator_16 hi;\n\nCREATE OR REPLACE VIEW generator_4k\nAS SELECT ( ( hi.n << 8 ) | lo.n ) AS n\n FROM generator_256 lo, generator_16 hi;\n\nCREATE OR REPLACE VIEW generator_64k\nAS SELECT ( ( hi.n << 8 ) | lo.n ) AS n\n FROM generator_256 lo, generator_256 hi;\n\nCREATE OR REPLACE VIEW generator_1m\nAS SELECT ( ( hi.n << 16 ) | lo.n ) AS n\n FROM generator_64k lo, generator_16 hi;\n```\n\nEven the last view, producing 220 rows, returns the result in a seconds on current hardware. However, the only use I have for the `GENERATOR_1M` view is producing test data.\n\nAlways use the smallest possible generator for best performance.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 7987, "slov": 1427, "odkazu": 57, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:56", "sha256": "6d69ce5ec1ca449d58d8290c8e9148e24224286b02d04342a6ee06acc45cbe31", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://modern-sql.com/feature/with", "https://bugs.mysql.com/bug.php?id=16244", "https://winand.at/lists", "https://sql-performance-explained.com/", "https://winand.at/sql-training/open-online-class", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2011-08-13/one-year-and-three-minutes", "titulek": "Use The Index, Luke Anniversary: Launching the Three Minutes Quiz", "h1": "One Year and Three Minutes", "popis": "One Year Use The Index, Luke and Three Minutes Test", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2011-08-13/one-year-and-three-minutes", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Use The Index, Luke Anniversary: Launching the Three Minutes Quiz", "og:description": "One Year Use The Index, Luke and Three Minutes Test", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "One Year and Three Minutes"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# One Year and Three Minutes\n\n---\n\nUse The Index, Luke! was one today.\n\nThere was quite some progress during this year. Besides the steadily growing content, I am particularly happy that the appendices about [execution plans](/sql/explain-plan) and the [example schema](/sql/example-schema) cover MySQL, PostgreSQL and SQL Server in addition to Oracle.\n\nBut what’s next?\n\nThe content will be completed until early 2012 (final outline in the [Preface](/sql/preface)). The second volume of [SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-one-year&utm_medium=web)—the e-book edition—will be published at that time as well. Additionally, Use The Index, Luke! will be translated gradually into German.\n\nIn the German-speaking area, I will also hold my “[SQL Performance Basics Workshop for Developers](https://winand.at/sql-training/inhouse)”. [Individual online workshops](https://winand.at/sql-training/inhouse) are available worldwide in German or English language.\n\nFinally, I have prepared something for the first anniversary of Use The Index, Luke. How good do you know SQL-Performance? I hope you had the feeling of success when you applied your experience from the book to your real-world problems. Did you actually blog or tweet about it? [Let me know](/contact). However, you can also take the new[3-minute quiz](/3-minute-quiz) to see how good you are. Although the test takes just three minutes, it’s not simple. Some of the questions are not yet covered by the book — don’t be surprised if you don’t get the perfect score. Short explanations are given at the end, longer ones will come in the next few month on Use The Index, Luke!\n\n[Take the 3-minute quiz](/3-minute-quiz)\n\n[Workshop](https://winand.at/sql-training/inhouse)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2404, "slov": 339, "odkazu": 53, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:57", "sha256": "133cf7e4f5cafd1a225e770839fb2906a4eb5a05eda8b4d4bf4fb372f27c6634", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://sql-performance-explained.com/", "https://winand.at/sql-training/inhouse", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2012-05-25/done-or-what", "titulek": "Use The Index, Luke! has been completed.", "h1": "Done! Or What?", "popis": "Done! Or What?", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2012-05-25/done-or-what", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Use The Index, Luke! has been completed.", "og:description": "Done! Or What?", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Done! Or What?"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Done! Or What?\n\n---\n\nDuring the last few weeks, it has become a little silent here at *Use The Index, Luke!* Today, I’d like to tell you the news that caused the silence and give a short outlook about the future of *Use The Index, Luke!*\n\nThe most important news is that I became father. It’s very important to me, at least. My son, Marcel, was born on 25th March 2012. So, we already had two month to settle down. Mommy is quite good at the night shift—I can sleep almost normally and have enough time and energy to work during daytime.\n\nMost of that time I’ve spent to complete the book. Yes, it is “done”. As done as an online IT book can get. That means, the originally planned content is—after two years—finalized. The German translation was completed at about the same time. *Use The Index, Luke!* is now fully available in two languages.\n\nDuring these two years of writing, I have always strived for an exciting text, because I know database tuning is not a popular topic for developers. I designed the structure so that one topic leads to the next in the hope it is read from cover to cover in one shot. The problem with the website is, however, that most people just see one or two pages. Those pages are often are often out of context and don’t make sense on their own. To cut a long story short: I believe the text only works when read entirely. So, I decided to publish the book as a real book.\n\nI took the title I already used for the e-Pub edition last year: [*SQL Performance Explained*](https://sql-performance-explained.de?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-done-or-what&utm_medium=web). The cover photo is a quickly running squirrel because the book is about fast SQL. So it comes that I sometimes introduce the book as “[Squirrel Performance Explained](https://sql-performance-explained.de?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-done-or-what&utm_medium=web)”.\n\nAt the moment, there is only a German edition available (to my own surprise). That is because I found some confusingly written paragraphs during translation. Definitely not good enough for printing. Those parts were not just translated, but rewritten from scratch. In two languages—at least at the beginning. Due to time constraints, I had to stop editing the English text after a while. Just writing in my native language was, of course, faster.\n\nYou can buy the German edition directly via [http://sql-performance-explained.de/](https://sql-performance-explained.de?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-done-or-what&utm_medium=web) or—private consumers in Germany—also in my [amazon.de-Shop](https://www.amazon.de/gp/product/3950307818/?ie=UTF8&site-redirect=de&m=AJFZUYB7XQGQN&tag=httpwinaat-21&linkCode=ur2&camp=1638&creative=6742). Delivery time is the same in both cases because I’m always using amazon’s delivery network for Germany—no matter which way you order.\n\nFinally, I’ll give you a small outlook what’s happening next. I’m currently completing the English text, of course. I’m looking for a lecturer, btw; A native speaker, preferably with German and IT knowledge ([contact](https://winand.at/contact)). Once the text is finalized, printing is no big issue. After that, I need to take care to earn some money again. From business perspective, this year was a disaster until now. Not only because I spent quite some time on the book, but also to prepare the arrival of my son. I finally took drivers education, for example. One would not believe how much time that takes.\n\nEarning money is for me mostly about doing [workshops](https://winand.at/sql-training/inhouse) and [Instant-Coaching](https://winand.at/sql-expert-teammate-on-demand). I’m constantly getting inquires for the workshop. The problem is, however, the travel time and expenses. That makes it too expensive very often. As workaround, I try to get three (or more) clients in the same area—in that case, the travel time and expenses is no problem anymore. So, if you would like to hire me for a workshop, just leave me a [short note](https://winand.at/contact). For the planning, I just need a postal code. The book is part of the course material, of course. At the moment, I’m only doing on-site workshops in the D-A-CH region. I’m, however, getting inquires from all over the world (thank you!). But that is even harder to manage. For those of you living outside Austria, Germany or Switzerland, please consider using the [Instant-Coaching](https://winand.at/sql-expert-teammate-on-demand) model. It is a virtual workshop, using your system. I can explain the principles based on examples from your own application, if you like.\n\nIf I find some time in between, I’d like to process my blog backlog. I’m having topics for about 20 articles in the pipeline—some of them for the miserably neglected [myth directory](/sql/myth-directory). I can also imagine writing some opinion articles. I’ve always aimed to stay objective when writing for the book. Now, I might write possibly some…well…more emotional articles.\n\nI did not yet make up my mind regarding long-term planning for *Use The Index, Luke!* I will, of course, maintain and update the material. Let me know if you have any topic you would like to see on *Use The Index, Luke!* Your wish might come true.\n\n*So long,*\n\n*-markus*\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 5929, "slov": 924, "odkazu": 57, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:58", "sha256": "f1db8430b9354c0e1c732ddd01f57c158f5679fdcb4dcee11f9ac934fae1d004", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://sql-performance-explained.de/", "https://www.amazon.de/gp/product/3950307818/?camp=1638&creative=6742&ie=UTF8&linkCode=ur2&m=AJFZUYB7XQGQN&site-redirect=de&tag=httpwinaat-21", "https://winand.at/contact", "https://winand.at/sql-training/inhouse", "https://winand.at/sql-expert-teammate-on-demand", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2012-08/customs-and-well-errata", "titulek": "Customs and, well, errata... of SQL Performance Explained", "h1": "Customs and, well, errata...", "popis": "Customs and, well, errata...", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2012-08/customs-and-well-errata", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Customs and, well, errata... of SQL Performance Explained", "og:description": "Customs and, well, errata...", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Customs and, well, errata..."}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Customs and, well, errata...\n\n---\n\nI’ve finally managed to put all the errors that were reported by readers so far online. I’m not exactly proud of this, but there are already more than 30 known errata for the German edition. There are still some German copies of “SQL Performance Explained” on stock, but it seems like I have to arrange a second printing soon. I will surly take up all these errors for the second printing. The English edition has just two errata at the moment, but I doubt it will stay that low. You are more than welcome to report any mistakes you find: I *do* follow them up :)\n\nAnd now, something different: customs. I’ve received some inquires if I can indicate how much customs you might have to pay if you order the book from outside the EU. Well, I cannot tell you the exact amount, but help you Google it ;) The important information you need to find the rate in your country is the so-called [HS](https://en.wikipedia.org/wiki/Harmonized_System) number and the origin of the goods. I’ve to put this information on the CN22 customs declaration on the outside of the package, so authorities know what’s inside. The HS number for books is 490199 and this particular book is printed in Austria. That’s what I write on the customs declaration form. I’ve also been told that some countries might charge other fees besides customs (e.g., VAT). Sorry, don’t know any more details.\n\nHowever, I’m asking all international buyers to report if and how much fees they had to pay. Until now, I’ve not received any feedback—but I’ve done only one international shipping so far. Next one is due on Tuesday.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2262, "slov": 361, "odkazu": 53, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:59", "sha256": "a3dced7bc0cf5e5be0431cdd1d8808fc83379664677d8b99147012fe9f5f5327", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://en.wikipedia.org/wiki/Harmonized_System", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2012-08/finally-almost-world-wide-free-shipping", "titulek": "Availability of SQL Performance Explained", "h1": "Finally: Almost World-Wide Free Shipping", "popis": "Finally — Almost World-Wide Free Shipping", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2012-08/finally-almost-world-wide-free-shipping", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Availability of SQL Performance Explained", "og:description": "Finally — Almost World-Wide Free Shipping", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Finally: Almost World-Wide Free Shipping"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Finally: Almost World-Wide Free Shipping\n\n---\n\nThe English edition of “[SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-free-shipping&utm_medium=web)” is finally available. It has its own website [http://sql-performance-explained.com/](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-free-shipping&utm_medium=web) where you can find a [PDF preview](https://sql-performance-explained.com/img/9783950307825_preview.pdf?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-free-shipping&utm_medium=web) and order information. The cover price is EUR 29.95 or GBP 26.99.\n\nIf you order it from outside the EU, you must also consider that you might be required to pay import duties in the destination country.\n\nKnowing that I have readers all over the world, I’ve spent a fair amount of time to make world-wide free shipping possible. I almost succeeded. If you use the [direct order form](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-free-shipping&utm_medium=web) I’ll be able to offer free shipping to 150+ countries. However, this is only possible when using a volume discount offered by the Austrian postal service. Therefore, I’ll dispatch international orders only once a week.\n\n[SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-free-shipping&utm_medium=web)\n\nFine print: There are some countries that do not accept dutiable letter post. These are: Afghanistan, Albania, Azerbaijan, Bangladesh, Belarus, Benin, Burkina Faso, Cambodia, Chile, Colombia, Côte d’Ivoire (Rep.), Cuba, Dem. People’s Rep. of Korea, Djibouti, El Salvador, Kazakhstan, Latvia, Mali, Mauritania, Moldova, Nepal, Peru, Russian Federation, Turkmenistan, Ukraine, Uzbekistan and Venezuela (see [Article X on page 79 of the Universal Postal Convention](https://lettersblogatory.com/wp-content/uploads/2011/11/UPC.pdf)).\n\nIf you live in one of those countries, please feel free to use the [direct order form](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-free-shipping&utm_medium=web) anyway. There is no obligation in filling in the form. If I know that you live in one of these countries and would like to get the print edition, I can check how I could send it to you anyway.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3090, "slov": 387, "odkazu": 55, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:00", "sha256": "a1c666a9cf8de74334a580ccd36439986614e80f64e5fad11f42bc03a9ad1fd8", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://sql-performance-explained.com/", "https://sql-performance-explained.com/img/9783950307825_preview.pdf", "https://lettersblogatory.com/wp-content/uploads/2011/11/UPC.pdf", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2012-08/second-anniversary", "titulek": "Use The Index, Luke Anniversary: SQLFiddle integration [discontinued]", "h1": "Second Anniversary", "popis": "Second Anniversary", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2012-08/second-anniversary", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Use The Index, Luke Anniversary: SQLFiddle integration [discontinued]", "og:description": "Second Anniversary", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Second Anniversary"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Second Anniversary\n\n---\n\n“Use The Index, Luke!” celebrates its second anniversary today. Unfortunately, I was not able to prepare anything for this anniversary like I did last year when I presented the [3-minute quiz.](/3-minute-quiz) The test is still very popular, by they way, it is taken about 20 times a day. However, all I have for this years anniversary is a promise.\n\nDo you know [http://sqlfiddle.com/](https://sqlfiddle.com)? You should ;) It’s an online tool to test SQL queries with five different databases (SQL Server, MySQL, Oracle, PostgreSQL and SQLite). It is not a cloud database that you could use for building applications. SQLFiddle is a tool for collaborative online work on SQL problems. It was built to improve asking and solving SQL related questions on Q/A sites like Stackoverflow.\n\nFor me, SQL Fiddle is interesting because of the “View Execution Plan” Button. As said before, it is not a cloud DB that we could use for performance tests, but we can have a look at executions plans. I believe it would be very convenient to have prepared fiddles for the examples from “Use The Index, Luke!” so that you can easily test them online without needing your own database.\n\nAnd this is exactly what will come—although I don’t have a time line yet. Stay tuned. **UPDATE in 2015**: SQLFiddle integration will be removed again because it it hardly used but causes a lot of overhead on my side.\n\n[SQL Fiddle](https://sqlfiddle.com/)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2091, "slov": 321, "odkazu": 54, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:01", "sha256": "ff900235449aebda8caf3ce5e6b5e0d32ea62eca7cd4680e99067401c0072384", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://sqlfiddle.com/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2012-09/convinced-pdf-and-bundle-sales", "titulek": "Convinced: Selling a PDF edition of SQL Performance Explained for EUR 9.95.", "h1": "Convinced", "popis": "Convinced: Selling a PDF edition of SQL Performance Explained", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2012-09/convinced-pdf-and-bundle-sales", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Convinced: Selling a PDF edition of SQL Performance Explained for EUR 9.95.", "og:description": "Convinced: Selling a PDF edition of SQL Performance Explained", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Convinced"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Convinced\n\n---\n\nAfter publishing the English edition of “SQL Performance Explained” there was a huge demand for an ebook edition. After a few days answering these queries, I though it’s probably easier to offer an e-book than to explain why there isn’t one. Well, I must admit that I don’t read ebooks very much. My wife has an e-ink device, but is hardly using it (probably in lack of German content). I’ve uploaded the ePUB pre-release from 2011 (not available anymore) and must say it works, but isn’t nice. However, many people told me they would be fine with a PDF, because they are anyway using tablets or smartphones to read their ebooks. Fast forward a few weeks: since Monday I can offer a PDF download for just EUR 9.95 (English, German [update] or French, you choose).\n\nAfterwards there was a huge demand—again—for a bundle discount when purchasing both, the PDF and the hard copy. That caught me by surprise. Not that people want a discount, but that people would like to buy both editions. So I asked, and listened, and learned something about my own business.\n\nSure there were usual suspected like “I’d just like the PDF for searching” “to have it with me when being on the road” and so forth. But the interesting point was “I’d like the hard copy, but would also like to start reading immediately.” Well, I didn’t think of that (shame on me). Although I’m offering free shipping to 150+ countries, it takes its time because I’m shipping from Europe only [once a week](/blog/2012-08/finally-almost-world-wide-free-shipping). Instead of express delivery, I just need to offer a bundle.\n\nIt took another day to tweak my accounting software because there are different VAT rates applied to real books and PDF downloads—but the accounting software could do only one VAT rate for each invoice. After all I’m just a geek like most of you, so I hacked a day and made it work. [The bundle is on sale for EUR 34.95](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-ebook&utm_medium=web) since yesterday evening—that’s a EUR 4.95 discount.\n\nAnd now, I’ll be your [“What-If” Machine](https://futurama.fandom.com/wiki/What-If_Machine):\n\nWhat if I already bought the print edition and would like to get the PDF and the bundle discount?\n\nNo problem, you’ll get the discount! I don’t see any reason I should treat the “early adopters” any worse than people who didn’t buy the print ed yet.UPDATE 2013-07-08: It currently works like this: On the invoice for the print edition, you’ll find a discount code to get the PDF edition for the reduced price. Same is true vice versa.OUTDATED: Please fill in the [order form and select the PDF edition](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-ebook&utm_medium=web). The important part is that you need to mention that you already bought the print ed in the “Notes” section. Please add any references you have for your purchase. You should have received an invoice from me, even when you bought at Amazon. Mention the invoice or offer-no. If you bought it at your local book dealer, tell me when and where you bought it. I’ll check your original purchase and grant you the discount. That is, however, a manual procedure and may take a while.\n\nWhat if I bought the PDF edition and would like to get the print ed and the bundle discount?\n\nNo problem, you’ll get the discount! Same procedure as above.\n\nNo matter in which order you buy, you’ll get the discount if you can prove your previous purchase.\n\nFinally, I have to tell you that I’ll be abroad in the next few week and I cannot dispatch international orders during this time. That means, the last international dispatch from my office will take place on Friday. So, place your orders now. Regardless of that, there are more than enough copies on stock at Amazon. They will take care of your order at any time but might charge shipping fees.\n\nOh, I forgot one more thing. Some readers from the United States have reported that they didn’t have to pay any custom duties or other fees after receiving the hard copy. So, if you are in the US, it seems that you don’t need to worry about customs when ordering the hard copy.\n\n[SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-ebook&utm_medium=web)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 4958, "slov": 807, "odkazu": 54, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:02", "sha256": "24f589c0d2d30381c38b7e8a5ad802baaf59f55f60437763d7c45ab9ea17fc6f", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://sql-performance-explained.com/", "https://futurama.fandom.com/wiki/What-If_Machine", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2012-10/PGConf.EU_2012_Schedule", "titulek": "My PGConf.EU 2012 Schedule for Prague", "h1": "My PGConf.EU 2012 Schedule", "popis": "My PGConf.EU 2012 Schedule", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2012-10/PGConf.EU_2012_Schedule", "jazyk": "en", "robots_meta": "", "og": {"og:title": "My PGConf.EU 2012 Schedule for Prague", "og:description": "My PGConf.EU 2012 Schedule", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "My PGConf.EU 2012 Schedule"}, {"uroven": 2, "text": "Tuesday, October 23"}, {"uroven": 2, "text": "Wednesday, October 24"}, {"uroven": 2, "text": "Thursday, October 25"}, {"uroven": 2, "text": "Friday, October 26"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# My PGConf.EU 2012 Schedule\n\n---\n\nAs mentioned before, I’ll be at [this year PostgreSQL Conference in Prague](https://2012.pgconf.eu/). Still two weeks to go, but I just had a few minutes “free” time and prepared my personal schedule.\n\nAs usual, I plan to attend as many sessions as possible. As usual, I’ll skip some in favour of a nice chat and/or change my mind in the last moment.\n\n## Tuesday, October 23\n\nI’ll spend the whole day with Joe Celko’s session “[A day of SQL with Celko](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/287-a-day-of-sql-with-celko/).” Thought it might be a good idear to listen to him—probably less time consuming than reading his books ;)\n\n## Wednesday, October 24\n\n11:10 - 12:00 — Room: Seine\n\n[“Programming the SQL Way with Common Table Expressions.”](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/294-programming-the-sql-way-with-common-table-expressions/) CTEs are not exactly new to me, still I’m hardly using them. Hope to see some good examples how they can help.\n\n12:10 - 13:00 — Room: Thames\n\n[“MultiMaster Replication: Applications, Comparison, Implementation.”](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/331-multimaster-replication-applications-comparison-implementation/) What caught my attention was “ various replication implementations in CouchDB, MongoDB, SQLServer and Oracle” — whow, that sounds interesting. NoSQL/SQL comparisons are difficult, let’s see how this one works out.\n\n14:00 - 14:50 — Room: Seine\n\n[“Understanding EXPLAINs output.”](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/348-understanding-explains-output/) I guess everybody knows: I love execution plans :)\n\n15:20 - 16:10 — Room: Thames\n\n[“Range Types in PostgreSQL 9.2 - Your Life Will Never Be The Same.”](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/284-range-types-in-postgresql-92-your-life-will-never-be-the-same/) We will see...\n\n16:20 - 17:10 — Room: Thames\n\n[“High availability in Postgres-XC, the symmetric PostgreSQL cluster.”](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/325-high-availability-in-postgres-xc-the-symmetric-postgresql-cluster/) Again, something in the domains of NoSQL...\n\n## Thursday, October 25\n\n09:30 - 10:20 — Room: Vltava\n\n[“Marketing PostgreSQL.”](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/283-marketing-postgresql/) When read “Your Life Will Never Be The Same” above I immediately though that must be a marketing guy. Confirmed. However, I need to do a lot of marketing as well.\n\n10:50 - 11:40 — Room: Thames\n\n[“Universal Data Access with SQL/MED.”](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/277-universal-data-access-with-sqlmed/)\n\n11:50 - 12:40 — Room: Vltava\n\n[“Elephants and Windmills.”](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/315-elephants-and-windmills/)\n\n13:40 - 14:30 — Room: Seine\n\n[“Inside PostgreSQL Shared Memory.”](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/296-inside-postgresql-shared-memory/)\n\n14:40 - 15:30 — Room: Vltava\n\n[“Index support for regular expression search.”](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/308-index-support-for-regular-expression-search/) No comment :)\n\n## Friday, October 26\n\n09:30 - 10:20 — Room: Seine\n\n[“Beyond Query Logging.”](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/358-beyond-query-logging/)\n\n10:50 - 11:40 — Room: Thames\n\n[“Migrating Oracle queries to PostgreSQL.”](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/346-migrating-oracle-queries-to-postgresql/) ... subtle (often undocumented) differences are highlighted.\n\n11:50 - 12:40 — ??\n\n“[Debugging complex SQL queries with writable CTEs](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/329-debugging-complex-sql-queries-with-writable-ctes/)” —OR— “[PG-Strom - GPU Accelerated Asynchronous Query Execution Module](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/297-pg-strom-gpu-accelerated-asynchronous-query-execution-module/)” Here I’ve a real problem, both sound very interesting.\n\n13:40 - 14:30 — Room: Seine\n\n[”Large Scale MySQL Migration to PostgreSQL.”](https://www.postgresql.eu/events/pgconfeu2012/schedule/session/317-large-scale-mysql-migration-to-postgresql/)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 4848, "slov": 557, "odkazu": 68, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:03", "sha256": "8873720cf71b8ab991f8f179752eb0f53e172613e299c6bf54c276a22dec0fd1", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://2012.pgconf.eu/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/287-a-day-of-sql-with-celko/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/294-programming-the-sql-way-with-common-table-expressions/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/331-multimaster-replication-applications-comparison-implementation/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/348-understanding-explains-output/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/284-range-types-in-postgresql-92-your-life-will-never-be-the-same/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/325-high-availability-in-postgres-xc-the-symmetric-postgresql-cluster/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/283-marketing-postgresql/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/277-universal-data-access-with-sqlmed/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/315-elephants-and-windmills/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/296-inside-postgresql-shared-memory/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/308-index-support-for-regular-expression-search/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/358-beyond-query-logging/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/346-migrating-oracle-queries-to-postgresql/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/329-debugging-complex-sql-queries-with-writable-ctes/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/297-pg-strom-gpu-accelerated-asynchronous-query-execution-module/", "https://www.postgresql.eu/events/pgconfeu2012/schedule/session/317-large-scale-mysql-migration-to-postgresql/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2012-10/discount_codes_you_missed_without_twitter", "titulek": "Stuff you missed without Twitter in October 2012", "h1": "Stuff you missed without Twitter", "popis": "Stuff you missed without Twitter", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2012-10/discount_codes_you_missed_without_twitter", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Stuff you missed without Twitter in October 2012", "og:description": "Stuff you missed without Twitter", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Stuff you missed without Twitter"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Stuff you missed without Twitter\n\n---\n\nIf you are not following my SQL Performance Tips ([@SQLPerfTips](https://x.com/SQLPerfTips)) feed on twitter, you are missing a lot. However, two things you should probably know, even without using twitter:\n\nAll You Base Conf — Database conference for web developers\n\nI’m in no way affiliated with those guys, but they were so nice to offer a discount code for my readers (followers?). The conference takes place in Oxford, UK on 23rd Nov 2012. Have a look at [http://allyourbaseconf.com/](https://web.archive.org/web/20170605002840/http://www.allyourbaseconf.com/) for more details. Use the promo code “SQLPerf” to get £35 off the standard ticket price.\n\nCelebrating 10k followers\n\nMy [@SQLPerfTips](https://x.com/SQLPerfTips) account has crossed the 10k followers mark recently. So I though I’ll celebrate this with another discount code (10kflwrs) that is good for -10% for orders of “SQL Performance Explained” when placed directly at [http://sql-performance-explained.com/](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-twitter-oct&utm_medium=web). This code expires on Fri, 12th Oct 20:00 Vienna local time (CEST). That’s 11am PDT, for example.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1843, "slov": 241, "odkazu": 54, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:04", "sha256": "84bcc2d3db78036ca8a0413ca88c2fdf888763f908f03402bc2ff57530aca956", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://x.com/SQLPerfTips", "http://www.allyourbaseconf.com/", "https://sql-performance-explained.com/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2012-11/joe-celko-reviews-sql-performance-explained", "titulek": "Joe Celko’s (former SQL Standard committee member) review of “SQL Performance Explained”", "h1": "Joe Celko’s review of “SQL Performance Explained”", "popis": "Joe Celko’s review of “SQL Performance Explained”", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2012-11/joe-celko-reviews-sql-performance-explained", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Joe Celko’s (former SQL Standard committee member) review of “SQL Performance Explained”", "og:description": "Joe Celko’s review of “SQL Performance Explained”", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Joe Celko’s review of “SQL Performance Explained”"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Joe Celko’s review of “SQL Performance Explained”\n\n---\n\nJoe Celko’s review of my book [SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-celko-review&utm_medium=web) was just published. The bottom line: “This book is definitively worth having in the company library.”\n\n[Read Joe’s review](https://www.i-programmer.info/bookreviews/21-database/5077-sql-performance-explained-.html)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1061, "slov": 125, "odkazu": 53, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:05", "sha256": "28b6bcae5455fe95be22b8033c14b85668a94c918de23f3dd85f516056777703", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://sql-performance-explained.com/", "https://www.i-programmer.info/bookreviews/21-database/5077-sql-performance-explained-.html", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2012-11/pgconfeu2012-summary", "titulek": "PG.Conf EU 2012 — Summary Prague", "h1": "PG.Conf EU 2012 — Summary", "popis": "PG.Conf EU 2012 — Summary", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2012-11/pgconfeu2012-summary", "jazyk": "en", "robots_meta": "", "og": {"og:title": "PG.Conf EU 2012 — Summary Prague", "og:description": "PG.Conf EU 2012 — Summary", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "PG.Conf EU 2012 — Summary"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# PG.Conf EU 2012 — Summary\n\n---\n\nWith a little delay of just three weeks, I’m writing something about this years PostgreSQL conference Europe.\n\nIncluding the training day, it was four days full of database stuff—in other terms: an awesome time, if you love databases :) But let’s start from the beginning.\n\nI booked the full day training with [Joe Celko](https://www.postgresql.eu/events/pgconfeu2012/schedule/speaker/119-joe-celko/) on the first day. And I must say that was the best part of the conference—mostly because Joe is great. If you never meet Joe Celko, or don’t even know who the heck he is, you should definitely look for an opportunity to meet him.\n\nThe training he gave (“A day of SQL with Celko”) was a mixture of SQL related topics like keys, naming (e.g., plurals for tables), metadata, rollup (`group by grouping sets`, `group by cube`) and trees. Due to my day to day work, I’ve already seen some of the “rarely known features” he mentioned. It was still very valuable because he presented good examples for them. The “[nested sets model](https://en.wikipedia.org/wiki/Nested_set_model)” is particularly noteworthy. I hope to write about some of these topics soon.\n\nOutside of the training, it was also very nice to talk to Joe. He even signed a copy of *my* book for me—kidding that he should write “I did not write this book.” On the next day, when I was skipping one session, I had a chance to chat with him. So, I challenged him about his famous “80-95% of the work in SQL is done in the DDL, not the DML” statement (e.g., recently cited [here](https://web.archive.org/web/20260215230955/https://tdan.com/select-from-celko-september-2012/16408)) and asked if he considers `create index` as part of DDL in this context. Well, there is a good reason `create index` is not part of the SQL standard: because indexing is an implementation detail. Still, I argued that it is required to make the final system working and I believe Joe agreed after a while. I hope he still agrees after a few weeks :)\n\nDay 2, after Joe’s opening keynote, I attended to [Bruce Momjian’s](https://momjian.us/) “Programming the SQL Way with Common Table Expressions.” Well, I did not like this talk because it was not focused on CTEs in general, but mostly about the “[writable CTE](https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-MODIFYING)” extenstion by PostgreSQL. Sure it is OK to focus on specifics on a PostgreSQL conference, but I don’t like this particular feature—even though I like some other proprietary features of PostgreSQL.\n\nIn the afternoon, I listened to [Guillaume Lelarge’s](http://blog.guillaume.lelarge.info/) “Understanding EXPLAIN’s output”. He covered almost all explain plan operations in 50 minutes, but it was still possible to follow him. I learned about [EXPLAIN BUFFERS](https://www.postgresql.org/docs/current/sql-explain.html) (how could I miss that so far?).\n\nThe talk about range types (“Your Life Will Never Be The Same”) did not exactly hold up to my expectations. It introduced range types in a, well, superficial way so that I neither had questions during the talk, nor did I feel enlightened. The only thing that remained was the feeling that I should have a closer look into this.\n\n[Josh Berkus’s](https://pgexperts.com/team/josh_berkus/) talk “Elephants and Windmills” was also a little bit disappointing. It was basically about a data warehouse, and as far as I could see, there was not particularly noteworthy innovation in their solution. On the contrary: in the age of NoSQL, sharding and cloud computing, it sounds strange that they just dedicated separate hardware to handle the load of separate clients because it was just too much for a single box. However, I might have missed a critical point.\n\nI liked Bruce Momjians second talk “Inside PostgreSQL Shared Memory”. It was just what I expected: some insight into internals you probably don’t need to know about :)\n\nThe last talk on Thursday “Index support for regular expression search” by Alexander Korotkov was very interesting. He is basically transforming regular expressions to logical expressions made up of trigraphs (3-letter groups) like this: `/[ab]cde/ => (acd OR bcd) AND cde` ([taken from his slides](https://wiki.postgresql.org/images/6/6c/Index_support_for_regular_expression_search.pdf)). After that, just use the existing PostgreSQL trigraph index, check each trigraph and apply the logic. Finally, the full regular expression must be applied to filter false positives (the logical expression can match too many rows). After all, it is very promising research that might give considerable speed improvements in *some* cases.\n\nFriday morning: “Beyond Query Logging”. It basically explained new ways to find slow queries—which is, an absolute essential trouble shooting tool. It seems that PostgreSQL is coming considerably closer to the tools other databases, like Oracle, support.\n\nGianni Ciolli’s “Debugging complex SQL queries with writable CTEs” was the last session I attended. Well, writeable CTEs. I had to attend that just to give writeable CTEs a second chance. I liked the presentation (Gianni does it in a very funny way) and I didn’t dislike the use of writable CTEs in this context because it is not intended for production use. The trick is as following: Just convert all sub-queries into CTEs, and capture the content of each CTE with another writable CTE that copies the content into a debug table. In this way, you can capture the intermediate results of an SQL statement and review it later to see where you have an error in the statement. Without this approach, we have to run each part of the SQL statement after another. It is a nice gimmick presented in a very funny way, which doesn’t change my opinion about writable CTEs.\n\nThere were also two social events (Wednesday and Thursday evening, sponsored by [EnterpriseDB](https://www.enterprisedb.com/) and [Heroku](https://www.heroku.com/)) and it was very nice to chat about the talks, about Prague, and about [SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2012-pgconf-summary&utm_medium=web). Writing a book is a very lonesome job—it was great to meet some of my readers in person.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 6849, "slov": 1050, "odkazu": 63, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:06", "sha256": "5736238dfb7da32fa8949282f25960dcf782beae03466cf06e41c0aa797ade3c", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://www.postgresql.eu/events/pgconfeu2012/schedule/speaker/119-joe-celko/", "https://en.wikipedia.org/wiki/Nested_set_model", "https://tdan.com/select-from-celko-september-2012/16408", "https://momjian.us/", "https://www.postgresql.org/docs/current/queries-with.html", "http://blog.guillaume.lelarge.info/", "https://www.postgresql.org/docs/current/sql-explain.html", "https://pgexperts.com/team/josh_berkus/", "https://wiki.postgresql.org/images/6/6c/Index_support_for_regular_expression_search.pdf", "https://www.enterprisedb.com/", "https://www.heroku.com/", "https://sql-performance-explained.com/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2012-12/french-anybody", "titulek": "Launching the French edition of Use The Index, Luke!", "h1": "French anybody? Use The Index, Luke is now available in French.", "popis": "French anybody?", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2012-12/french-anybody", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Launching the French edition of Use The Index, Luke!", "og:description": "French anybody?", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "French anybody? Use The Index, Luke is now available in French."}, {"uroven": 2, "text": "About the Author"}], "markdown": "# French anybody? Use The Index, Luke is now available in French.\n\n---\n\nGood news everybody—well, at least if you speak French. *Use The Index, Luke* and *SQL Performance Explained* will be translated. You can already start reading the first chapters [here](/fr/sql/preface).\n\nHow did that happen? We all owe Guillaume Lelarge ([blog](http://blog.guillaume.lelarge.info/)|[twitter](https://x.com/g_lelarge)) a big thank you for that! He contacted me a while ago about the book and suggested to translate it into French. My first reaction was very skeptical—not because I don’t believe there is a need for a French translations, but because I know translating a book is very hard work. However, Guillaume has already translated a book ([Bases de données PostgreSQL](https://www.pearson.fr/livre/?GCOI=27440100863920)) and the [PostgreSQL documentation](https://docs.postgresql.fr/) (major parts of it). And the best thing is: these are all database topics. I’m quite sure that he is the right one :)\n\nWe will publish the translated chapters in a step-by-step manner here on *Use The Index, Luke!* The print and PDF editions will be available once the translation is done (no release date yet). In the meanwhile I invite you to read the first parts and report errors if you find them—there is an error reporting form on the bottom of each page. Besides that you should also send Guillaume some kudos and read [his post](http://blog.guillaume.lelarge.info/index.php/post/2012/12/18/Use-the-index,-luke!-...-en-fran%C3%A7ais-!) about the translation.\n\n[Start reading: Préface](/sql/preface)\n\n[Visit Guillaume’s blog](http://blog.guillaume.lelarge.info/)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2246, "slov": 310, "odkazu": 57, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:07", "sha256": "4211aad7f1c042c53b7744d4f656804dfe04935fd9ab8ee971dfad443647febd", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["http://blog.guillaume.lelarge.info/", "https://x.com/g_lelarge", "https://www.pearson.fr/livre/?GCOI=27440100863920", "https://docs.postgresql.fr/", "http://blog.guillaume.lelarge.info/index.php/post/2012/12/18/Use-the-index,-luke!-...-en-fran%C3%A7ais-!", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2012-12/instant-what", "titulek": "Instant What? Consulting by Markus Winand charged in units of 30 minutes!", "h1": "Instant What?", "popis": "Instant What? Consulting by Markus Winand", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2012-12/instant-what", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Instant What? Consulting by Markus Winand charged in units of 30 minutes!", "og:description": "Instant What? Consulting by Markus Winand", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Instant What?"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Instant What?\n\n---\n\nYou might guess it, but I’m not making my living from this site nor are the book sales paying all the bills—although the books pays some bills, thank you! However, to pay the remaining bills I’m doing coaching, training and consulting. You can find all the details on my professional site [http://winand.at/](https://winand.at/) but I’d like to highlight one service here: [Instant Coaching](https://winand.at/sql-expert-teammate-on-demand).\n\nAfter googling and trying many ways to solve a problem, have you ever got that feeling of resignation where you just want to ask somebody who should know the answer? Well, that’s Instant Coaching—at least if your problem is about performance and/or databases.\n\nInstant Coaching is remarkably easy and efficient: we just arrange an online meeting where you present your problem or question to me. We’ll use a desktop sharing tool ([TeamViewer](https://www.teamviewer.com/en/)) so that I can see your screen and—if you like—show you something on your computer (control your mouse/keyboard). Instant Coaching needs virtually no preparation: it often starts just a few minutes after you faced the problem—hence “Instant”!\n\nAnother critical success factor for Instant Coaching is that we can put our knowledge and experiences together: you bring the know-how about your application and your data while I’m adding a little database and performance know-how to the mix. Instead of guessing about things I don’t know about your application or you don’t know about databases, we can just ask each other! I’m usually getting asked a lot: you don’t just get the “magic” solution, but you learn about the rational behind it so that can solve similar problems on your own the next time—hence “Coaching”!\n\nIf you have read this marketing post up to here, you’ll even get a special present: just tell me about this blog post and I’ll give you twenty percent off on any Instant Coaching session. And to make that even better, I’ll give up to two hours free Instant Coaching to free open source projects (FOSS). Both offers valid till July 30, 2014 and until I’m booked out.\n\nSo, reserve your seat by filling in the Instant Coaching registration now!\n\n[Step 1: Registration](https://winand.at/sql-expert-teammate-on-demand)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2872, "slov": 438, "odkazu": 53, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:08", "sha256": "4d8e85397c9b23d5a723d9582b979a83a2366f0eef90af0e6faf0670593ab8f9", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/", "https://winand.at/sql-expert-teammate-on-demand", "https://www.teamviewer.com/en/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2012-12/top-tweets", "titulek": "Top Tweets December 2012 selected by Markus Winand", "h1": "Top Tweets December 2012", "popis": "Top Tweets December 2012", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2012-12/top-tweets", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Top Tweets December 2012 selected by Markus Winand", "og:description": "Top Tweets December 2012", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Top Tweets December 2012"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Top Tweets December 2012\n\n---\n\nThis is a short collection of the best tweets on [@SQLPerfTips](https://x.com/SQLPerfTips) and/or [@MarkusWinand](https://x.com/MarkusWinand) for those who missed them and those who don’t use twitter at all.\n\nAnd I want to take this opportunity to wish you a happy new year :)\n\n- Latency Numbers Every Programmer Should Know — Also illustrating how these numbers changed over time: [berkeley.edu](https://colin-scott.github.io/personal_website/research/interactive_latency.html) [[original](https://x.com/MarkusWinand/status/284004275133247488)]\n- Explaining SQL Injection without technical jargon. [security.stackexchange.com](https://security.stackexchange.com/questions/25684/how-can-i-explain-sql-injection-without-technical-jargon#answer-25710) [[original](https://x.com/SQLPerfTips/status/282437633941065728)]\n- RT [@schuon](https://x.com/schuon): Read [https://use-the-index-luke.com](/) yesterday, applied it during lunch, awesome result! [@SQLPerfTips](https://x.com/SQLPerfTips) [pic.twitter.com/GGp2y8Ij](https://pic.twitter.com/GGp2y8Ij) [[original](https://x.com/schuon/status/280810910300389379)]\n- Snowflake SQL: last years happy-new-year post by Quassnoi: [explainextended.com](https://explainextended.com/2011/12/31/happy-new-year-3/) [[original](https://x.com/MarkusWinand/status/283195026555670529)]\n- “How to Design Indexes, Really” — Slides by Bill Karwin ([@billkarwin](https://x.com/billkarwin)) [slideshare.net [[original](https://x.com/SQLPerfTips/status/276755135428964352)]](https://www.slideshare.net/slideshow/how-to-design-indexes-really/14886467)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2210, "slov": 206, "odkazu": 65, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:10", "sha256": "afacb713f7b5d353d28b9732570cce03377c41d80e22c96db43f3a4675c266d3", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://x.com/SQLPerfTips", "https://x.com/MarkusWinand", "https://colin-scott.github.io/personal_website/research/interactive_latency.html", "https://x.com/MarkusWinand/status/284004275133247488", "https://security.stackexchange.com/questions/25684/how-can-i-explain-sql-injection-without-technical-jargon", "https://x.com/SQLPerfTips/status/282437633941065728", "https://x.com/schuon", "https://pic.twitter.com/GGp2y8Ij", "https://x.com/schuon/status/280810910300389379", "https://explainextended.com/2011/12/31/happy-new-year-3/", "https://x.com/MarkusWinand/status/283195026555670529", "https://x.com/billkarwin", "https://www.slideshare.net/slideshow/how-to-design-indexes-really/14886467", "https://x.com/SQLPerfTips/status/276755135428964352", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-01/fosdem-pgday", "titulek": "I’m speaking at FOSDEM PGDay 2013 - Markus Winand", "h1": "I’m speaking at FOSDEM PGDay 2013", "popis": "I’m speaking at FOSDEM PGDay 2013", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-01/fosdem-pgday", "jazyk": "en", "robots_meta": "", "og": {"og:title": "I’m speaking at FOSDEM PGDay 2013 - Markus Winand", "og:description": "I’m speaking at FOSDEM PGDay 2013", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "I’m speaking at FOSDEM PGDay 2013"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# I’m speaking at FOSDEM PGDay 2013\n\n---\n\nMy talk “[Pagination done the PostgreSQL way](https://www.postgresql.eu/events/fosdem2013/schedule/session/384-pagination-done-the-postgresql-way/)” was accepted for the one-day PostgreSQL conference [PGDay on 1st Feb 2013](https://fosdem2013.pgconf.eu/) just before FOSDEM in Brussels.\n\nAs this is the first talk I’ll deliver on a conference, I’ve not yet prepared anything. However, I’ve three weeks left to prepare an awesome talk. Luckily, I do have some ideas to make this talk awesome, but casting a few good ideas into a well-delivered presentation is a non-trivial task. However, I’ll try hard. Promised.\n\nBtw, [Guillaume LeLarge](http://blog.guillaume.lelarge.info/), who is currently doing the French translation of [SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2013-fodem-announcement&utm_medium=web), is also there.\n\nOn the following weekend, there will be the [Free and Open source Software Developers’ European Meeting (FOSDEM)](https://archive.fosdem.org/2013/about/) in Brussels. From the website: “It is renowned for being highly developer-oriented and brings together 5000+ geeks from all over the world. No registration necessary.” At FOSDEM you can find all kinds of topics: from Ada and Free Java to Python, from MySQL and PostgreSQL to NoSQL. Just have a look at the [schedule](https://archive.fosdem.org/2013/schedule/) to get an idea.\n\n[PGDay Schedule](https://www.postgresql.eu/events/fosdem2013/schedule/)\n\n[FOSDEM Schedule](https://archive.fosdem.org/2013/schedule/)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2210, "slov": 275, "odkazu": 58, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:10", "sha256": "80490e5be9b52ff8e17a59517bd7ab35007fd967cf5ba581bd359154143c0e5c", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://www.postgresql.eu/events/fosdem2013/schedule/session/384-pagination-done-the-postgresql-way/", "https://fosdem2013.pgconf.eu/", "http://blog.guillaume.lelarge.info/", "https://sql-performance-explained.com/", "https://archive.fosdem.org/2013/about/", "https://archive.fosdem.org/2013/schedule/", "https://www.postgresql.eu/events/fosdem2013/schedule/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-02/better-performance-with-postgresql-conference", "titulek": "Better Performance with PostgreSQL - SQL Session #5 by Dalibo", "h1": "Better Performance with PostgreSQL", "popis": "Better Performance with PostgreSQL", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-02/better-performance-with-postgresql-conference", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Better Performance with PostgreSQL - SQL Session #5 by Dalibo", "og:description": "Better Performance with PostgreSQL", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Better Performance with PostgreSQL"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Better Performance with PostgreSQL\n\n---\n\n[Dalibo](https://www.dalibo.com/), the company where [Guillaume Lelarge](http://blog.guillaume.lelarge.info/) works (he does the [French translation of SQL Performance Explained](https://sql-au-coeur-des-performances.fr/?utm_source=use-the-index-luke.com&utm_campaign=blog-2013-dalibo-pgsession&utm_medium=web)) invited me to give a talk at their (mostly French) for-free conference “[Better Performance with PostgreSQL](https://www.pgsessions.com/archives.html#5)” on 28th March in Paris. Seats are limited: if you’d like to go there, register now!\n\n[Register Now](https://www.pgsessions.com/archives.html#5)\n\nAnd if you don’t speak French, there are other good news for you. [SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2013-dalibo-pgsession&utm_medium=web) is currently on sale at Amazon.co.uk for £25.00 (you save £1.99, -7%). Please note that this is the free-delivery threshold for these countries: Belgium, Denmark, Luxembourg, Netherlands, Andorra, Finland, Gibraltar, Greece, Iceland, Ireland, Italy, Liechtenstein, Norway, Portugal, San Marino, Spain, Sweden, Vatican city and Poland. They will also ship for free to UK of course.\n\n[Buy at Amazon.co.uk](https://www.amazon.co.uk/SQL-Performance-Explained-Markus-Winand/dp/3950307826/?_encoding=UTF8&m=AJFZUYB7XQGQN&tag=winandat-21&linkCode=ur2&camp=1634&creative=6738)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2048, "slov": 231, "odkazu": 57, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:11", "sha256": "aa5d223e2533bde390eefa5aff363b397b015b4e783939dac6553f71ec188500", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://www.dalibo.com/", "http://blog.guillaume.lelarge.info/", "https://sql-au-coeur-des-performances.fr/", "https://www.pgsessions.com/archives.html", "https://sql-performance-explained.com/", "https://www.amazon.co.uk/SQL-Performance-Explained-Markus-Winand/dp/3950307826/?_encoding=UTF8&camp=1634&creative=6738&linkCode=ur2&m=AJFZUYB7XQGQN&tag=winandat-21", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-02/fosdem-impressions", "titulek": "FOSDEM Impressions 2013 by Markus Winand", "h1": "FOSDEM Impressions", "popis": "FOSDEM Impressions 2013", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-02/fosdem-impressions", "jazyk": "en", "robots_meta": "", "og": {"og:title": "FOSDEM Impressions 2013 by Markus Winand", "og:description": "FOSDEM Impressions 2013", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "FOSDEM Impressions"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# FOSDEM Impressions\n\n---\n\nLast weekend I’ve visited the Free and Open source Software Developers’ European Meeting (FOSDEM) in Brussels, Belgium. It is a huge and free conference covering countless open source topics such as Open/Libre Office, Microkernels, MySQL, NoSQL, PostgreSQL, OWASP, and much more.\n\nOn the day before FOSDEM, Friday, I’ve been at the PgDay giving my talk “Pagination Done the PostgreSQL Way” [[slides](https://winand.at/sql-slides-for-developers)]. I think it was well received but I’m still curious to get the feedback from the feedback forms. So, if you have been there, please fill in the [feedback form](https://www.postgresql.eu/events/feedback/fosdem2013/)!\n\nHere you find a short list of notable talks. I’ve actually attended more, I’m just mentioning the most impressive ones.\n\nThe GNU/Hurd architecture, nifty features, and latest news\n\n[Hurd](https://en.wikipedia.org/wiki/GNU_Hurd) is still being released in two years. This has been funny 15 years ago, but is quite sad today. However, they aim to get a fully supported Debian distro based on Hurd by that time. Good luck. It seems that current virtualization developments (e.g. Linux containers) are a very good fit for the Hurd architecture, effectively not needing any changes to support containers natively.\n\nLightning talk: Spoiling and Counter-spoiling\n\nAn attempt to make a coding contest that honours maintainable code. The problem: how to measure it? The solution: make three contests: (1) one for writing maintainable code; (2) one for incorporating difficult bugs into that code; (3) and a last one to fix those bugs again. Add some statistics to that and you know who’s code had the best maintainability by measuring how long it took to find and fix the bugs. Funny idea, but not yet executed.\n\nPractical Security for developers, using OWASP ZAP\n\nPromising tool for security checks (brute force). Video available at the [homepage](https://owasp.org/www-project-zap).\n\nLightning talk: The C2 programming language\n\nAnother successor of C. It’s a minimalistic approach to just change what really hurts in C. That are a few syntax issues and the preprocessor (#include). At a very early stage. See [c2lang.org](https://c2lang.org/).\n\nHow to Share a Trademark\n\nAbout legal issues (e.g., Trademark vs. Registered Trademark). Some example cases from the open source scene.\n\nLightning talk: BIND 10: DNS by Cooperating Processes\n\nHave I ever mentioned that I used to be the DNS admin of an Austrian ISP? It’s more than 10 years ago, but I still hate BIND ;) Privately I’m only using [djbdns](https://cr.yp.to/djbdns.html) since then. One of the fundamental design principles of djbdns is that there is a separation of concerns (e.g., serving a zone authoritatively is different from acting as caching resolver). Guess what’s gonna be introduced in BIND 10 ;)\n\nPostGIS 2.0 and beyond\n\nReally interesting talk where PostGIS is coming from (1.5 releases) and how 2.0 differs from it. One of the nice things about PostGIS presentations is that they always have nice visualizations (by definition). There was also a PostGIS 3D talk at PgDay.\n\nWhen and How to Take Advantage of New Optimizer Features in MySQL 5.6\n\nI’ve been to another MySQL talks as well and I must say they don’t feel like FOSS talks. It’s just Oracle presenting. However, the topics presented are no surprise (e.g. Index Condition Pushdown, a.k.a. Index-Filterpredicates). The scary thing about this talk was that the examples almost always needed hits to work. Sure you could say that these are just made up examples, but I think it just a proof of the optimizers weakness if it needs all the time hints to do the “right thing”.\n\nA real-time architecture using Hadoop & Storm\n\nPresenting the “classical” batch/online mixture to handle BigData: Running Hadoop/MapReduce in Batches and processing the new data online (in memory). To get the full picture, you must query both of them.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 4524, "slov": 696, "odkazu": 57, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:13", "sha256": "53aec968d22d5ffecdf2d44a054e31ecf5641de87dca0575636ff38e7a9d7fea", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/sql-slides-for-developers", "https://www.postgresql.eu/events/feedback/fosdem2013/", "https://en.wikipedia.org/wiki/GNU_Hurd", "https://owasp.org/www-project-zap", "https://c2lang.org/", "https://cr.yp.to/djbdns.html", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-02/top-tweets", "titulek": "Top Tweets January 2013 selected by Markus Winand", "h1": "Top Tweets January 2013", "popis": "Top Tweets January 2013", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-02/top-tweets", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Top Tweets January 2013 selected by Markus Winand", "og:description": "Top Tweets January 2013", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Top Tweets January 2013"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Top Tweets January 2013\n\n---\n\nThis is a short collection of the best tweets on [@SQLPerfTips](https://x.com/SQLPerfTips) and/or [@MarkusWinand](https://x.com/MarkusWinand) for those who missed them and those who don’t use twitter at all.\n\nAs I’m late posting the January tweets, I also include an awesome picture taken at [FOSDEM](https://archive.fosdem.org/2023/) (February, technically).\n\n- RT [@kryskool](https://x.com/kryskool): You can see this at O Reilly stand at Fosdem ;) #postgres #fosdem [[tweet](https://x.com/kryskool/status/297626922861608962)]\n- RT [@CompSciFact](https://x.com/CompSciFact): “Technology is the name we have for stuff that doesn’t work yet.” -- Danny Hills [[tweet](https://x.com/CompSciFact/status/297104206433775617)]\n- RT [@highscal](https://x.com/highscal): NoSQL Parody: say No! No! and No! [highscalability.com](https://highscalability.com/nosql-parody-say-no-no-and-no/) [[tweet](https://x.com/highscal/status/294597623510351872)]\n- A SQL injection case study — s[securesolutions.no/why-its-easy-being-a-hacker/](https://web.archive.org/web/20240219030310/https://www.securesolutions.no/why-its-easy-being-a-hacker/) — In SPE (p32) I wrote: This section covers a topic that is skipped in most SQL textbooks… [[tweet](https://x.com/MarkusWinand/status/293299276799422464)]\n- «…hardcore SQL programmers call it “Volkswagen Programming”…» — Joe Celko about prefixing view names with “vw_” [linkedin.com](http://www.linkedin.com/groups/SQL-Server-Naming-Conventions-Standards-72017.S.196763294?view=&gid=72017&type=member&item=196763294#commentID_null) — [[tweet](https://x.com/MarkusWinand/status/290451101398999041)]\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2249, "slov": 235, "odkazu": 65, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:14", "sha256": "d233c10ea816624b96869f0d9114ca0817dea2df1854e27d220217374eb8bc2c", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://x.com/SQLPerfTips", "https://x.com/MarkusWinand", "https://archive.fosdem.org/2023/", "https://x.com/kryskool", "https://x.com/kryskool/status/297626922861608962", "https://x.com/CompSciFact", "https://x.com/CompSciFact/status/297104206433775617", "https://x.com/highscal", "https://highscalability.com/nosql-parody-say-no-no-and-no/", "https://x.com/highscal/status/294597623510351872", "https://www.securesolutions.no/why-its-easy-being-a-hacker/", "https://x.com/MarkusWinand/status/293299276799422464", "http://www.linkedin.com/groups/SQL-Server-Naming-Conventions-Standards-72017.S.196763294?gid=72017&item=196763294&type=member&view=", "https://x.com/MarkusWinand/status/290451101398999041", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-03/Party-Time", "titulek": "Party time: Discounts on SQL Performance Explained due to the launch of the French edition", "h1": "Party time", "popis": "Party time", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-03/Party-Time", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Party time: Discounts on SQL Performance Explained due to the launch of the French edition", "og:description": "Party time", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Party time"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Party time\n\n---\n\nGood news everybody. I’m in a good mood today ;) I’ll explain. First of all, the French edition of [SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2013-give-away&utm_medium=web) is almost done and will ship at the end of the month ([pre-order](https://sql-au-coeur-des-performances.fr/?utm_source=use-the-index-luke.com&utm_campaign=blog-2013-give-away&utm_medium=web) now ;). It has a different name ([SQL : Au cœur des performances](https://sql-au-coeur-des-performances.fr/?utm_source=use-the-index-luke.com&utm_campaign=blog-2013-give-away&utm_medium=web)) but is otherwise the same. So, that triggered some kind of “project done” feeling.\n\nFurther, I’ve given a few good [trainings](https://winand.at/sql-training/inhouse) recently and looking forward for some more in the next weeks. It’s just awesome when the audience comes up with great questions, but it’s even more awesome if they come up with great conclusions that proof their correct understanding. That triggers a “missing accomplished” feeling.\n\nSo, as the pre-sale of the French edition is running on a 10% discount, I though why not giving a general 10% discount to celebrate the French edition? And here it is: “aucoeur”. It’s only valid for order placed directly at [http://sql-performance-explained.com/](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2013-give-away&utm_medium=web) (not valid on Amazon) and expires on March 28 (the release date of the French edition).\n\nFurther, I’ll repeat the “[retweet to win](https://x.com/SQLPerfTips/status/302497813726638081)” campaign every week during March. It goes like this: I’ll tweet something like “Retweet this for a chance to win”. After a while, I’ll select one of the retweeters as winner. You can’t win twice (sorry [@d_gustafsson](https://x.com/SQLPerfTips/status/302543274864963584)). So, watch out, the first giveaway tweet comes soon.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2602, "slov": 344, "odkazu": 56, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:14", "sha256": "082382fbd8ce2a51ee016f31b9e8db753fd3ef23dc3e23a2e520618c25a2b23b", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://sql-performance-explained.com/", "https://sql-au-coeur-des-performances.fr/", "https://winand.at/sql-training/inhouse", "https://x.com/SQLPerfTips/status/302497813726638081", "https://x.com/SQLPerfTips/status/302543274864963584", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-04/i-need-your-help", "titulek": "I need your help: take my survey for a chance to win a DON'T PANIC towel!", "h1": "I need your help!", "popis": "I need your help!", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-04/i-need-your-help", "jazyk": "en", "robots_meta": "", "og": {"og:title": "I need your help: take my survey for a chance to win a DON'T PANIC towel!", "og:description": "I need your help!", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "I need your help!"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# I need your help!\n\n---\n\nHi!\n\nWould you please spare me a few minutes and help me a little bit?\n\nAs you might know—or maybe not—I’m making my living as an *independent* trainer and consultant. Up till now I’ve only delivered on-site training at the clients’ site, but I though it makes sense to offer open trainings as well so that singe participants can also join. For that I’d need to know how many people would like to join such a training, where they are physically located, and which database they are using. So, I’ve set up a short survey:\n\n[http://winand.at/services/sql-performance-training/survey](https://winand.at/sql-training/inhouse)\n\nIt’s just one form and won’t take much time. Naturally, you are under no obligation if you fill out the form, and as a way of saying thank you for your time, I’ll be drawing three participants to receive a [DON’T PANIC towel](https://winand.at/sql-training/inhouse)—the perfect preparation for the upcoming [Towel Day on 25th May](https://en.wikipedia.org/wiki/Towel_Day). So take a minute to complete the survey now because the deadline is 26th of April!\n\nThanks,\n\n-markus\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1760, "slov": 255, "odkazu": 54, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:15", "sha256": "0aef0f9774ef32f78ecce0ef4218b1f842f224ed9723bd7b084e16c8fe675534", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/sql-training/inhouse", "https://en.wikipedia.org/wiki/Towel_Day", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-04/the-two-top-performance-problems-caused-by-ORM-tools", "titulek": "The infamous N+1 selects problem and the hardly-known Index-Only Scan are the most common SQL performance problems caused by ORM tools like Hibernate.", "h1": "The two top performance problems caused by ORM tools", "popis": "The two top performance problems caused by ORM tools", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-04/the-two-top-performance-problems-caused-by-ORM-tools", "jazyk": "en", "robots_meta": "", "og": {"og:title": "The infamous N+1 selects problem and the hardly-known Index-Only Scan are the most common SQL performance problems caused by ORM tools like Hibernate.", "og:description": "The two top performance problems caused by ORM tools", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "The two top performance problems caused by ORM tools"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# The two top performance problems caused by ORM tools\n\n---\n\n“[*ORMs are not entirely useless…*](https://x.com/SQLPerfTips/status/326599395627905024)” I just tweeted in response to a not exactly constructive message that we should fire developers who want to use ORMs. But than I continued in a not exactly constructive tone myself when I wrote “*…the problem is that the ORM authors don’t know anything about database performance*”.\n\nWell, I don’t think they “don’t know anything” but I wonder why they don’t provide decent solutions (including docs) for the two most striking performance problems caused by ORMs? Here they are:\n\nThe infamous N+1 selects problem\n\n[This problem](/sql/join/nested-loops-join-n1-problem) is actually well-known and I believe there are working solutions in all recent ORMs. The problem that remains is about documentation and culture: although there are solutions, many developers are not aware of them or still live in the “joins are slow—let’s avoid them” universe. The N+1 selects problem seems to be on the decline but I still think ORMs’ documentation should put more emphasis on joins.For me, it looks very similar to the [SQL injection](https://owasp.org/www-community/attacks/SQL_Injection) topic: each and every database access layer provides bind parameters but the documentation and books just show examples using literal values. The result: SQL injection was the most dangerous weakness in the [CWE/SANS Top 25 list](https://cwe.mitre.org/top25/). Not because the tools don’t provide proper ways to close that hole, but because the examples don’t use them consistently.\n\nThe hardly-known Index-Only Scan\n\nAlthough the [Index-Only Scan](/sql/clustering/index-only-scan-covering-index) is one of the most powerful SQL tuning techniques, it seems to be hardly known by developers (related [SO question](https://dba.stackexchange.com/questions/39603/should-i-separate-frequently-updated-columns/39606#39606) I was involved in recently). However, I’ll try to make the story short.Whenever a database uses an index to find the requested data quickly, it can also use the information in the index to deliver the queried data itself—if the queried data is available in the index. Example:`CREATE TABLE demo\n ( last_name VARCHAR(255)\n , first_name VARCHAR(255)\n -- more columns and constraints\n );\n\nCREATE INDEX ios_demo\n ON demo (last_name, first_name);\n\nSELECT last_name, first_name\n FROM demo\n WHERE last_name = ?;`If the database uses the `IOS_DEMO` index to find the rows in question, it can directly use the first name that is stored along with the last name in the index and deliver the queries’ result right away without accessing the actual table. That saves a lot of IO—especially when you are selecting more than a few rows. This technique is even more useful (important) for databases that use clustered indexes like SQL Server or MySQL+InnoDB because they have an [extra level of indirection between the index and the table data](/sql/clustering/index-organized-clustered-index).Did you see the crucial prerequisite to make an Index-Only Scan happen? Or asking the other way around: what’s a good way to make sure you’ll never get an Index-Only Scan? Yes, selecting all columns is the most easy yet effective Index-Only-Scan-Preventer. And now guess who is selecting all the columns all the time on behalf of you? Your good old friend the ORM-tool.This is where the tool support is really getting sparse. Selecting [partial objects is hardly supported by ORMs](/sql/join/hash-join-partial-objects). If it is supported then often in a very inconvenient way that doesn’t give runtime control over the columns you’d like to select. And for gods sake, let’s forget about the documentation for a moment. To say it straight: using Index-Only Scans is a pain in the a** with most ORMs.Besides Index-Only Scans, not selecting everything can also improve sorting, grouping and [join performance](/sql/join/hash-join-partial-objects) because the database can save memory that way.\n\nWhat we would actually need to get decent database performance is a way to declare which information we are going to need in the upcoming unit of work. Malicious tongues might now say “that’s SQL!” And it’s true (in my humble opinion). However, I do acknowledge that ORMs reduce boilerplate code. Luckily they often offer an easier language than SQL: their whatever-QL (like HQL). Although the syntactic difference between SQL and whatever-QL is often small, the semantic difference is huge because they don’t work on tables and columns but on objects and classes. That avoids a lot of typing and feels more natural to developers from the object world. Of course, the whatever-QL needs to support everything we need—also partial objects like in this [Doctrine example](/sql/join/hash-join-partial-objects#orm-partial-objects).\n\nAfter all, I think ORM documentation should be more like this: first introduce whatever-QL as simplified SQL dialect that is the default way to query the database. Those methods that are currently mentioned first (e.g., `.find` or `.byId`) should be explained as a shortcut if you really need only one row from a single table.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 5761, "slov": 890, "odkazu": 60, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:17", "sha256": "909f0002a9cba6a34334b1c10a970020c2009909906c44f5ca36b74f2328d4d0", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://x.com/SQLPerfTips/status/326599395627905024", "https://owasp.org/www-community/attacks/SQL_Injection", "https://cwe.mitre.org/top25/", "https://dba.stackexchange.com/questions/39603/should-i-separate-frequently-updated-columns/39606", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-04/whats-left-of-nosql", "titulek": "When Google announced their scalable SQL Database F1 one might wonder what’s left of the NoSQL movement if we add SQL again? An analysis.", "h1": "What’s left of NoSQL?", "popis": "What’s left of NoSQL if they start adding ACID and SQL support?", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-04/whats-left-of-nosql", "jazyk": "en", "robots_meta": "", "og": {"og:title": "When Google announced their scalable SQL Database F1 one might wonder what’s left of the NoSQL movement if we add SQL again? An analysis.", "og:description": "What’s left of NoSQL if they start adding ACID and SQL support?", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "What’s left of NoSQL?"}, {"uroven": 2, "text": "Top Dog SQL"}, {"uroven": 2, "text": "And Then: NoSQL"}, {"uroven": 2, "text": "Nevertheless: Back to SQL"}, {"uroven": 2, "text": "What’s left of NoSQL?"}, {"uroven": 4, "text": "Related"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# What’s left of NoSQL?\n\n---\n\n*This is my own and very loose translation of an article I wrote for the Austrian newspaper [derStandard.at](https://www.derstandard.at/consent/tcf/1381368486902/Was-bleibt-von-NoSQL) in October 2013. As this article was very well received and the SQL vs. NoSQL discussion is currently hot again, I though it might be a good time for a translation.*\n\nBack in 2013 [The Register](https://www.theregister.com/software/2013/08/30/google-goes-back-to-the-future-with-sql-f1-database/937689) reported that Google sets its bets on SQL again. On the first sight this might look like a surprising move because it was of all things Google’s publications about [MapReduce](https://research.google/pubs/mapreduce-simplified-data-processing-on-large-clusters/) and [BigTable](https://research.google/pubs/bigtable-a-distributed-storage-system-for-structured-data/) that gave the NoSQL movement a big boost in the first place. On a second sight it turns out that there is a trend to use SQL or similar languages to access data from NoSQL systems—and that’s not even a new trend. However, it raises a question: What remains of NoSQL if we add SQL again? To answer this question, I need to start with a brief summary about the history of databases.\n\n## Top Dog SQL\n\nIt was undisputed for decades: store enterprise data in a relational database and use the programming language SQL to process the stored data.\n\nThe theoretical foundation for this approach, the relational model, was laid down as early as 1970. The first commercial representative of this new database type became available in 1979: the [Oracle Database in release 2](https://en.wikipedia.org/wiki/Oracle_database#History). Todays appearance of relational databases was mainly coined in the 1980s. The most important milestones were the formalization of the [ACID criteria](https://en.wikipedia.org/wiki/ACID) (Atomicity, Consistency, Isolation, Durability), which avoid accidental data corruption, and the standardization of the [query language SQL](https://en.wikipedia.org/wiki/Sql)—first by ANSI, one year later by ISO. From this time on SQL and ACID compliance were desirable goals for database vendors.\n\nAt first glance there were no major improvements during the next decades. The result: SQL and the relational model are sometimes called old or even outdated technology. At a closer look SQL databases evolved into mature products during that time. This process took that long because SQL is a declarative language and was way ahead of the technical possibilities of the 1980s. “Declarative language” means that SQL developers don’t need to specify the steps that lead to the desired result as with imperative programming, they just describe the desired result itself. The database finds the most efficient way to gather this result automatically—which is by no means trivial so that early implementations only mastered it for simple queries. Over these decades, however, the hardware got more powerful and the software more advanced so that modern databases deliver good results for complex queries too (see [here](https://sql-performance-explained.com/l?utm_source=use-the-index-luke.com&utm_campaign=blog-201404-nosql&utm_medium=web&utm_content=top-dog-sql) if it doesn’t work for you).\n\nIt is especially important to note that the capabilities of SQL are not limited to storing and fetching data. In fact, SQL was designed to make refining and transforming data easy. Without any doubt, that was an important factor that made SQL and the relational model the first choice when it comes to databases.\n\n## And Then: NoSQL\n\nDespite the omnipresence of SQL, a new trend emerged during the past few years: NoSQL. This term alone struck the nerve of many developers and caused a rapid spread that ultimately turned into a religious war. The opponents were SQL as symbol for outdated, slow, and expensive technology on the one side against an inhomogeneous collection of new, highly-scalable, free software that is united by nothing more than the umbrella brand “NoSQL.”\n\nOne possible explanation for the lost appreciation of SQL among developers is the increasing popularity of object-relational mapping tools (ORM) that generally tend to reduce SQL databases to pure storage media (“persistence layer”). The possibility to refine data using SQL is not encouraged but considerably hindered by these tools. The result of the [excessive use](https://plus.google.com/+GavinKing/posts/LGJU1NorAvY) is a step-by-step processing by the application. Under this circumstances SQL does indeed not deliver any additional value and it becomes understandable why so many developers sympathise with the term NoSQL.\n\nBut the problem is that the term NoSQL was not aimed against SQL in the first place. To make that clear the term was defined to mean “not only SQL” later on. Thus, NoSQL is about complementary alternatives. To be precise it is not even about alternatives to SQL but about alternatives to the relational model and ACID. In the meantime the [CAP theorem](https://en.wikipedia.org/wiki/CAP_theorem) revealed that the ACID criteria will inevitably reduce the availability of *distributed* databases. That means that traditional, ACID compliant, databases cannot benefit from the virtually unlimited resources available in cloud environments. This is what many NoSQL systems provide a solution for: instead of sticking to the very rigid ACID criteria to keep data 100% consistent all the time they accept temporary inconsistencies to increase the availability in a distributed environment. Simply put: in doubt they prefer to deliver wrong (old) data than no data. A more correct but less catchy term would therefore be NoACID.\n\nDeploying such systems only makes sense for applications that don’t need strict data consistency. These are quite often applications in the social media field that can still fulfil their purpose with old data and even accept the loss of some updates in case of service interruption. These are also applications that could possibly need the unlimited scalability offered by cloud infrastructure. If a central database is sufficient, however, the CAP theorem does not imply a compelling reason to abandon the safety of ACID. However, using NoSQL systems can still make sense in domains where SQL doesn’t provide sufficient power to process the data. Interestingly, this problem is also very dominant in the social media field: although it is easy to express a social graph in a relational model it is rather cumbersome to analyse the edges using SQL.\n\n## Nevertheless: Back to SQL\n\nNotwithstanding the above, SQL is still a very good tool to answer countless questions. This is also true for questions that could not be foreseen at the time of application design—a problem many NoSQL deployments face after the first few years. That’s probably also the cause for the huge demand for powerful and generic query languages like SQL.\n\nAnother aspect that strengthens the trend back to SQL goes to the heart of NoSQL: without ACID it is very difficult to write reliable software. Google said that very clearly in their paper about the F1 database: without ACID “we find developers spend a significant fraction of their time building extremely complex and error-prone mechanisms to cope with eventual consistency and handle data that may be out of date.” Apparently you only learn to appreciate ACID once you lost it.\n\n## What’s left of NoSQL?\n\nIf SQL and ACID become the flavor of the time again you may wonder what’s left of the NoSQL movement? Did it really waste half a decade like [Jack Clark speculated at The Register](https://www.theregister.com/software/2013/08/30/google-goes-back-to-the-future-with-sql-f1-database/937689)? One thing we can say for sure is that SQL and ACID conformity are still desirable goals for database vendors. Further we know that there is a trade-off between ACID and scalability in cloud environments.\n\nOf course, the race for the Holy Grail of the ideal balance between ACID and scalability has already begun. The NoSQL systems entered the field from the corner of unlimited scalability and started adding tools to control data consistency such as [causal consistency](https://queue.acm.org/detail.cfm?id=2610533). Obviously there a newcomers that use the term NewSQL to jump on the bandwagon by developing completely new SQL databases that bring ACID and SQL from the beginning but use NoSQL ideas internally to improve scalability.\n\nAnd what about the established database vendors? They want to make us believe they are doing NoSQL too and release products like the “Oracle NoSQL Database” or “Windows Azure Table Storage Service.” The intention to create these products for the sole purpose to ride the hype is so striking that one must wonder why they treat neither NoSQL nor NewSQL as a serious threat to their business? When looking a the Oracle Database in it’s latest release 12*c*, we can even see the opposite trend. Although the version suffix “c” is ought to express its cloud capability it doesn’t change the fact that the killer feature of this release serves a completely different need: the easy and safe operation of multiple databases on a single server. That’s the exact opposite of what many NoSQL systems aim for: running a giant database on a myriad of cheap commodity servers. Virtualization is a way bigger trend than scale-out.\n\nIs it even remotely possible that the established database vendors underwent such a fundamental misjudgment? Or is it more like that NoSQL only serves a small market niche? How many companies really need to cope with data at the scale of Google, Facebook or Twitter? Incidentally three companies that grew up on the open source database MySQL. One might believe the success of NoSQL is also based on the fact that it solves a problem that everybody would love to have. In all reality this problem is only relevant to a very small but prominent community, which managed to get a lot of attention. After all, also judging on the basis that the big database vendors don’t show a serious engagement, NoSQL is nothing more than a storm in a teacup.\n\n#### Related\n\n- [MongoDB seems to be as Bad for NoSQL as MySQL is for SQL](/blog/2013-10/mysql-is-to-sql-like-mongodb-to-nosql)\n- [Choosing NoSQL For The Right Reason](https://blog.fatalmind.com/2011/05/13/choosing-nosql-for-the-right-reason/)\n- [“Just because you’re using Hibernate, doesn’t mean you have to use it for *everything*.”](https://plus.google.com/+GavinKing/posts/LGJU1NorAvY) — Gavin King, creator of Hibernate\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 11135, "slov": 1711, "odkazu": 64, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:18", "sha256": "7b40b033a645638faa0c83fd54dc11c62b7754f4ceac771b5e86c11de366158d", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://www.derstandard.at/consent/tcf/1381368486902/Was-bleibt-von-NoSQL", "https://www.theregister.com/software/2013/08/30/google-goes-back-to-the-future-with-sql-f1-database/937689", "https://research.google/pubs/mapreduce-simplified-data-processing-on-large-clusters/", "https://research.google/pubs/bigtable-a-distributed-storage-system-for-structured-data/", "https://en.wikipedia.org/wiki/Oracle_database", "https://en.wikipedia.org/wiki/ACID", "https://en.wikipedia.org/wiki/Sql", "https://sql-performance-explained.com/l", "https://plus.google.com/+GavinKing/posts/LGJU1NorAvY", "https://en.wikipedia.org/wiki/CAP_theorem", "https://queue.acm.org/detail.cfm?id=2610533", "https://blog.fatalmind.com/2011/05/13/choosing-nosql-for-the-right-reason/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-05/training-and-conference-dates", "titulek": "Training and Conference Dates 2013 by Markus Winand", "h1": "Training and Conference Dates", "popis": "Training and Conference Dates 2013", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-05/training-and-conference-dates", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Training and Conference Dates 2013 by Markus Winand", "og:description": "Training and Conference Dates 2013", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Training and Conference Dates"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Training and Conference Dates\n\n---\n\nA few weeks ago I invited you to take part in a survey about your interest in SQL performance training for developers. In the meanwhile there is a schedule for [German](https://winand.at/de/sql-training/5-tages-kurs) and [English](https://winand.at/sql-training/inhouse) trainings available. In particular, I’d like to point out [four online courses](https://winand.at/sql-training/inhouse) I’m giving during summer time. Hope to see you there.\n\nAnother opportunity for a short get-together are conferences I’ll attend and/or speak at. The next one is the [Prague PostgreSQL Developers’ Day (p2d2)](https://p2d2.cz/en/) next Thursday. You can buy [SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2013-dates&utm_medium=web) there (CZK 700; in the breaks and after the conference). The next conference that I can already confirm is this years [PostgreSQL Conference Europe](https://2013.pgconf.eu/) in Dublin end of October. You might have noticed that I attended a lot of PostgreSQL conferences recently (Brussels in February, Paris in March). I do plan to attend other conferences too and I’ve just filed some proposals for talks at other conferences. I’ll let you know if they are accepted.\n\nOne more thing: in case you are involved in the organization of developer and/or database centric event—no matter how small—you might want to ask about [sponsoring](https://winand.at/contact) I can offer.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2110, "slov": 283, "odkazu": 57, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:19", "sha256": "5603ec01edaabd69c98270ef165c014427002c7e2ba700332901ed6fb2460391", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/de/sql-training/5-tages-kurs", "https://winand.at/sql-training/inhouse", "https://p2d2.cz/en/", "https://sql-performance-explained.com/", "https://2013.pgconf.eu/", "https://winand.at/contact", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-07/about-query-optimizer-hints", "titulek": "About Optimizer Hints in Oracle, SQL Server, MySQL and even PostgreSQL.", "h1": "About Optimizer Hints: Prefer supportive and avoid restrictive SQL hints", "popis": "About Optimizer Hints", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-07/about-query-optimizer-hints", "jazyk": "en", "robots_meta": "", "og": {"og:title": "About Optimizer Hints in Oracle, SQL Server, MySQL and even PostgreSQL.", "og:description": "About Optimizer Hints", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "About Optimizer Hints: Prefer supportive and avoid restrictive SQL hints"}, {"uroven": 2, "text": "Combined Selectivity Example"}, {"uroven": 2, "text": "And Then There Was PostgreSQL"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# About Optimizer Hints: Prefer supportive and avoid restrictive SQL hints\n\n---\n\nQuite often I’m asked what I think about query hints. The answer is more lengthy and probably also more two-fold than most people expect it to be. However, to answer this question once and forever, I though I should write it down.\n\nThe most important fact about query hints is that not all query hints are born equally. I distinguish two major types:\n\nRestricting Hints\n\nMost query hints are restricting hints: they limit the optimizers’ freedom to choose an execution plan. “Hint” is an incredibly bad name for these things as they *force* the optimizer to do what it has been told—probably the reason MySQL uses the [`FORCE`](https://dev.mysql.com/doc/refman/8.0/en/index-hints.html) keyword for those.I do not like restricting hints, yet I use them sometimes to test different execution plans. It usually goes like this: when I believe a different execution plan could (should?) give better performance, I just hint it to see if it really gives better performance. Quite often it becomes slower and sometimes I even realize that the execution plan I though of does not work at all—at least not with the database I’m working on at that moment.Typical examples for restricting query hints are hints that force the database to use or not to use a particular index (e.g., [`INDEX` and `NO_INDEX`](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Comments.html#GUID-EC0D9F8A-20E7-4281-A16A-6B9C993F2930) in the Oracle database, [`USE INDEX` and `IGNORE INDEX`](https://dev.mysql.com/doc/refman/8.0/en/index-hints.html) in MySQL, or [`INDEX`, `FORCESEEK` and the like](https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table) in SQL Server).So, what’s wrong with them? Well, the two main problems are that they (1) restrict the optimizer and that they (2) often need volatile object names as parameters (e.g., index names). Example: if you use a hint to use index `ABC` for a query, the hint becomes ineffective when somebody changes the name of the index to `ABCD`. Further, if you restrict the optimizer you can no longer expect it to adjust the execution plan if you add another index that servers the query better. Of course there are ways around these problems. The Oracle database, for example, offers [“index description” hints](https://jonathanlewis.wordpress.com/2013/06/23/index-hints-2/) to avoid both issues: instead of specifying the index name, it accepts a description of the ideal index (column list) and it selects the index that matches this definition best.Nevertheless, I strongly recommend against using restricting query hints in production. Instead you should find out why the optimizer does “the wrong thing”™ and fix the root cause. Restricting hints fix the symptom, not the cause. That being said, I know that there is sometimes no other reasonable choice.\n\nSupporting Hints\n\nThe second major type of query hints are supporting hints: they support the optimizer by providing information it doesn’t have otherwise. Supporting hints are rare—I’m only aware of a few good examples and the most useful one has already become obsolete: it’s [`FAST` *number_rows*](https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-query) (SQL Server) and [`FIRST_ROWS(n)`](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Comments.html#GUID-CEA66568-0168-4AE2-AD3B-FE86CDD73894) (Oracle). They tell the optimizer that the application plans to fetch only that many rows of the result. Consequently, the optimizer can prefer using indexes and nested loop joins that would be inefficient when fetching the full result (see [Chapter 7, Partial Results](/sql/partial-results) for more details). Although being kind-of obsolete, I’m still using these hints as the defining example for supporting hints because they provide information the optimizer cannot have otherwise. This particular example is important enough that it was worth defining new keywords in the ISO SQL:2008: `FETCH FIRST ... ROWS ONLY` and `OFFSET`. That’s why this hint is a very good, yet obsolete example for supporting query hints.Another example for supporting hints is the (undocumented) `CARDINALITY` hint of the Oracle database. It basically overwrites the row count estimate of sub-queries. This hint was often used if the combined selectivity of two predicates was way off the product of the selectivity of each individual predicate (see *Combined Selectivity Example*). But this hint is also outdated since Oracle database 11g introduced [extended statistics](https://blogs.oracle.com/optimizer/extended-statistics) to cope with issues like that. SQL Server’s [filtered statistics](https://learn.microsoft.com/en-us/archive/blogs/psssql/case-of-using-filtered-statistics) serve the same purpose. If your database cannot reflect data correlation in it’s statistics, you’ll need to fall back to restricting hints.The Oracle hint `OPT_ESTIMATE` is somehow the successor of the `CARDINALITY` hint for cases when the estimations are still off. Pythian wrote a [nice article about `OPT_ESTIMATE`](https://www.pythian.com/blog/oracles-opt_estimate-hint-usage-guide).Combined Selectivity ExampleLet’s say we have two Y/N columns and each has a 50:50 distribution. When you select using both columns most optimizers estimate that the query matches 25% of the table (by multiplying two times 50%). That means that the optimizer assumes there is no correlation between those two columns.Column 1Column 2count(*)YY25YN25NY25NN25If there is a correlation, however, so that most rows that have Y in one column also have Y in the other column, then the estimate is way off.Column 1Column 2count(*)YY49YN1NY1NN49If you query one of the rare Y/N combinations, the optimizer might refrain from using an index due to the high cardinality estimate. Nevertheless, it would be better to use the index because this particular combination is very selective.\n\nIt think supporting hints are not that bad: they are just a way to cope with known limitations of the optimizer. That’s probably why they tend to become obsolete when the optimizers evolve.\n\n## And Then There Was PostgreSQL\n\nYou might have noticed that I did not mention PostgreSQL. It’s probably because [PostgreSQL doesn’t have query hints](https://web.archive.org/web/20171119065414/http://it.toolbox.com/blogs/database-soup/why-postgresql-doesnt-have-query-hints-44121) although [it has](http://thoughts.davisjeff.com/2011/02/05/why-postgresql-already-has-query-hints/) (which are actually [session parameters](https://www.postgresql.org/docs/current/runtime-config-query.html)). Confused? No problem, there is a [short Wiki](https://wiki.postgresql.org/wiki/OptimizerHintsDiscussion) for that.\n\nHowever, to see some discussion about introducing a similar hint as `CARDINALITY` described above or implementing “cross column statistics” read the first few messages in [this thread from February 2011](https://www.postgresql.org/message-id/flat/95E9B329-CE40-495D-B954-B1FB9B6ADDA4%40cybertec.at) (after the first page, the discussion moves to another direction). And the result? PostgreSQL still doesn’t have a good way to cope with the original problem of column correlation. **UPDATE 2017-10-25 for PostgreSQL 10:** Now it has [extended statistics for column correlation](https://www.postgresql.org/docs/10/sql-createstatistics.html).\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 7977, "slov": 1126, "odkazu": 67, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:20", "sha256": "699efdef12d6bb0854d835457ae4c11367576b93a91aff9eb06ea4910b9fa513", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://dev.mysql.com/doc/refman/8.0/en/index-hints.html", "https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Comments.html", "https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table", "https://jonathanlewis.wordpress.com/2013/06/23/index-hints-2/", "https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-query", "https://blogs.oracle.com/optimizer/extended-statistics", "https://learn.microsoft.com/en-us/archive/blogs/psssql/case-of-using-filtered-statistics", "https://www.pythian.com/blog/oracles-opt_estimate-hint-usage-guide", "http://it.toolbox.com/blogs/database-soup/why-postgresql-doesnt-have-query-hints-44121", "http://thoughts.davisjeff.com/2011/02/05/why-postgresql-already-has-query-hints/", "https://www.postgresql.org/docs/current/runtime-config-query.html", "https://wiki.postgresql.org/wiki/OptimizerHintsDiscussion", "https://www.postgresql.org/message-id/flat/95E9B329-CE40-495D-B954-B1FB9B6ADDA4@cybertec.at", "https://www.postgresql.org/docs/10/sql-createstatistics.html", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-07/afraid-of-ssd", "titulek": "SSD for SQL databases like PostgreSQL, Oracle or MySQL have a catch: the better your system is tuned, the more benefit your get from SSD.", "h1": "Afraid of SSD? Will SSD kill the profession of database and SQL tuning specialists?", "popis": "Afraid of SSD?", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-07/afraid-of-ssd", "jazyk": "en", "robots_meta": "", "og": {"og:title": "SSD for SQL databases like PostgreSQL, Oracle or MySQL have a catch: the better your system is tuned, the more benefit your get from SSD.", "og:description": "Afraid of SSD?", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Afraid of SSD? Will SSD kill the profession of database and SQL tuning specialists?"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Afraid of SSD? Will SSD kill the profession of database and SQL tuning specialists?\n\n---\n\nWhen clients tell me about their plans to invest in SSD storage for their database, they often look at me like a doctor telling a patient about his deadly disease. I didn’t discuss this with my clients until recently, when one client just asked me straight away: “As SQL tuning guy, are you afraid of SSD because it kills your job?” Here is what I told that client.\n\nGenerally, people seem to believe that SSD are just much faster than HDD. As a matter of fact, this is only partially true because—as I also mentioned in [Chapter 3](/sql/testing-scalability/response-time-throughput-scaling-horizontal)—performance has two dimensions: response time and throughput. Although SSDs tend to deliver more performance on both axes, it has to be considered that the throughput delivered by SSD is “only” about five times as high as that of HDDs. That’s because HDDs are not bad at sequential read/write operations anyway.\n\nSure enough a five times faster storage makes many performance problems go away…for a while…until you have five times more data. For a decently growing start-up it might just take a few months until you have the same problem again. However, this is not the crucial point here. The crucial point is that SSDs essentially fix the one performance issue where HDDs are really bad at: the response time. Due to the lack of moving parts, the response time of SSDs is about *fifty times* faster as that of HDDs. Well, that really helps solving problems for a while.\n\nHowever, there is a catch—maybe even a [Catch-22](https://en.wikipedia.org/wiki/Catch-22_(logic)): If you want to get the factor 50 speed-up of SSDs, you’d better avoid reading large chunks of sequential data, because that’s where you can only gain a factor five improvement. To put that into database context: if you are doing many full table scans, you won’t get the full potential of SSD. On the other hand, index lookups have a tendency to cause many random IO operations and can thus benefit from the fast response time of SSDs. The fun part is that properly indexed databases get better benefits from SSD than poorly indexed ones. But guess who is most desperately betting on SSD to solve their performance problems? People having proper indexes or those who don’t have them?\n\nThe story goes on: which database operation do you think causes most random IO operations? Of course it’s our old friend the join—it is the sole purpose of joins to gather many little data fragments from different places and combine them into the result we want. Joins can also greatly benefit from SSDs. SSDs actually voids one of arguments often brought up by NoSQL folks against relational databases: with SSD it doesn’t matter that much if you fetch data from one place or from many places.\n\nTo conclude what I said to my client: No, as an indexing-focused SQL performance guy, I’m absolutely not afraid of SSD.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3566, "slov": 582, "odkazu": 53, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:21", "sha256": "e0185e7050cd456ff8ba2fc79ce1c7e580f674cec76e20f1f85004f1a5f7be3c", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://en.wikipedia.org/wiki/Catch-22_(logic)", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-07/indexes-the-neglected-performance-all-rounder", "titulek": "Indexes: The neglected performance all-rounder", "h1": "Indexes: The neglected performance all-rounder", "popis": "Party time", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-07/indexes-the-neglected-performance-all-rounder", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Indexes: The neglected performance all-rounder", "og:description": "Party time", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Indexes: The neglected performance all-rounder"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Indexes: The neglected performance all-rounder\n\n---\n\nI think I’ve actually never shared the slides of my talk given in Paris at [Dalibo’s](https://dalibo.com/) PostgreSQL Session about Performance. So, here they are.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 825, "slov": 106, "odkazu": 52, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:22", "sha256": "cbecfc63c7ad551300247fe3a163607757ce21c2477f19231d4a9c9bc0513b12", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://dalibo.com/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-07/pagination-done-the-postgresql-way", "titulek": "Pagination Done the Right Way", "h1": "Pagination Done the Right Way", "popis": "Fetching results in a page-wise manner: Don’t use OFFSET to avoid a performance problem also known as “The Ramp”.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-07/pagination-done-the-postgresql-way", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Pagination Done the Right Way", "og:description": "Fetching results in a page-wise manner: Don’t use OFFSET to avoid a performance problem also known as “The Ramp”.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Pagination Done the Right Way"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Pagination Done the Right Way\n\n---\n\nHere is another slide deck for my “Pagination Done the Right Way” talk that I’ve given at many occasions.\n\nPlease also have a look at this blog post by Cary Millsap about “[The Ramp](https://carymillsap.blogspot.com/2010/04/ramp.html)”. Do you see how using OFFSET implements this anti-pattern?\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 938, "slov": 125, "odkazu": 52, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:23", "sha256": "40fd16e0a094a6ee088edc41163c9bae2c786bccd51f073484d51ceaffb61c8c", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://carymillsap.blogspot.com/2010/04/ramp.html", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-08/its-not-about-the-star-stupid", "titulek": "Asking for unnecessary columns causes unnecessary SQL performance problems", "h1": "Don’t ask for what you don’t need", "popis": "It is not about the star, stupid: selecting unnecessary columns is bad", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-08/its-not-about-the-star-stupid", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Asking for unnecessary columns causes unnecessary SQL performance problems", "og:description": "It is not about the star, stupid: selecting unnecessary columns is bad", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Myth Directory"], "osnova": [{"uroven": 1, "text": "Don’t ask for what you don’t need"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Don’t ask for what you don’t need\n\n---\n\n`select *` has a bad reputation. Most people think it is because changes in the table definition cause hard-to-detect bugs. Listing all columns in the desired order solves that problem, right? Yes, but that doesn’t solve the second problem of `select *`.\n\nThe other problem is that asking for more columns causes more work for the database. The surprise is that the performance impact can be huge.\n\nUp to 100x slower when preventing an Index-Only Scan\n\nBroadly speaking, the less columns you ask for, the less data must be loaded from disk when processing your query. However, this relationship is *non-linear*.Quite often, selecting from a table involves two steps: (1) use an index to find the address where the selected rows are stored; (2) load the selected rows from the table. Now imagine that you are just selecting columns that are present in the index. Why should the database still perform the second step? In fact, most databases don’t. They can process your query just with the information stored in the index—hence [index-only scan](/sql/clustering/index-only-scan-covering-index).But why should an index-only scan be 100 times faster? Simple: an ideal index stores the selected rows next to each other. It’s not uncommon that each index page holds about 100 rows—a ballpark figure; it depends on the size of the indexed columns. Nonetheless, it means that one IO operation might fetch 100 rows. The table data, on the other hand, is not organized like that ([exceptions](/sql/clustering/index-organized-clustered-index)). Here it is quite common that a page just contains one of the selected rows—along with many other rows that are of no interest for the particular query. So, the reason an Index-Only Scan can be 100 times faster is that an index access can easily deliver 100 rows per IO while the table access typically just fetches a few rows per IO.If you select a single column that’s not in the index, the database cannot do an index-only scan. If you select all columns, … , well I guess you know the answer.Further, some databases store large objects in a separate place (e.g., LOBs in Oracle). Accessing those causes an extra IO too.\n\nUp to 5x slower when bloating server memory footprint\n\nAlthough databases avoid storing the result in the server’s main memory—instead they deliver each row after loading and forget about it again—it is sometimes inevitable. Sorting, for example, needs to keep all rows—and all selected columns—in memory to do the job. Once again, the more columns you select, the more memory the database needs. In the worst case, the database might even need to do an external sort on disk.However, most database are extremely well tuned for this kind of workload. Although I’ve seen a sorting speed-up of factor two quite often—just by removing a few unused columns—I cannot remember having got more than factor five. However, it’s not just sorting, [hash joins](/sql/join/hash-join-partial-objects) are rather sensitive to memory bloat too. Don’t know what that is? Please read [this article](/sql/join/hash-join-partial-objects).\n\nThese are just the two top issues from database perspective. Remember that the network suffers too and that the client needs to process the data as well—which might put a considerable pressure on garbage collection.\n\nMany people think the star is the bad thing. Consequently they believe they are not having any problem if their ORM lists all columns by name anyway. In fact, the crime is to select all columns without thinking about it—and most [ORMs readily commit this crime](/blog/2013-04/the-two-top-performance-problems-caused-by-ORM-tools) on behalf of their users.\n\nWhen we say “`select *` is bad” we use the star as a symbol for “selecting everything without thinking about it”. This is the bad thing. If you need a more catch phrase to remember that, take this:\n\n> It’s not about the star, stupid!\n\n*If you like my way to explain things, you’ll love my book [SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=myth-select-star&utm_medium=web).*\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 4763, "slov": 762, "odkazu": 61, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:23", "sha256": "5e5b8612f27baa4b95e7e40f4d089a624df746656698997232c2e2ccd3b02f19", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://sql-performance-explained.com/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-08/try-online-at-sqlfiddle", "titulek": "Test the examples from Use The Index, Luke online at SQL Fiddle. We have already prepared the schema for you!", "h1": "Try it online!", "popis": "Try it online! — Working Examples at SQL Fiddle", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-08/try-online-at-sqlfiddle", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Test the examples from Use The Index, Luke online at SQL Fiddle. We have already prepared the schema for you!", "og:description": "Try it online! — Working Examples at SQL Fiddle", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Try it online!"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Try it online!\n\n---\n\n**UPDATE**: SQLFiddle integration has been removed in 2015 due to the low usage and high effort on my side.\n\nToday marks the third anniversary of Use The Index, Luke! And I have to fulfill a promise I gave [one year ago](/blog/2012-08/second-anniversary): You can now test many of the example from this site online at [SQLFiddle.com](https://sqlfiddle.com/).\n\nHere is a trivial example how it looks like. Just click on the SQL Fiddle logo on the right top corner of the execution plan.\n\n```\nSELECT first_name, last_name\n FROM employees\n WHERE employee_id = 123\n AND subsidiary_id = 30\n```\n\nDb2 (LUW)\n\n`Explain Plan\n--------------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 13\n 2 | FETCH EMPLOYEES | 1 of 1 (100.00%) | 13\n 3 | IXSCAN EMPLOYEES_PK | 1 of 10000 ( .01%) | 6\n\nPredicate Information\n 3 - START (Q1.EMPLOYEE_ID = +00123.)\n START (Q1.SUBSIDIARY_ID = +00030.)\n STOP (Q1.EMPLOYEE_ID = +00123.)\n STOP (Q1.SUBSIDIARY_ID = +00030.)`\n\nMySQL\n\n`+----+-----------+-------+---------+---------+------+-------+\n| id | table | type | key | key_len | rows | Extra |\n+----+-----------+-------+---------+---------+------+-------+\n| 1 | employees | const | PRIMARY | 10 | 1 | |\n+----+-----------+-------+---------+---------+------+-------+`\n\nOracle\n\n`---------------------------------------------------------------\n|Id |Operation | Name | Rows | Cost |\n---------------------------------------------------------------\n| 0 |SELECT STATEMENT | | 1 | 2 |\n| 1 | TABLE ACCESS BY INDEX ROWID| EMPLOYEES | 1 | 2 |\n|*2 | **INDEX UNIQUE SCAN** | **EMPLOYEES_PK** | 1 | 1 |\n---------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 2 - access(\"EMPLOYEE_ID\"=123 AND \"SUBSIDIARY_ID\"=30)`\n\nPostgreSQL\n\n`QUERY PLAN\n-------------------------------------------\n Index Scan using employees_pk on employees \n (cost=0.00..8.27 rows=1 width=14)\n Index Cond: ((employee_id = 123::numeric)\n AND (subsidiary_id = 30::numeric))`\n\nSQL Server\n\n`|--Nested Loops(Inner Join)\n |--Index Seek(OBJECT:employees_pk,\n | **SEEK:employee_id=@1 AND subsidiary_id=@2**\n | ORDERED FORWARD)\n |--RID Lookup(OBJECT:employees,\n SEEK:Bmk1000=Bmk1000\n LOOKUP ORDERED FORWARD)`\n\nAs I said—a trivial example borrowed from [chapter 2](/sql/where-clause/the-equals-operator/concatenated-keys).\n\nI have to admit that not all examples are available at SQL Fiddle yet. At the moment I’m finishing the examples of chapter 2. However, if you have read [SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2013-sqlfiddle&utm_medium=web) you know that chapter 2 makes up half of the book. In other words, half of the book is already available at SQL Fiddle.\n\nI hope this online experience makes Use The Index, Luke an even more awesome learning resource. A large part of this additional awesomeness is owed to [Jake Feasel who built SQL Fiddle](https://sqlfiddle.com/about.html#whoBuilt). Please note that you can [flattr SQL Fiddle](https://flattr.com/) and donate via PayPal (on the right top of the page).\n\nIf you have not yet read the book, please have a look at the [table of contents](/sql/table-of-contents) now and remember that you are just one click away from actually running the examples shown in the book. Learning about SQL performance has never been that easy ;)\n\n[Table of Contents](/sql/table-of-contents)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3495, "slov": 517, "odkazu": 57, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:24", "sha256": "e35cce034f7cacefe88c51bc36c560fbef2669815abd7ff46261aab3de69efa5", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://sqlfiddle.com/", "https://sql-performance-explained.com/", "https://sqlfiddle.com/about.html", "https://flattr.com/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2013-10/mysql-is-to-sql-like-mongodb-to-nosql", "titulek": "MongoDB and MySQL are pretty similar in many regards — they even share similar weaknesses.", "h1": "MongoDB is to NoSQL like MySQL to SQL — in the most harmful way", "popis": "MySQL and MongoDB are both popular, yet poor representatives of their species", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2013-10/mysql-is-to-sql-like-mongodb-to-nosql", "jazyk": "en", "robots_meta": "", "og": {"og:title": "MongoDB and MySQL are pretty similar in many regards — they even share similar weaknesses.", "og:description": "MySQL and MongoDB are both popular, yet poor representatives of their species", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "MongoDB is to NoSQL like MySQL to SQL — in the most harmful way"}, {"uroven": 4, "text": "Translations"}, {"uroven": 4, "text": "Links"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# MongoDB is to NoSQL like MySQL to SQL — in the most harmful way\n\n---\n\n#### Translations\n\nA Japanese translation of this article is available [here](https://yakst.com/ja/posts/74).\n\nYesterday evening I tweeted: “[MongoDB seems to be as Bad for NoSQL as MySQL is for SQL.](https://x.com/MarkusWinand/status/384739280465043456)” Unfortunately, I tweeted without context. But I guess I couldn’t have given all the required context in a single tweet anyway, so I’m dedicating this post to it. I hope this answers [some](https://x.com/tomtom62/status/384892908123717632) [of the](https://x.com/HuttHuttnDaButt/status/384900662418358272) [questions](https://x.com/lexachebara/status/384923601834496000) I’ve got in response to the tweet.\n\nFirst of all, I think everybody should know that I’m not a NoSQL fanboy, yet I’m open to the [polyglot persistence](https://www.martinfowler.com/bliki/PolyglotPersistence.html) idea. This distinction doesn’t seem to make sense if you read NoSQL as “not only SQL” (as you are supposed to do). However, I believe there are NoSQL systems out there that greatly benefit from the idea that SQL is bad and not using SQL is good. On other words, they offer “not using SQL” as their main advantage. MongoDB seems to be one of them. Just my perception.\n\nBut if I don’t like NoSQL, then I should like MySQL? Not exactly. In my eyes, MySQL has done great harm to SQL because many of the problems people associate with SQL are in fact just MySQL problems. One of the more important examples is that MySQL is rather poor at joining because is only supports [nested loops joins](/sql/join/nested-loops-join-n1-problem). Most other SQL database implement the [hash join](/sql/join/hash-join-partial-objects) and [sort/merge join](/sql/join/sort-merge-join) algorithms too—both deliver better performance for non-tiny data sets. Considering the wide adoption of MySQL (“The most popular open source database”) and the observation that many people move away from SQL because “joins are slow,” it isn’t far-fetched to say that an implementation limitation of MySQL pushes people towards NoSQL.\n\nNow let’s look at MongoDB. I think the direct competition between MongoDB and MySQL became most obvious in the epic video “[MongoDB is Web Scale](https://www.youtube.com/watch?v=b2F-DItXtZs).” In the meanwhile, MongoDB even claims to be “[the leading NoSQL database](https://web.archive.org/web/20150327140250/https://www.mongodb.com/leading-nosql-database)” — does that sound like “the most popular open source database”? Nevertheless, MongoDB has disappointed many people because it couldn’t live up to it’s promise of “web scale” (example: [global write lock](https://www.mongodb.com/docs/manual/faq/concurrency/) up to release 2.2).\n\nThe next piece in the puzzle that eventually caused me to tweet was a funny [tweet](https://x.com/gwenshap/status/384657881137573888) by [Gwen (Chen) Shapira](https://x.com/gwenshap) (she’s an Oracle DB consultant):\n\n#mongoDB : the big data platform that is challenging to scale over 100GB. [http://blog.mongodb.org/post/62899600960/scaling-advice-from-mongohq](https://blog.mongodb.com/post/62899600960/scaling-advice-from-mongohq)\n\nNote that the link was broken for a while (the post originally appeared on Sep 30, then disappeared, but is online since Oct 2 again at a different URL). The article is about handling MongoDB if it grows above 100GB. It gives me the impression that scaling MongoDB to that size is a serious issue. Even though there is no exact definition of “web scale” I guess most people would assume that it should be easy to scale MongoDB to 100GB. 100GB is not big data nowadays. 100GBs can be easily managed with most SQL DBs (joining in MySQL could be a problem). It was really funny to see this post on the MongoDB blog. Chen’s tweet nailed it.\n\nAt this point, I was once more thinking about the “misspent half-decade” mentioned by Jack Clark in his article “[Google goes back to the future with SQL F1 database](https://www.theregister.com/software/2013/08/30/google-goes-back-to-the-future-with-sql-f1-database/937689).” But as mentioned before, I like the idea of polyglot persistence. I’m not saying NoSQL is bullshit—not just because a single implementation fails to deliver. That would be like saying SQL is bullshit because MySQL is bad at joining. On the contrary, it reminded how Alex Popescu lost his temper in his post “[The premature return to SQL](https://nosql.mypopescu.com/post/62403847766/the-premature-return-to-sql)” last Friday. His response to the “misspent half-decade” was:\n\nJust take a second a think what we got during this misspent half-decade: [Redis](https://redis.io/), [Cassandra](https://cassandra.apache.org/_/index.html), [Riak](https://riak.com/riak/), a [multi-parallel fully programmatic way to process data](https://en.wikipedia.org/wiki/Mapreduce), [Cascading](https://cascading.wensel.net/), [Pig](https://pig.apache.org/), [Cypher](https://neo4j.com/docs/cypher-manual/current/introduction/), [ReQL](https://rethinkdb.com/api/#py) and many more tools, languages, and APIs for processing data.\n\nWell, I don’t know all of these but I do realize that some of them are interesting tools to have in the tool box. Further, I’m following Alex Popescu long enough to know that he is rather reflective on NoSQL—the title of his post being an exception. That’s why I came back to his post to see if he mentioned “the leading NoSQL database“ in his list. He didn’t. I don’t think it’s a coincidence.\n\nAt this point it was inevitable to see MongoDB as a popular, yet poor representative of its species—just like MySQL is.\n\n#### Links\n\n- [MongoDB mocked after posting “100GB Scaling Checklist”](https://web.archive.org/web/20181224033109/https://jaxenter.com/mongodb-mocked-after-posting-100gb-scaling-checklist-106822.html) Also covering how the [re-posted checklist](https://blog.mongodb.com/post/62899600960/scaling-advice-from-mongohq) was changed as compared to the [original post](https://gist.github.com/bsodmike/6792993) :)\n- [Discussion on Reddit](https://www.reddit.com/r/programming/comments/1niheb/mongodb_is_to_nosql_like_mysql_to_sql_in_the_most/)\n- [Discussion on Hacker News](https://news.ycombinator.com/item?id=6481526)\n- [Baron Schwartz “MySQL isn’t limited to nested-loop joins”](https://web.archive.org/web/20160327214421/https://www.xaprb.com/blog/2013/10/01/mysql-isnt-limited-to-nested-loop-joins/) Note the comments too. There is doubt if the mentioned features can compete with hash joins.\n- [The blog entry that disappeared (but has some comments).](https://blog.mongodb.org/post/62704324103/scaling-100gb-of-data)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 7223, "slov": 954, "odkazu": 82, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:25", "sha256": "12f90cfe117abc25c66dd9d71023d70b15859851b8708401fabb0b84a45a5f1d", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://yakst.com/ja/posts/74", "https://x.com/MarkusWinand/status/384739280465043456", "https://x.com/tomtom62/status/384892908123717632", "https://x.com/HuttHuttnDaButt/status/384900662418358272", "https://x.com/lexachebara/status/384923601834496000", "https://www.martinfowler.com/bliki/PolyglotPersistence.html", "https://www.youtube.com/watch?v=b2F-DItXtZs", "https://www.mongodb.com/leading-nosql-database", "https://www.mongodb.com/docs/manual/faq/concurrency/", "https://x.com/gwenshap/status/384657881137573888", "https://x.com/gwenshap", "https://blog.mongodb.com/post/62899600960/scaling-advice-from-mongohq", "https://www.theregister.com/software/2013/08/30/google-goes-back-to-the-future-with-sql-f1-database/937689", "https://nosql.mypopescu.com/post/62403847766/the-premature-return-to-sql", "https://redis.io/", "https://cassandra.apache.org/_/index.html", "https://riak.com/riak/", "https://en.wikipedia.org/wiki/Mapreduce", "https://cascading.wensel.net/", "https://pig.apache.org/", "https://neo4j.com/docs/cypher-manual/current/introduction/", "https://rethinkdb.com/api/", "https://jaxenter.com/mongodb-mocked-after-posting-100gb-scaling-checklist-106822.html", "https://gist.github.com/bsodmike/6792993", "https://www.reddit.com/r/programming/comments/1niheb/mongodb_is_to_nosql_like_mysql_to_sql_in_the_most/", "https://news.ycombinator.com/item?id=6481526", "https://www.xaprb.com/blog/2013/10/01/mysql-isnt-limited-to-nested-loop-joins/", "https://blog.mongodb.org/post/62704324103/scaling-100gb-of-data", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2014-01/unreasonable-defaults-primary-key-clustering-key", "titulek": "The primary key is the default clustered index in SQL Server and MySQL. This implies a 'clustered index penalty' on all non-clustered indexes.", "h1": "Unreasonable Defaults: Primary Key as Clustering Key", "popis": "Unreasonable Defaults: Primary Key as Clustering Key", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2014-01/unreasonable-defaults-primary-key-clustering-key", "jazyk": "en", "robots_meta": "", "og": {"og:title": "The primary key is the default clustered index in SQL Server and MySQL. This implies a 'clustered index penalty' on all non-clustered indexes.", "og:description": "Unreasonable Defaults: Primary Key as Clustering Key", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Unreasonable Defaults: Primary Key as Clustering Key"}, {"uroven": 2, "text": "Recap: What is a clustered index"}, {"uroven": 4, "text": "Note"}, {"uroven": 2, "text": "The costs of an extra level of indirection"}, {"uroven": 4, "text": "Note"}, {"uroven": 2, "text": "How bad is it?"}, {"uroven": 2, "text": "Who cares about logical reads anyway"}, {"uroven": 2, "text": "What was the upside of clustered indexes again?"}, {"uroven": 4, "text": "Note"}, {"uroven": 2, "text": "Concluding: How many clustered indexes can a SQL Server table have?"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Unreasonable Defaults: Primary Key as Clustering Key\n\n---\n\nAs you might have noticed—at least if you have read [*SQL Performance Explained*](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2014-clustering-key-default&utm_medium=web)—I don’t think clustered indexes are as useful as most people believe. That is mainly because it is just too darn difficult to choose a good clustering key. As a matter of fact, choosing a good—the “right”—clustering key is almost impossible if there are more than one or two indexes on the table. The result is that most people just stick to the default—which is the primary key. Unfortunately, this is almost always the worst possible choice.\n\nIn this article I explain the beast named clustered index and all it’s downsides. Although this article uses SQL Server as demo database, the article is equally relevant for MySQL/MariaDB with InnoDB and the Oracle database when using index-organized tables.\n\n## Recap: What is a clustered index\n\nThe idea of clustered indexes is to store a complete table in a B-tree structure. If a table *has* a clustered index, it basically means the index *is* the table. A clustered index has a strict row order like any other B-tree index: it sorts the rows according to the index definition. In case of clustered indexes we call the columns that define the index order the clustering key. The alternative way to store a table is as a heap with no particular row order. Clustered indexes have the advantage that they support very fast range scans. That is, they can fetch rows with the same (or similar) clustering key value quickly, because those rows are physically stored next to each other (clustered)—often in the same data page. When it comes to clustered indexes it is very important to understand that there is no separate place where the table is stored. The clustered index *is* the primary table store—thus you can have only one per table. That’s the definition of clustered indexes—it’s a contrast to heap tables.\n\nThere is, however, another contrast to clustered indexes: non-clustered indexes. Just because of the naming, this is the more natural counterpart to clustered indexes to many people. From this perspective, the main difference is that querying a clustered index is always done as index-only scan. A non-clustered index, on the other hand, has just a sub-set of the table columns so it causes extra IOs for getting the missing columns from the primary table store if needed. Every row in a non-clustered index has a reference to the very same row in the primary table store for this purpose. In other words, using a non-clustered index generally involves resolving an extra level of indirection. Generally, I said. In fact it is pretty easy to avoid this overhead by including all needed columns in the non-clustered index. In that case the database can find all the required data in the index and just doesn’t resolve the extra level of indirection. Even non-clustered indexes can be used for index-only scans—making them as fast as clustered indexes. Isn’t that what matters most?\n\n#### Note\n\nThe index-only scan is the important concept—not the clustered index.\n\nLater in the article, we’ll see that there is a duality among these aspects of clustered indexes: being a table store (in contrast to heap tables) or being an index that happens to have all table columns. Unfortunately, this “table-index duality” can be as confusing as the [wave-particle duality of light](https://en.wikipedia.org/wiki/Wave%E2%80%93particle_duality). Hence, I’ll explicitly state which aspect appears at the time whenever necessary.\n\n## The costs of an extra level of indirection\n\nWhen it comes to performance, an extra level of indirection is not exactly desirable because dereferencing takes time. The crucial point here is that the costs of dereferencing is greatly affected by the way the table is physically stored—either as heap table or as clustered index.\n\nThe following figures explain his phenomenon. They visualize the process to execute a query to fetch all `SALES` rows from 2012-05-23. The first figure uses a non-clustered index on `SALE_DATE` together with a heap table (= a table that doesn’t have a clustered index):\n\nNote that there is a single `Index Seek (Non-Clustered)` operation on the non-clustered index that causes two `RID Lookups` into the heap table (one for each matched row). This operation reflects dereferencing the extra indirection to load the remaining columns from the primary table store. For heap tables, a non-clustered index uses the physical address (the so-called `RID`) to refer to the very same row in the heap table. In the worst case the extra level of indirection causes one additional read access per row (neglecting forwarding).\n\nNow let’s look at the same scenario with a clustered index. More precisely, when using a non-clustered index in presence of a clustered-index on `SALE_ID`—that is, the primary key as clustering key.\n\nNote that the definition of the index on the left hand side has not changed: it’s still a non-clustered index on `SALE_DATE`. Nevertheless, the pure presence of the clustered index affects they way the non-clustered index refers to the primary table storage—which is the clustered index! Unlike heap tables, clustered indexes are “living creatures” that move rows around as needed to maintain their properties (i.e.: the row order and tree balance). Consequently the non-clustered index can’t use the physical address as reference anymore because it [could change at any time](/sql/clustering/index-organized-clustered-index#sb-physical-rowid-iot). Instead, it uses the clustering key `SALE_ID` as reference. Loading the missing columns from the primary table store (=clustered index) now involves a full B-tree traversal for each row. That are *several* extra IOs per row as opposed to a single extra IO in case of heap tables.\n\nI also refer to this effect as the “clustered index penalty”. This penalty affects all non-clustered indexes on tables that have a clustered index.\n\n#### Note\n\nFor index-organized tables, the Oracle database also stores the physical address of that row (=guess `ROWID`) along with the clustering key in the secondary indexes (=non-clustered indexes). If the row is found at this address, the database doesn’t need to perform the B-tree traversal. If not, however, it has performed one more IO for nothing.\n\n## How bad is it?\n\nNow that we have seen that clustered indexes cause a considerable overhead for non-clustered indexes, you’ll probably like to know how bad it is? The theoretic answer has been given above—one IO for the `RID Lookup` compared to several IOs for the `Key Lookup (Clustered)`. However, as I learned the hard way when giving performance training, people tend to ignore, deny, or just don’t believe that fact. Hence, I’ll show you a demo.\n\nObviously, I’ll use two similar tables that just vary by the table storage they use (heap vs. clustered). The following listing shows the pattern to create these tables. The part in square brackets makes the difference to either use a heap table or clustered index as table store.\n\n```\nCREATE TABLE sales[nc] (\n sale_id NUMERIC NOT NULL,\n employee_id NUMERIC NOT NULL,\n eur_value NUMERIC(16,2) NOT NULL,\n SALE_DATE DATE NOT NULL\n CONSTRAINT salesnc_pk\n PRIMARY KEY [nonclustered] (sale_id),\n);\n\nCREATE INDEX sales[nc]2 ON sales[nc] (sale_date);\n```\n\nI’ve filled these tables with 10 million rows for this demo.\n\nThe next step is to craft a query that allows us to measure the performance impact.\n\n```\nSELECT TOP 1 * \n FROM salesnc\n WHERE sale_date > '2012-05-23'\n ORDER BY sale_date\n```\n\nThe whole idea behind this query is to use the non-clustered index (hence filtering and ordering on `SALE_DATE`) to fetch a variable number of rows (hence `TOP N`) from the primary table store (hence `select *` to make sure it’s not executed as index-only scan).\n\nNow lets look what happens if we `SET STATISTICS IO ON` and run the query against the heap table:\n\n`Scan count 1, **logical reads 4**, physical reads 0, read-ahead reads 0,…`The interesting figure is the logical reads count of four. There were no physical reads because I have executed the statement twice so it is executed from the cache. Knowing that we have fetched a single row from a heap table, we can already conclude that the tree of the non-clustered index must have three levels. Together with one more logical read to access the heap table we get the total of four logical reads we see above.\n\nTo verify this hypothesis, we can change the `TOP` clause to fetch two rows:\n\n```\nSELECT TOP 2 * \n FROM salesnc\n WHERE sale_date > '2012-05-23'\n ORDER BY sale_date\n```\n\n```\nScan count 1, logical reads 5, physical reads 0, read-ahead reads 0,…\n```\n\nKeep in mind that the lookup in the non-clustered index is essentially unaffected by this change—it still needs three logical reads if the second row happens to reside in the same index page—which is very likely. Hence we see just one more logical read because of the second access to the heap table. This corresponds to the first figure above.\n\nNow let’s do the same test with the table that has (=is) a clustered index:\n\n```\nSELECT TOP 1 * \n FROM sales\n WHERE sale_date > '2012-05-23'\n ORDER BY sale_date\n```\n\n```\nScan count 1, logical reads 8, physical reads 0, read-ahead reads 0,…\n```\n\nFetching a single row involves *eight* logical reads—twice as many as before. If we assume that the non-clustered index has the same tree depth, it means that the `KEY Lookup (Clustered)` operation triggers five logical reads per row. Let’s check that by fetching one more row:\n\n```\nSELECT TOP 2 * \n FROM sales\n WHERE sale_date > '2012-05-23'\n ORDER BY sale_date\n```\n\n```\nScan count 1, logical reads 13, physical reads 0, read-ahead reads 0,…\n```\n\nAs feared, fetching a second row triggers five more logical reads.\n\nI’ve continued these test in 1/2/5-steps up to 100 rows to get more meaningful data:\n\n| Rows Fetched | Logical Reads (Heap) | Logical Reads (Clustered) |\n| --- | --- | --- |\n| 1 | 4 | 8 |\n| 2 | 5 | 13 |\n| 5 | 8 | 27 |\n| 10 | 13 | 48 |\n| 20 | 23 | 91 |\n| 50 | 53 | 215 |\n| 100 | 104 | 418 |\n\nI’ve also fitted linear equations in the chart to see how the slope differs. The heap table matches the theoretic figures pretty closely (3 + 1 per row) but we see “only” four logical reads per row with the clustered index—not the five we would have expected from just fetching one and two rows.\n\n## Who cares about logical reads anyway\n\nLogical reads are a fine benchmark because it yields reproducible results—independent of the current state of caches or other work done on the system. However, the above chart is still a very theoretic figure. Four times as many logical reads does not automatically mean four times as slow. In all reality you’ll have a large part of the clustered index in the cache—at least the first few B-tree levels. That reduces the impact definitively. To see how it affects the impact, I conducted another test: measuring the execution time when running the queries from the cache. Avoiding disk access is another way to get more or less reproducible figures that can be compared to each other.\n\nAgain, I’ve used 1/2/5-steps but started at 10.000 rows—selecting fewer rows was too fast for the timer’s resolution. Selecting more than 200.000 rows took extraordinarily long so that I believe the data didn’t fit into the cache anymore. Hence I stopped collecting data there.\n\n| Rows Fetched | Time (Heap) | Time (Clustered) |\n| --- | --- | --- |\n| 10.000 | 31 | 78 |\n| 20.000 | 47 | 130 |\n| 50.000 | 109 | 297 |\n| 100.000 | 203 | 624 |\n| 200.000 | 390 | 1232 |\n\nFrom this test it seems that the “clustered index penalty” on the non-clustered index is more like three times as high as compared to using a heap table.\n\nNotwithstanding these results, is it perfectly possible that the real world caching leads to a “clustered index penalty” outside the here observed range in a production system.\n\n## What was the upside of clustered indexes again?\n\nThe upside of clustered indexes is that they can deliver subsequent rows quickly when accessed directly (not via a non-clustered index). In other words, they are fast if you use the clustering key to fetch several rows. Remember that the primary key is the clustering key per default. In that case, it means fetching several rows via primary key—with a single query. Hmm. Well, you can’t do that with an equals filter. But how often do you use non-equals filters like `>` or `<` on the primary key? Sometimes, maybe, but not that often that it makes sense to optimize the physical table layout for these queries *and* punish all other indexes with the “clustered index penalty.” That is really *insane* (IMHO).\n\nLuckily, SQL Server is quite flexible when it comes to clustered indexes. As opposed to MySQL/InnoDB, SQL Server can use any column(s) as clustering key—even non-unique ones. You can choose the clustering key so it catches the most important range scan. Remember that equals predicates (`=`) can also cause range scans (on non-unique columns). But beware: if you are using long columns and/or many columns as clustering key, they bloat all non-clustered indexes because each row in every non-clustered indexes contains the clustering key as reference to the primary table store. Further, SQL Server makes non-unique clustering keys automatically unique by adding an extra column, which also bloats all non-clustered indexes. Although this bloat will probably not affect the tree depth—thanks to the [logarithmic growth of the B-tree](/sql/anatomy/the-tree#sb-log)—it might still hurt the cache-hit rate. That’s also why the “clustered index penalty” could be outside the range indicated by the tests above—in either way!\n\nEven if you are able to identify the clustering key that brings the most benefit for range scans, the overhead it introduces on the non-clustered indexes can void the gains again. As I said in the intro above, it is just too darn difficult to estimate the overall impact of these effects because the clustering key affects all indexes on the table in a pretty complex way. Therefore, I’m very much in favour of using heap tables if possible and index-only scans when necessary. From this perspective, clustered indexes are just an additional space optimization in case the “clustered index penalty“ isn’t an issue—most importantly if you need only one index that is used for range scans.\n\n#### Note\n\nSome databases don’t support heap tables at all—most importantly MySQL/MariaDB with InnoDB and the Azure database.\n\nFurther there are configurations that can only use the primary key as clustering key—most importantly MySQL/MariaDB with InnoDB and Oracle index-organized tables.\n\nNote that MySQL/MariaDB with InnoDB is on both lists. They don’t offer any alternative for what I referred to as “insane.” MyISAM being no alternative.\n\n## Concluding: How many clustered indexes can a SQL Server table have?\n\nTo conclude this article, I’d like to demonstrate why it is a bad idea to consider the clustered index as the “silver bullet” that deserves all your thoughts about performance. This demo is simple. Just take a second and think about the following question:\n\nHow many clustered indexes can a SQL Server table have?\n\nI love to ask this question in my SQL Server performance trainings. It truly reveals the bad understanding of clustered indexes.\n\nThe first answer I get is usually is “one!” Then I ask why I can’t have a second one. Typical response: —silence—. After this article, you already know that a clustered index is not only an index, but also the primary table store. You can’t have two *primary* table stores. Logical, isn’t it? Next question: Do I need to have a clustered index on every table? Typical response: —silence— or “no” in a doubtful tone. I guess this is when the participants realize that I’m asking trick questions. However, you now know that SQL Server doesn’t need to have a clustered index on every table. In absence of a clustered index, SQL Server uses a heap as table store.\n\nAs per definition, the answer to the question is: “at most one.”\n\nAnd now stop thinking about the clustered index as “silver bullet” and start putting the index-only scan into the focus. For that, I’ll rephrase the question slightly:\n\nHow many indexes on a SQL Server table can be queried as fast as a clustered index?\n\nThe only change to the original question is that it doesn’t focus on the clustered index as such anymore. Instead it puts your focus on the positive effect you expect from a clustering index. The point in using a clustered index is not just to have a clustered index, it is about improving performance. So, let’s focus on that.\n\nWhat makes the clustered index fast is that every (direct) access is an index-only scan. So the question essentially boils down to: “how many indexes can support an index-only scan?” And the simple answer is: as many as you like. All you need to do is to add all the required columns to a non-clustered index and ***BAM*** using it is as fast as though it was a clustered index. That’s what SQL Server’s `INCLUDE` keyword of the `CREATE INDEX` statement is for!\n\nFocusing on index-only scans instead of clustered indexes has several advantages:\n\n- You are not limited to one index. Any index can be as fast as a clustered index.\n- Adding `INCLUDE` columns to a non-clustered index doesn’t affect anything else than this particular index. There is no penalty that hurts all other indexes!\n- You don’t need to add all table columns to a non-clustered index to enable an index-only scan. Just add the columns that are relevant for the query you’d like to tune. That keeps the index small and can thus become even faster than a clustered index.\n- And the best part is: there is no mutual exclusion of index-only scans and clustered indexes. Index-only scans work irrespective of the table storage. You can extend non-clustered indexes for index-only scans even if there is a clustered index. That’s also an easy way to avoid paying the “clustered index penalty” on non-clustered indexes.\n\nBecause of the “clustered index penalty” the concept of the index-only scan is even more important when having a clustered index. Really, if there is something like a “silver bullet”, it is the index-only scan—not the clustered index.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 18701, "slov": 3159, "odkazu": 56, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:26", "sha256": "11c1959fb24045076a06725690b5a82099e6ea2117b6f64e5110d8190f60bbd9", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://sql-performance-explained.com/", "https://en.wikipedia.org/wiki/Wave%E2%80%93particle_duality", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2014-02/results-three-minutes-sql-performance-quiz", "titulek": "No wonder people believe SQL is slow, if more than 60% fail to apply basic indexing techniques.", "h1": "Results of the SQL Performance Quiz: 60% fail", "popis": "SQL indexing: 60% don’t know how to get it right", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2014-02/results-three-minutes-sql-performance-quiz", "jazyk": "en", "robots_meta": "", "og": {"og:title": "No wonder people believe SQL is slow, if more than 60% fail to apply basic indexing techniques.", "og:description": "SQL indexing: 60% don’t know how to get it right", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Results of the SQL Performance Quiz: 60% fail"}, {"uroven": 4, "text": "Note"}, {"uroven": 2, "text": "Question 1: Functions in the WHERE Clause"}, {"uroven": 2, "text": "Question 2: Indexed Top-N Queries"}, {"uroven": 2, "text": "Question 3: Index Column Order"}, {"uroven": 2, "text": "Question 4: LIKE Searches"}, {"uroven": 2, "text": "Question 5a: Index-Only Scan"}, {"uroven": 2, "text": "Question 5b: Index Column Order and Range Operators"}, {"uroven": 2, "text": "Overall Score: How Many Passed the Test?"}, {"uroven": 4, "text": "Links"}, {"uroven": 2, "text": "About the Author"}, {"uroven": 2, "text": "Footnotes"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Results of the SQL Performance Quiz: 60% fail\n\n---\n\nIn 2011, I’ve launched the “[The 3-Minute Test: What do you know about SQL performance.](/3-minute-quiz)” It consists of five questions that follow a simple pattern: each question shows a query/index pair and asks if it demonstrates proper indexing or not. Till today, this test has become one of the most popular features on [Use The Index, Luke](/) and has been completed more than 28,000 times.\n\n#### Note\n\nJust in case you got curious, please be aware that this article is a spoiler. You might want to [do the quiz yourself](/3-minute-quiz) before continuing.\n\nAlthough the quiz was created for educational purposes, I was wondering if I could get some interesting figures out of these 28,000 results. And I think I could. However, there are several things to keep in mind when looking at these figures. First, the quiz uses the surprise factor to catch attention. That means, three questions show cases that look fine, but aren’t. One question does it the other way around and shows an example that might look dangerous, but isn’t. There is only one question where the correct answer is in line with the first impression. Another effect that might affect the significance of the results is that there was no representative selection of participants. Everybody can take the quiz. You can even do it multiple times and will probably get a better result the second time. Just keep in mind that the quiz was never intended to be used for scientific research upon the indexing knowledge in the field. Nevertheless, I think that the size of the dataset is still good enough to get an impression.\n\nBelow I’ll show two different statistics for each question. First, the average rate at which this question was correctly answered. Second, how this figure varies for users of MySQL, Oracle, PostgreSQL and SQL Server databases. In other word, it says if e.g. MySQL users are more knowledgeable about indexing as PostgreSQL users. Spoiler: It’s the other way around. The only reason I’m in the lucky position to have this data is that the test sometimes uses vendor specific syntax. For example, what is `LIMIT` in MySQL and PostgreSQL is `TOP` in SQL Server. Therefore, the participants have to select a database at the beginning so that the questions are shown in the native syntax of that product.\n\n## Question 1: Functions in the WHERE Clause\n\n> Is the following SQL good or bad practice from a performance perspective?\n> \n> Searching for all rows of the year 2012:\n> \n> ```\n> CREATE INDEX tbl_idx ON tbl (date_column);\n> \n> SELECT text, date_column\n> FROM tbl\n> WHERE TO_CHAR(date_column, 'YYYY') = '2012';\n> ```\n\nThis is an example where the code uses functions specific to the Oracle and PostgreSQL databases. For MySQL, the question uses `YEAR(date_column)` and for SQL Server `datepart(yyyy, date_column)`. Of course, I could have used `EXTRACT(YEAR date_column)`, but I thought it is better to use the most common syntax.\n\nThe participants have these options:\n\n- Good practice — There is no major improvement possible.\n- Bad practice — There is a major improvement possible.\n\nThe correct answer is “bad practice” because the index on `date_column` cannot be used when searching on something derived from `date_column`. If you don’t believe that, please have a look at the [proof scripts](/sql/example-schema/postgresql/3-minute-quiz#quiz-pg-q1) or the explanations shown at the end of the test. They also contain links to the [Use The Index, Luke](/) pages explaining it in more detail.\n\nHowever, if you didn’t know how functions effectively “disable” indexes, you are not alone. Only about two-thirds gave the correct answer. And as for every multiple choice test, there is a certain probably to pick the correct answer by chance. In this cases it’s a 50/50 chance — by no means negligible. I’ve marked this “guessing score” in the figure to emphasize that.\n\nThis is one of the most common problems I see in my everyday work. The same problem can also hit you with `VARCHAR` fields when using `UPPER`, `TRIM` or the like. Please keep in mind: whenever you are applying functions on columns in the `where` clause, an index on the column itself is no longer useful for this query.\n\nAlthough this result is quite disappointing — I mean it’s not much better than guessing — it is no surprise to me. What is a surprise for me is how the result differs amongst the users of different databases.\n\nAs a matter of fact, MySQL users just score 55% — almost as low as the “guessing score”. PostgreSQL users, on the other hand, get a score of 83%.\n\nAn effect that might explain this result is that MySQL doesn’t support [function-based indexes](/sql/where-clause/functions/case-insensitive-search) while Oracle and PostgreSQL do. Function-based indexes allow you to index expressions like `TO_CHAR(date_column, 'YYYY')`. Although it is not the [recommended solution](/sql/where-clause/obfuscation/dates) for this case, the pure existence of this feature might make users of the Oracle and PostgreSQL database more aware of this problem. SQL Server offers a similar feature: although it cannot index expressions directly, you can create a so-called computed column on expressions, which in turn can be indexed.\n\nAlthough support for function-based indexes might explain why MySQL users underperformed, it is still no excuse. The shown query/index pair is bad — no matter whether the database supports function-based indexes or not. And the major improvement is also possible without function-based indexes:\n\n```\nSELECT text, date_column\n FROM tbl\n WHERE date_column >= TO_DATE('2012-01-01', 'YYYY-MM-DD')\n AND date_column < TO_DATE('2013-01-01', 'YYYY-MM-DD');\n```\n\nThe index doesn’t need to be changed. This solution is very flexible because it supports queries for different ranges too — e.g. by week or month. This is the recommended solution.\n\nAs a curious guy, I’d love to know how many of the people who correctly answered this question were thinking of the sub-optimal solution to use a function-based index. I’d rate this solution half-correct at best.\n\n## Question 2: Indexed Top-N Queries\n\n> Is the following SQL good or bad practice from a performance perspective?\n> \n> To find the most recent row:\n> \n> ```\n> CREATE INDEX tbl_idx ON tbl (a, date_column);\n> \n> SELECT id, a, date_column\n> FROM tbl\n> WHERE a = ? \n> ORDER BY date_column DESC\n> LIMIT 1;\n> ```\n\nNote that the question mark is a placeholder, because I always encourage developers to use [bind parameters](/sql/where-clause/bind-parameters).\n\nAs participant, you have these two options again:\n\n- Good practice — There is no major improvement possible.\n- Bad practice — There is a major improvement possible.\n\nThis is the question that is supposed to look dangerous, but isn’t. Generally, it seems like people believe `order by` must always sort the data. This index, however, eliminates the need to sort the data entirely so that the query is basically as fast as a unique index lookup. Please find a detailed explanation of this trick [here](/sql/partial-results/top-n-queries).\n\nThe result is very close to the “guessing score” which I interpret as “people don’t have a clue about it.”\n\nThis result is particularly sad because I’ve seen people building caching tables, regularly refilled by a cron jobs, to avoid queries like this. Interestingly, the cron job tends to cause performance problems because it is running in rather short intervals to make sure the cache table has fresh data. However, the right index is often the better option in the first place.\n\nHere I have to mention that the Oracle database needs the most special syntax for this trick. Up till version 12c released in 2013, the Oracle database did not offer a handy shortcut such as `LIMIT` or `TOP`. Instead, you have to use the `ROWNUM` pseudo-column like this:\n\n```\nSELECT *\n FROM (\n SELECT id, date_column\n FROM tbl\n WHERE a = :a\n ORDER BY date_column DESC\n )\n WHERE rownum <= 1;\n```\n\nThe extra complexity of this query might have pushed Oracle users more heavily towards the wrong answer — actually below guessing score!\n\nAnother argument I’m getting in response to this question is that including the `ID` column in the index would allow an [index-only scan](/sql/clustering/index-only-scan-covering-index). Although this is correct, I don’t consider not doing so a “bad practice” because the query touches only one row anyway. An index-only scan could just avoid a single table access. Obviously there are cases were you need that improvement, but in the general case I’d consider it a premature optimization. But that’s just my opinion. However, following this argument might give us an idea why PostgreSQL users got the best score (again): PostgreSQL did not have index-only scans until version 9.2, which was released in September 2012. As a result, PostgreSQL users could not fall into this trap of thinking an index-only scan can bring major improvements in this case. Undoubtedly, the term “major” is troublesome in this context.\n\n## Question 3: Index Column Order\n\n> Is the following SQL good or bad practice from a performance perspective?\n> \n> Two queries, searching by a common column:\n> \n> ```\n> CREATE INDEX tbl_idx ON tbl (a, b);\n> \n> SELECT id, a, b\n> FROM tbl\n> WHERE a = ?\n> AND b = ?;\n> \n> \n> SELECT id, a, b\n> FROM tbl\n> WHERE b = ?;\n> ```\n\nThe same options:\n\n- Good practice — There is no major improvement possible.\n- Bad practice — There is a major improvement possible.\n\nThe answer is “bad practice,” because the second query cannot use the index properly. Changing the index column order to `(b, a)` would, however, allow both queries to use this index in the most efficient way. You can find a full explanation [here](/sql/where-clause/the-equals-operator/concatenated-keys). Adding a second index on `(b)` would be a poor solution due to the overhead it adds for no reason. Unfortunately, I don’t know how many would have done that.\n\nThe result is disappointing, but in line with my expectations — just 12.5% above guessing score.\n\nThis is also a problem I see almost every day. People just don’t understand how multi-column indexes work.\n\nAll the per-database results are pretty close together. Maybe because there is no syntactic difference or well-known database features that could have a major influence the answer. Less known features like Oracle’s `SKIP SCAN` could have a minor impact, of course. Generally, the index-only scan could have a influence too, but it pushes the participants to the “right” answer this time.\n\nAfter all, this result might just say that users of some databases know more about indexing than others. Interestingly, PostgreSQL users get the best score for the third time.\n\n## Question 4: LIKE Searches\n\n> Is the following SQL troublesome or bulletproof from a performance perspective?\n> \n> Searching within a string:\n> \n> ```\n> CREATE INDEX tbl_idx ON tbl (text);\n> \n> SELECT id, text\n> FROM tbl\n> WHERE text LIKE '%TERM%';\n> ```\n\nI’ve phrased the options differently this time:\n\n- Bulletproof: It will always run fast.\n- Troublesome: There is high risk for performance problems.\n\nAnd the correct answer is “troublesome” because the `LIKE` pattern uses a leading wild card. Otherwise, if it would use the pattern `'TERM%'`, it could use the index very efficiently. Have a look at this [visual explanation](/sql/where-clause/searching-for-ranges/like-performance-tuning) for details.\n\nThe results of this question are promising. Here I feel safe to say most people know that `LIKE` is not for full-text search.\n\nThe segregated results are also within a very narrow corridor:\n\nIt is, however, strange that PostgreSQL users under performed at this question. A closer look at how the question is presented to PostgreSQL users might give an explanation:\n\n```\nCREATE INDEX tbl_idx ON tbl (text varchar_pattern_ops);\n\nSELECT id, text\n FROM tbl\n WHERE text LIKE '%TERM%';\n```\n\nNote the addition to the index (`varchar_pattern_ops`). In PostgreSQL, this special operator class is required to make the index usable for postfix wild card searches (e.g. `'TERM%'`). I added this because I aimed to find out if people know about the problem of leading wild cards in `LIKE` expressions. Without the operator class, there are two reasons why it doesn’t work: (1) the leading wild card; (2) the missing operator class. I though that would be too obvious. Retrospectivley, I believe some participants interpreted this operator class as “magic that makes it work” and thus took the wrong answer.\n\n## Question 5a: Index-Only Scan\n\nQuestion five is a little bit tricky, because PostgreSQL did not support [index-only scans](/sql/clustering/index-only-scan-covering-index) when the quiz was created. For that reason, there are two variants of question five: one about index-only scans for users of MySQL, Oracle and SQL Server databases. And another question about index column order for PostgreSQL users. Both results are presented here, but the segregated data is limited for obvious reasons. We start with the question about index-only scans:\n\n> How will the change affect query performance?\n> \n> Current situation, selecting about hundred rows out of a million:\n> \n> ```\n> CREATE INDEX tab_idx ON tbl (a, date_column);\n> \n> SELECT date_column, count(*)\n> FROM tbl\n> WHERE a = 123\n> GROUP BY date_column;\n> ```\n> \n> Changed query, selecting about ten rows out of a million:\n> \n> ```\n> SELECT date_column, count(*)\n> FROM tbl\n> WHERE a = 123\n> AND b = 42\n> GROUP BY date_column;\n> ```\n\nNote the added `where` clause in the second query.\n\nThis question is also special because it offers four options:\n\n- Query performance will roughly stay the same (+/- 10%)\n- Depends on the data.\n- The query will be much slower (impact >10%)\n- The query will be much faster (impact >10%)\n\nWhen I created the quiz, I was well aware that 50/50 questions have a tendency to render the score meaningless. This question is a trade-off between keeping the questions easy to gasp and answer (questions 1–4) and giving a more accurate result.\n\nTo make it short, the correct answer is “the query will be much slower.” The reason is that the original query could use an index-only scan — that is, the query could be answered only using data from the index without fetching any data from the actual table. The second query, however, needs to check column `B` too, which is not in the index. Consequently, the database must take some extra effort to fetch the candidate rows from the table to evaluate the expression on `B` That is, it must fetch at least 100 rows from the table — the number of rows returned by the first query. Due to the `group by` there are probably more rows to fetch. A quite considerable extra effort that will make the query much slower. A more exhaustive explanation is [here](/sql/clustering/index-only-scan-covering-index).\n\nWith that number of options, the overall score drops significantly to about 39% or 14% above guessing score.\n\nStill I think saying that about 39% of participants knew the right answers is wrong. They gave the right answer, but there was still a probability of 25% that they gave the right answer without knowing it.\n\nThe segregation by database is quite boring. Conspicuously boring.\n\nHowever, with four options, it is also interesting to see how people actually answered.\n\nThat caught me by surprise. Both options “roughly the same” and “depends on the data” got about 25% — the guessing probably. Does this mean half of the participants were guessing? As it is the last question some participants might have picked a random option just to get through. Quite possible. However, the correct option “much slower” got 38.8% at the cost of the “much faster” option, which got just 10.9%.\n\nMy intention with this question was to trap people into the “much faster” option because fetching less data should be faster — except when breaking an index-only scan. The only hypothesis I have for this result is that people might have got the idea that the obvious answer isn’t the correct one. That, however, would mean the 39% score doesn’t prove anything about the knowledge of this phenomenon in the field.\n\nAnother effect that I expected to have an impact is that “it is always depending on the data.” Of course there are edge cases where the performance impact might roughly stay the same — e.g., when all inspected rows are in the same table block. However, this is rather unlikely — just because there would be no point in adding the `date_column` for an index-only scan in the first place.\n\n## Question 5b: Index Column Order and Range Operators\n\nThis question is only shown to PostgreSQL users.\n\n> Is the following SQL good or bad practice from a performance perspective?\n> \n> Searching for entries in state X, not older than 5 years.\n> \n> ```\n> CREATE INDEX tbl_idx ON tbl (date_column, state);\n> \n> SELECT id, date_column, state\n> FROM tbl\n> WHERE date_column >= CURRENT_DATE - INTERVAL '5' YEAR\n> AND state = 'X';\n> \n> (365 rows)\n> ```\n> \n> The data distribution is as follows:\n> \n> ```\n> SELECT count(*)\n> FROM tbl\n> WHERE date_column >= CURRENT_DATE - INTERVAL '5' YEAR;\n> \n> count \n> -------\n> 1826\n> \n> SELECT count(*)\n> FROM tbl\n> WHERE state = 'X';\n> \n> count \n> -------\n> 10000\n> ```\n\nThere is an index with two columns and a query that filters on both of them. One filter uses an equals operator, the other a greater than or equal operator. When using each filter individually the query returns many more rows as when combining both filters.\n\nThe options are:\n\n- Good practice — There is no major improvement possible.\n- Bad practice — There is a major improvement possible.\n\nAnd the correct answer is “bad practice” because the column order in the index is the wrong way around. The general rule is that index columns can be used efficiently from the left hand side as long as they are used with equals operators. Further, one column can be used efficiently with a range operator. However, the first range operator effectively cuts off the index so that further columns cannot be used efficiently anymore. With efficiently I mean as an index access predicate. Please find a visualization [here](/sql/where-clause/searching-for-ranges/greater-less-between-tuning-sql-access-filter-predicates).\n\nWith the original index shown above, the query has to fetch 1826 entries from the index (those matching the `date_column` filter) and check each of them for the value of the `state` column. If we turn the index column order around, the database can use both filters efficiently (= as access predicate) and directly limit the index access to those 365 rows of interest.\n\nAnd this is how people answered:\n\nWait a moment, that’s below the guessing score! It’s not just people don’t know, they believe the wrong thing. However, I must admit that the term “major” is very problematic again. When I run this example, the speed-up I get is just 70%. Not even twice as fast.\n\n## Overall Score: How Many Passed the Test?\n\nLooking at each question individually is interesting, but doesn’t tell us how many participants managed to answer all five questions correctly, for example. The following chart has that information.\n\nFinally, I’d like to boil this chart down to a single figure: how many participants “passed” the test?\n\nConsidering that the test has only five questions, out of which four are 50/50 questions, I think it is fair to say three correct answers isn’t enough to pass the test. Requiring five correct answers would quite obviously be asking for too much. Requiring four correct answers to “pass” the test is therefore the only sensible choice I see. Using this definition, only *38.2% passed the test*. The chance to pass the test by guessing is still 12.5%.\n\n*If you like this article and want to learn about proper indexing, [SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2014-quiz-results&utm_medium=web&utm_content=overall) is for you.*\n\n#### Links\n\n- [Raw results](results-three-minutes-sql-performance-quiz/raw_quiz_results_20170802.txt.gz) (.txt.gz, 4.6 MB, explanations included) To verify my analysis and/or draw your own conclusions. Also includes data that I haven’t used. Especially timestamps that might allow to filter for guessing (e.g. question answered in less than X seconds).\n- [Indexes: The neglected performance all-rounder](/blog/2013-07/indexes-the-neglected-performance-all-rounder) Analysis why developers know very little about SQL indexing.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-â� sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).\n\n## Footnotes\n\n1. 0 Actually 13.3% if we consider that PostgreSQL users only have 50/50 questions and weight it according to the number of PostgreSQL tests conducted.", "znaku_textu": 21170, "slov": 3435, "odkazu": 64, "kodovani": "windows-1250", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:27", "sha256": "c275dee35dbe22beb6d47ab4823ac7ba20331f85faa087f0f416cf80a9774709", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://sql-performance-explained.com/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2014-04-01/thank-you-mysql-we-will-miss-you", "titulek": "Thank You MySQL, We’ll Miss You!", "h1": "Thank You MySQL, We’ll Miss You!", "popis": "When Oracle announced the retirement of MySQL, I just had to write a fare well letter to MySQL.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2014-04-01/thank-you-mysql-we-will-miss-you", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Thank You MySQL, We’ll Miss You!", "og:description": "When Oracle announced the retirement of MySQL, I just had to write a fare well letter to MySQL.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Thank You MySQL, We’ll Miss You!"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Thank You MySQL, We’ll Miss You!\n\n---\n\nDear MySQL,\n\nThank you for introducing me to SQL. It must have been 1998 when we first met I and fell in love with the simplicity of SQL immediately. Before that I’ve been using [C structs](https://en.wikipedia.org/wiki/Struct_(C_programming_language)) all the time; I had to do my joins programmatically and also create and maintain my indexes manually. It was even hard to combine several search conditions via `and` and `or`. But then there was the shiny new world of SQL you were showing me…\n\nEverything was easily. Just write a `where` clause, no matter how complex, you found the right rows. Joins were equally easy to write and you took all the effort to combine the data from several tables as I needed them. I also remember how easy it became to manage the schema. Instead of writing a program to copy my data from one C struct to another, I just say `alter table` now—in the meanwhile it even works online in many cases! I didn’t take long until I used SQL for stuff I wouldn’t have thought a database could do for me. So I was quickly embracing `group by` and co.\n\nBut I haven’t spent a lot of time with you lately. It’s not because I was too busy. I’m still practicing what you have shown me! And I’ve moved on. Now I’m using [common table expressions](https://en.wikipedia.org/wiki/Hierarchical_and_recursive_queries_in_SQL#Common_table_expression) to organize complex queries and I use [window functions](https://www.postgresql.org/docs/current/tutorial-window.html) to calculate running totals or just do a ranking. I’m also using joins more efficiently because I know about [hash](/sql/join/hash-join-partial-objects) and [sort/merge joins](/sql/join/sort-merge-join). A while ago I was wondering why you didn’t tell me about these things. But then I realized that you don’t know them.\n\nI know it was not always nice [what I said about you recently](/blog/2013-10/mysql-is-to-sql-like-mongodb-to-nosql). But now that [Oracle announced your retirement](https://en.wikipedia.org/wiki/April_Fools'_Day) to focus on [Oracle NoSQL](https://www.oracle.com/database/technologies/nosql/), I realized how right this [comment on reddit](https://www.reddit.com/r/programming/comments/1niheb/mongodb_is_to_nosql_like_mysql_to_sql_in_the_most/ccje34x/) was. Sure you are neither the [most advanced](https://www.postgresql.org/) nor the [most widely deployed](https://sqlite.org/mostdeployed.html) open source SQL database, but you introduced millions of people to SQL. There should be no tears when some of them move away because they want to see what’s next. Isn’t that the greatest compliment a teacher can get? You can be proud of what you have accomplished.\n\nThank you!\n\nMarkus WinandApril 1, 2014\n\n*ps.: Even when fooling around, I can’t resist to inform my fellow readers. Besides the claim that Oracle retires MySQL, everything is true. [Initially I thought Oracle NoSQL is an Aprils fool’s joke](https://x.com/MarkusWinand/status/339408492458819584) but it isn’t.*\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3607, "slov": 516, "odkazu": 63, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:28", "sha256": "b45ead8b32e862b9bbf134bf0406da001a7912fc9014356f0dc6e77c2bed7fe7", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://en.wikipedia.org/wiki/Struct_(C_programming_language)", "https://en.wikipedia.org/wiki/Hierarchical_and_recursive_queries_in_SQL", "https://www.postgresql.org/docs/current/tutorial-window.html", "https://en.wikipedia.org/wiki/April_Fools'_Day", "https://www.oracle.com/database/technologies/nosql/", "https://www.reddit.com/r/programming/comments/1niheb/mongodb_is_to_nosql_like_mysql_to_sql_in_the_most/ccje34x/", "https://www.postgresql.org/", "https://sqlite.org/mostdeployed.html", "https://x.com/MarkusWinand/status/339408492458819584", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2014-05/what-i-learned-about-sqlite-at-a-postgresql-conference", "titulek": "What I learned about SQLite…at a PostgreSQL conference", "h1": "What I learned about SQLite…at a PostgreSQL conference", "popis": "I’ve been to PgCon 2014 in Ottawa and ended up learning more about SQLite than about PostgreSQL.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2014-05/what-i-learned-about-sqlite-at-a-postgresql-conference", "jazyk": "en", "robots_meta": "", "og": {"og:title": "What I learned about SQLite…at a PostgreSQL conference", "og:description": "I’ve been to PgCon 2014 in Ottawa and ended up learning more about SQLite than about PostgreSQL.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "What I learned about SQLite…at a PostgreSQL conference"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# What I learned about SQLite…at a PostgreSQL conference\n\n---\n\nSo, I’ve been to [PgCon 2014 in Ottawa](https://www.pgcon.org/2014/) to give a short version of my [SQL performance training](https://winand.at/sql-training/inhouse). However, I think I ended up learning more about [SQLite](https://sqlite.com/) than about PostgreSQL there. Here is how that happened and what I actually learned.\n\n[Richard Hipp](https://en.wikipedia.org/wiki/D._Richard_Hipp), creator of SQLite was the keynote speaker at this years PgCon. In his keynote ([slides](https://www.pgcon.org/2014/schedule/attachments/319_PGCon2014OpeningKeynote.pdf), [video](https://www.youtube.com/watch?v=ZvmMzI0X7fE)) he has put the focus on three topics: how PostgreSQL influenced SQLite development (“[SQLite was originally written from PostgreSQL 6.5 documentation](https://x.com/dchest/status/469597738431434752)” and the “What Would PostgreSQL Do?” (WWPD) way of finding out what the SQL standard tries to tell us). The second main topic was that SQLite should be seen as an application file format—an alternative to inventing own file formats or using ZIPped XMLs. The statement “SQLite is not a replacement for PostgreSQL. SQLite is a replacement for fopen()” nails that (slide 21). Finally, Richard put a lot of emphasis on that fact that SQLite takes care of your data (crash safe, ACID)—unlike many of the so-called NoSQL systems, which Richard refers to as “Postmodern Databases: absence of objective truth; Queries return opinions rather than facts”. In his keynote, Richard has also shown that SQLite is pretty relaxed when it comes to data types. As a matter of fact, SQLite accepts strings like “Hello” for `INT` fields. Note that it still stores “Hello”—no data is lost. I think he mentioned that it is possible to enforce the types via `CHECK` constraints.\n\nHere I have to mention that I’ve had an e-mail conversation with Richard about covering SQLite on [Use The Index, Luke](/) last year. When our ways crossed at the PgCon hallway I just wanted to let him know that this has not been forgotten (despite the minimal progress on my side). Guess what—he was still remembering our mail exchange and immediately suggested to go through those topics once more in PgCon’s hacker lounge later. Said. Done. Here comes what I learned about SQLite.\n\nFirst of all, SQLite uses the [clustered index](/sql/clustering/index-organized-clustered-index) concept as known from SQL Server or MySQL/InnoDB. However, before version 3.8.2 (released 2013-12-06) you always had to use an `INTEGER` column as clustering key. If the primary key happened to be a non-integer, SQLite was creating an integer primary key implicitly and used this as the main clustering key. Querying by the real primary key (e.g. `TEXT`) required a secondary index lookup. This limitation was recently lifted by introducing [`WITHOUT ROWID` tables](https://sqlite.org/withoutrowid.html).\n\nWhen it comes to execution plans, SQLite has two different variants: the regular `explain` prefix returns the [byte code](https://www.sqlite.org/opcode.html) that is actually executed. To get an execution plan similar to what we are used to, use [`explain query plan`](https://www.sqlite.org/eqp.html). SQLite has some hints (unlike PostgreSQL) to affect the query plan: [`indexed by`](https://www.sqlite.org/lang_indexedby.html) and [`unlikely`](https://www.sqlite.org/lang_corefunc.html#unlikely), [`likelihood`](https://www.sqlite.org/lang_corefunc.html#likelihood).\n\nWe also discussed whether or not SQLite can cope with search conditions like `(col1, col2) < (val1, val2)`—it can’t. Here Richard was questioning the motivation to have that, so I gave him an elevator-pitch version of my “[Pagination Done The PostgreSQL Way](/blog/2013-07/pagination-done-the-postgresql-way)” talk. I think he got “excited” about this concept to avoid `offset` at all and I’m curious to see if he can make it work in SQLite faster than I’m adding SQLite content to [Use The Index, Luke](/) :)\n\nSQLite supports `limit` and `offset` (*sigh*) but the optimizer does currently not consider `limit` for optimization. Offering the SQL:2008 `first fetch ... rows only` syntax is not planned and might actually turn out to be hard because the parser is close to run out of 8-bit token codes (when I understood that right).\n\nJoins are basically always executed as [nested loops joins](/sql/join/nested-loops-join-n1-problem) but SQLite might create an “[automatic transient index](https://www.sqlite.org/optoverview.html#autoindex)” for the duration of the query. We also figured out that there seems to be a oddity with they way `CROSS JOIN` works in SQLite: it turn [the optimizers table reordering off](https://www.sqlite.org/optoverview.html#crossjoin). Non-cross joins, on the other hand, don’t enforce the presence of `ON` or `USING` so that you can still build a Cartesian product using the optimizers smartness to reorder the tables.\n\nLast but not least I’d like to mention that [SQLite supports partial indexes](https://www.sqlite.org/partialindex.html) in the way it should be: just a `where` clause at index creation. Partial indexes are available since version 3.8.0 (released 2013-08-26).\n\nOn the personal side, I’d describe Richard as very pragmatic and approachable. [He joined twitter](https://x.com/DRichardHipp) a few month ago and all he did there is helping people who asked questions about SQLite. Really, look at [his time line](https://x.com/DRichardHipp). That says a lot.\n\nI’m really happy that I had the opportunity to meet Richard at a PostgreSQL conference—as happy as I was to meet [Joe “Smartie” Celko](/blog/2012-11/pgconfeu2012-summary) years ago…at a another PostgreSQL conference. Their excellent keynote speaker selection is just one more reason to recommend PostgreSQL conferences in general. [Here are the upcoming ones](https://wiki.postgresql.org/wiki/Events) just in case you got curious.\n\nps.: There was also a unconference where I discussed the topic of [Bitmap Index Only Scan (slides & minutes)](https://wiki.postgresql.org/wiki/Pgcon2014unconferenceBitmapIndexOnlyScan).\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 6686, "slov": 954, "odkazu": 74, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:29", "sha256": "587090504cc39a16066afbfb4d0ee080a3237bc8846684bff51726991765a5ed", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://www.pgcon.org/2014/", "https://winand.at/sql-training/inhouse", "https://sqlite.com/", "https://en.wikipedia.org/wiki/D._Richard_Hipp", "https://www.pgcon.org/2014/schedule/attachments/319_PGCon2014OpeningKeynote.pdf", "https://www.youtube.com/watch?v=ZvmMzI0X7fE", "https://x.com/dchest/status/469597738431434752", "https://sqlite.org/withoutrowid.html", "https://www.sqlite.org/opcode.html", "https://www.sqlite.org/eqp.html", "https://www.sqlite.org/lang_indexedby.html", "https://www.sqlite.org/lang_corefunc.html", "https://www.sqlite.org/optoverview.html", "https://www.sqlite.org/partialindex.html", "https://x.com/DRichardHipp", "https://wiki.postgresql.org/wiki/Events", "https://wiki.postgresql.org/wiki/Pgcon2014unconferenceBitmapIndexOnlyScan", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2014-07/finding-all-the-red-mms", "titulek": "Finding All the Red M&Ms: A Story of Indexes and Full‑Table Scans", "h1": "Finding All the Red M&Ms: A Story of Indexes and Full‑Table Scans", "popis": "A colourful and tasty introduction in cost-based database optimization.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2014-07/finding-all-the-red-mms", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Finding All the Red M&Ms: A Story of Indexes and Full‑Table Scans", "og:description": "A colourful and tasty introduction in cost-based database optimization.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Finding All the Red M&Ms: A Story of Indexes and Full‑Table Scans"}, {"uroven": 2, "text": "How do databases determine the cost of an index?"}, {"uroven": 2, "text": "What have M&M’s got to do with databases?"}, {"uroven": 2, "text": "When does an index scan become more efficient than a FTS?"}, {"uroven": 2, "text": "Bringing it all together"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Finding All the Red M&Ms: A Story of Indexes and Full‑Table Scans\n\n---\n\n> *In this guest post, [Chris Saxon](https://www.chrissaxon.co.uk/) explains a very important topic using an analogy with chocolates: When does a database use an index and when is it better not using it. Although Chris explanation has the Oracle database in mind, the principles apply to other databases too.*\n\nA common question that comes up when people start tuning queries is “why doesn’t this query use the index I expect?”. There are a few myths surrounding when database optimizers will use an index. A common one I’ve heard is that an index will be used when accessing 5% or less of the rows in a table. This isn’t the case however - the basic decision on whether or not to use an index comes down to its cost.\n\n## How do databases determine the cost of an index?\n\nBefore getting into the details, let’s talk about chocolate! Imagine you have 100 packets of M&M’s. You also have a document listing the colour of each M&M and the bag it’s stored in. This is ordered by colour, so we have all the blue sweets first, then the brown, green and so on like so:\n\nYou’ve been asked to find all the red M&M’s. There’s a couple of basic ways you could approach this task:\n\nMethod 1\n\nGet your document listing the colour and location of each M&M. Go to the top of the “red” section. Lookup the location of the first red M&M, pick up the bag it states, and get the sweet. Go back to your document and repeat the process for the next red chocolate. Keep going back-and-forth between your document and the bags until you’ve reached the end of the red section.\n\nMethod 2\n\nPick up a number of bags at a time (e.g. 10), empty their contents out, pick out the red chocolates and return the others (back to their original bag).\n\nWhich approach is quicker?\n\nIntuitively the second approach appears to be faster. You only select each bag once and then do some filtering of the items inside. Whereas with the first approach you have done a lot of back-and-forth between the document and the bags. This means you have to look into each bag multiple times.\n\nWe can be a bit more rigorous than this though. Let’s calculate how many operations we need to do to get all the red chocolates in each case.\n\nWhen going between the document and the bags (method 1), each time you lookup the location of a new sweet and fetch that bag that’s a new operation. You have 100 bags with around 55 sweets in each. This means you’re doing roughly 920 (100 bags x 55 sweets / 6 colours) operations (plus some work to find the red section in your document). So the “cost” of using the document is around 920.\n\nWith the second approach you collect 10 bags in one step. This means you do ( 100 bags / 10 bags per operation = ) 10 operations (plus some filtering of the chocolates in them), giving a “cost” of 10.\n\nComparing these costs (920 vs. 10), method 2 is the clear winner.\n\nLet’s imagine another scenario. Mars have started doing a promotion where around 1 in 100 bags contain a silver M&M. If you get the silver sweet, you win a prize. You want to find the silver chocolate!\n\nIn this case, using method 1, you go to the document to find the location of the single sweet. Then you go to that bag and retrieve the sweet. One operation (well two, including going to the document to find location of the silver chocolate), so we have a cost of two.\n\nWith method 2, you still need to pick up every single bag (and do some filtering) just to find one sweet - the cost is fixed at 10. Clearly method 1 is far superior in this case.\n\n## What have M&M’s got to do with databases?\n\nWhen Oracle stores a record to the database, it is placed in a block. Just like there are many M&Ms in a bag, (normally) there are many rows in a block. When accessing a particular row, Oracle fetches the whole block and retrieves the requested row from within it. This is analogous to us picking up a bag of M&Ms and then picking a single chocolate out.\n\nWhen doing an index-range scan, Oracle will search the index (the document) to find the first value matching your where clause. It then goes back-and-forth between the index and the table blocks, fetching the records from the location pointed to by the index. This is similar to method 1, where you continually switch between the document and the M&M bags.\n\nAs the number of rows accessed by an index increases, the database has to do more work. Therefore the cost of using an index increases in line with the number of records it is expected to fetch.\n\nWhen doing a full table scan (FTS), Oracle will fetch several blocks at once in a *multi-block read*. The data fetched is then filtered so that only rows matching your where clause are returned (in this case the red M&Ms) – the rest are discarded. Just like in method 2.\n\nThe expected number of rows returned has little impact on the work a FTS does. Its basic cost is fixed by the size of the table and how many blocks you fetch at once.\n\nWhen fetching a “high” percentage of the rows from a table, it becomes far more efficient to get several blocks at once and do some filtering than it is to visit a single block multiple times.\n\n## When does an index scan become more efficient than a FTS?\n\nIn our M&M example above, the “full-table scan” method fetches all 100 bags in 10 operations. Whereas with “index” approach requires a separate operation for each sweet. So an index is more efficient when it points to 10 M&Ms or less.\n\nMars puts around 55 M&M’s in each bag, so as a percentage of the “table” that’s just under ( 10 M&M’s / (100 bags * 55 sweets) * 100 = ) 0.2%!\n\nWhat if Mars releases some “giant” M&Ms with only 10 sweets in a bag? In this case there’s fewer sweets in total, so the denominator in the equation above decreases. Our FTS approach is still fixed at a “cost” of 10 for the 100 bags. This means the point at which an index is better is when accessing approximately ( 10/1000*100 = ) 1% of the “rows”. A higher percentage, but still small in real terms.\n\nIf they released “mini” M&Ms with 200 in a bag, the denominator would increase. This means that the index is more efficient when accessing a very small percentage of the table!\n\nSo as you increase the space required to store a row, an index becomes more effective than a FTS. The number of rows accessed by the index remains fixed. The number of blocks required to store the data increases however, making the FTS more expensive and leading to it having a higher cost.\n\nThere’s a big assumption made in the above reasoning however. It’s that there’s no correlation between the order M&M’s are listed in the document and which bag they are in. So, for example, the first red M&M (in the document) may be in bag 1, the second in bag 56, the third in bag 20, etc.\n\nLet’s make a different assumption – that the order of red chocolates in the document corresponds to the order they appear in the bags. So the first 9 red sweets are in bag 1, the next 9 in bag 2 etc. While you still have to visit all 100 bags, you can keep the last bag accessed in your hand, only switching bags every 9 or so sweets. This reduces the number of operations you do, making the index approach more efficient.\n\nWe can take this further still. What if Mars changes the bagging process so that only one colour appears in each bag?\n\nNow, instead of having to visit every single bag to get all the red sweets, you only have to visit around ( 100 bags / 6 colours) 16 bags. If the sweets are also placed in the bags in the same order they are listed in the document (so M&M’s 1-55 are all blue and in bag 1, bag 2 has the blue M&M’s 56-100, and so on until bag 100, which has yellow M&M’s 496-550) you get the benefits of not switching bags compounded with the effect of having fewer bags to fetch.\n\nThis principle – how closely the order of records in a table matches the order they’re listed in a corresponding index – is referred to as the *clustering factor*. This figure is lower when the rows appear in the same physical order in the table as they do in the index (all sweets in a bag are the same colour) and higher when there’s little or no correlation.\n\nThe closer the clustering factor is to the number of blocks in a table the more likely it is that the index will be used (it is assigned a lower cost). The closer it is to the number of rows in a table, the more likely it is a FTS will be chosen (the index access is given a higher cost).\n\n## Bringing it all together\n\nTo sum up, we can see the cost-based optimizer decides whether to use an index or FTS by:\n\n- Taking the number of blocks used to store the table and dividing this by the number of blocks read in a multi-block read to give the FTS cost.\n- For each index on the table available to the query:\n - Finding the percentage of the rows in the table it expects a query to return (the selectivity)\n - This is then used to determine the percentage of the index expected to be accessed\n - The selectivity is also multiplied by the clustering factor to estimate the number of table blocks it expects to access to fetch these rows via an index\n - Adding these numbers together to give the expected cost (of the index)\n- The cost of the FTS is then compared to each index inspected and the access method with the lowest cost used.\n\nThis is just an overview of how the (Oracle) cost-based optimizer works. If you want to see the formulas the optimizer uses have a read of Wolfgang Breitling’s “[Fallacies of the Cost Based Optimizer](http://www.centrexcc.com/Fallacies%20of%20the%20Cost%20Based%20Optimizer.pdf)” paper or Jonathan Lewis’ [Cost-Based Oracle Fundamentals](https://www.amazon.co.uk/Cost-Based-Oracle-Fundamentals-Experts-Voice/dp/1590596366/ref=sr_1_1?ie=UTF8&qid=1502472304&sr=8-1&keywords=Cost-Based+Oracle+Fundamentals&tag=winandat-21&m=AJFZUYB7XQGQN) book. The blogs of [Jonathan Lewis](https://jonathanlewis.wordpress.com/), [Richard Foote](https://richardfoote.wordpress.com/) and of course Markus’ articles on [this site](/) also contain many posts going into this subject in more detail.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nChris Saxon is an Oracle Developer Advocate for SQL. His job is to help you get the best out of the Oracle Database and have fun with SQL!\nTo help you with this he blogs at [All Things SQL](https://blogs.oracle.com/sql/) and creates videos on [The Magic of SQL](https://www.youtube.com/c/TheMagicofSQL).", "znaku_textu": 10559, "slov": 1902, "odkazu": 52, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:30", "sha256": "a4dfd372d8466c74eb324656739933d9fb8152306bcb3a2d56579cf2b39a1099", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://www.chrissaxon.co.uk/", "http://www.centrexcc.com/Fallacies%20of%20the%20Cost%20Based%20Optimizer.pdf", "https://www.amazon.co.uk/Cost-Based-Oracle-Fundamentals-Experts-Voice/dp/1590596366/ref=sr_1_1?ie=UTF8&keywords=Cost-Based+Oracle+Fundamentals&m=AJFZUYB7XQGQN&qid=1502472304&sr=8-1&tag=winandat-21", "https://jonathanlewis.wordpress.com/", "https://richardfoote.wordpress.com/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://blogs.oracle.com/sql/", "https://www.youtube.com/c/TheMagicofSQL", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand", "https://winand.at/"]} {"url": "https://use-the-index-luke.com/blog/2014-10/meta-post-mascot-japanese-db2", "titulek": "Meta-Post: New Mascot, New Language, New Database", "h1": "Meta-Post: New Mascot, New Language, New Database", "popis": "It has been quiet here at the Use The Index, Luke blog lately. But that’s not because I’ve run out of topics to write about — in fact, my blog backlog seems to be ever growing.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2014-10/meta-post-mascot-japanese-db2", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Meta-Post: New Mascot, New Language, New Database", "og:description": "It has been quiet here at the Use The Index, Luke blog lately. But that’s not because I’ve run out of topics to write about — in fact, my blog backlog seems to be ever growing.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Meta-Post: New Mascot, New Language, New Database"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Meta-Post: New Mascot, New Language, New Database\n\n---\n\nIt has been quiet here at the *Use The Index, Luke* blog lately. But that’s not because I’ve run out of topics to write about — in fact, my blog backlog seems to be ever growing — the recent silence is just because there are some more demanding projects happening at the moment.\n\nFirst of all, *Use the Index, Luke* got a new mascot—not exactly breaking news. However, I’m currently preparing give-aways and merchandise products featuring the new mascot. Stay tuned.\n\nNext, *Use The Index, Luke* gets translated to Japanese! The first two chapters have [just been published](/ja/sql/preface). Insiders will remember that chapter 1 and 2 make up half of the book. The translation is done by [Hayato Matsuura](https://x.com/dblmkt), [Takuto Matsuu](https://x.com/matsuu) has a second look over it. As far as I can tell both are making a great job and I’d like to be the first to thank them! Please help spreading the word about this in the Japanese community.\n\nFinally, I’m just adding Db2 (LUW) as a first-class citizen to *Use The Index, Luke* because a client wanted to get [my SQL performance training](https://winand.at/sql-training/inhouse) based on Db2 (LUW) Express-C (which is free, by the way). Like the Japanese translation, this work is not yet finished. However, the [appendix on execution plans](/sql/explain-plan/db2) is already there. Again, please help spreading the word about this in the Db2 community.\n\nThat’s it. I just wanted to give you a short update.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2165, "slov": 330, "odkazu": 57, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:32", "sha256": "a64a3c1bb17a933c2bc60e204b900fdce6f265c0051071ad79147e6f7988af52", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://x.com/dblmkt", "https://x.com/matsuu", "https://winand.at/sql-training/inhouse", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2014-11/seven-surprising-findings-about-DB2", "titulek": "Seven Surprising Findings About Db2 (LUW)", "h1": "Seven Surprising Findings About Db2 (LUW)", "popis": "Free. Easy installation. No easy execution plan. INCLUDE clause only for unique indexes. No NULL FIRST/LAST.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2014-11/seven-surprising-findings-about-DB2", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Seven Surprising Findings About Db2 (LUW)", "og:description": "Free. Easy installation. No easy execution plan. INCLUDE clause only for unique indexes. No NULL FIRST/LAST.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Seven Surprising Findings About Db2 (LUW)"}, {"uroven": 2, "text": "Free & Easy"}, {"uroven": 2, "text": "No Easy Explain"}, {"uroven": 2, "text": "Emulating Partial Indexes is Possible"}, {"uroven": 2, "text": "INCLUDE Clause Only for Unique Indexes"}, {"uroven": 2, "text": "Almost No NULLS FIRST/LAST Support until 11.1"}, {"uroven": 2, "text": "SQL:2008 FETCH FIRST but not OFFSET (until 11.1)"}, {"uroven": 2, "text": "Decent Row-Value Predicates Support"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Seven Surprising Findings About Db2 (LUW)\n\n---\n\nI’ve just completed IBM Db2 for Linux, Unix and Windows (LUW) coverage here on [Use The Index, Luke](/) as preparation for an upcoming [training I’m giving](https://winand.at/sql-training/inhouse). This blog post describes the major differences I’ve found compared to the other databases I’m covering (Oracle, SQL Server, PostgreSQL and MySQL).\n\n## Free & Easy\n\nWell, let’s face it: it’s IBM software. It has a pretty long history. You would probably not expect that it is easy to install and configure, but in fact: it is. At least Db2 (LUW) Express-C 10.5 (LUW is for Linux, Unix and Windows, Express-C is the free community edition). That might be another surprise: there is a free community edition. It’s not open source, but it’s [free as in free beer](https://www.ibm.com/us-en/marketplace/db2-express-c).\n\n## No Easy Explain\n\nThe first problem I stumbled upon is that Db2 has no easy way to display an execution plan. No kidding. Here is what IBM says about it:\n\n- Explain a statement by prefixing it with `explain plan for` This stores the execution plan in a set of tables in the database (you’ll need to create these tables first). This is pretty much like in Oracle.\n- Display a stored explain plan using `db2exfmt` This is a command line tool, not something you can call from an SQL prompt. To run this tool you’ll need shell access to a Db2 installation (e.g. on the server). That means, that you cannot use this tool over an regular database connection.\n\nThere is another command line tool (`db2expln`) that combines the two steps from above. Apart from the fact that this procedure is not exactly convenient, the output you get an ASCII art:\n\n`Access Plan:\n-----------\n Total Cost: 60528.3\n Query Degree: 1\n\n Rows\n RETURN\n ( 1)\n Cost\n I/O\n |\n 49534.9\n ^HSJOIN\n ( 2)\n 60528.3\n 68095\n /-----+------\\\n 49534.9 10000\n TBSCAN TBSCAN\n ( 3) ( 4)\n 59833.6 687.72\n 67325 770\n | |\n 1.00933e+06 10000\n TABLE: DB2INST1 TABLE: DB2INST1\n SALES EMPLOYEES\n Q2 Q1`\n\nPlease note that this is just an excerpt—the full output of `db2exfmt` has 400 lines. Quite a lot information that you’ll hardly ever need. Even the information that you need all the time (the operations) is presented in a pretty unreadable way (IMHO). I’m particularly thankful that all the numbers you see above are not labeled—that’s really the icing that renders this “tool” totally useless for the occasional user.\n\nHowever, according to the IBM documentation there is another way to display an execution plan: “[Write your own queries against the explain tables.](https://www.ibm.com/docs/en/db2/11.5.x?topic=facility-tools-collecting-analyzing-explain-information)” And that’s exactly what I did: I wrote a view called `last_explained` that does exactly what it’s name suggest: it shows the execution plan of the last statement that was explained (in a non-useless formatting):\n\n`Explain Plan\n------------------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 60528\n 2 | HSJOIN | 49535 of 10000 | 60528\n 3 | TBSCAN SALES | 49535 of 1009326 ( 4.91%) | 59833\n 4 | TBSCAN EMPLOYEES | 10000 of 10000 (100.00%) | 687\n\nPredicate Information\n 2 - JOIN (Q2.SUBSIDIARY_ID = DECIMAL(Q1.SUBSIDIARY_ID, 10, 0))\n JOIN (Q2.EMPLOYEE_ID = DECIMAL(Q1.EMPLOYEE_ID, 10, 0))\n 3 - SARG ((CURRENT DATE - 6 MONTHS) < Q2.SALE_DATE)\n\nExplain plan by Markus Winand - NO WARRANTY\nhttp://use-the-index-luke.com/s/last_explained`\n\nI’m pretty sure many Db2 (LUW) users will say that this presentation of the execution plan is confusing. And that’s OK. If you are used to the way IBM presents execution plans, just stick to what you are used to. However, I’m working with all kinds of databases and they all have a way to display the execution plan similar to the one shown above—for me this format is much more useful. Further, I’ve made a useful selection of data to display: the row count estimates and the predicate information.\n\nYou can get the source of the `last_explained` view from [here](/sql/explain-plan/db2/getting-an-execution-plan) or from [GitHub](https://github.com/fatalmind/DB2-last-explained) ([direct download](https://raw.githubusercontent.com/fatalmind/DB2-last-explained/master/last_explained.sql)). I’m serious about the no warranty part. Yet I’d like to know about problems you have with the view.\n\n## Emulating Partial Indexes is Possible\n\n[Partial indexes](/sql/where-clause/partial-and-filtered-indexes) are indexes not containing all table rows. They are useful in three cases:\n\n1. To preserve space when the index is only useful for a very small fraction of the rows. Example: [queue tables](/sql/where-clause/partial-and-filtered-indexes).\n2. To establish a specific row order in presence of constant non-equality predicates. Example: `WHERE x IN (1, 5, 9) ORDER BY y`. An index like the following can be used to avoid a sort operation: `CREATE INDEX … ON … (y)\n WHERE x IN (1, 5, 9)`\n3. To implement unique constraints on a subset of rows (e.g. only those `WHERE active = 'Y'`).\n\nHowever, Db2 (LUW) doesn’t support a `where` clause for indexes like shown above. But Db2 has many Oracle-compatibility features, one of them is `[EXCLUDE NULL KEYS](https://www.ibm.com/docs/en/db2/11.5.x?topic=statements-create-index)`: “Specifies that an index entry is not created when all parts of the index key contain the null value.” This is actually the hard-wired behaviour in the Oracle database and it is commonly exploited to [emulate partial indexes in the Oracle database](/sql/where-clause/null/partial-index).\n\nGenerally speaking, emulating partial indexes works by mapping all parts of the key (all indexed columns) to `NULL` for rows that should not end up in the index. As an example, let’s emulate this partial index in the Oracle database (Db2 is next):\n\n```\nCREATE INDEX messages_todo\n ON messages (receiver)\n WHERE processed = 'N'\n```\n\nThe solution presented in [*SQL Performance Explained*](https://sql-performance-explained.com/l?utm_source=use-the-index-luke.com&utm_campaign=blog-201411-db2&utm_medium=web&utm_content=blog-db2intro-partialidx) uses a function to map the processed rows to `NULL`, otherwise the receiver value is passed through:\n\n```\nCREATE OR REPLACE\nFUNCTION pi_processed(processed CHAR, receiver NUMBER)\nRETURN NUMBER\nDETERMINISTIC\nAS BEGIN\n IF processed IN ('N') THEN\n RETURN receiver;\n ELSE\n RETURN NULL;\n END IF;\nEND\n```\n\nIt’s a deterministic function and can thus be used in an Oracle function-based index. This won’t work with Db2, because Db2 doesn’t allow user defined-functions in index definitions. However, let’s first complete the Oracle example.\n\n```\nCREATE INDEX messages_todo\n ON messages (pi_processed(processed, receiver))\n```\n\nThis index has only rows `WHERE processed IN ('N')`—otherwise the function returns `NULL` which is not put in the index (there is no other column that could be non-`NULL`). Voilà: a partial index in the Oracle database.\n\nTo use this index, just use the `pi_processed` function in the `where` clause:\n\n```\nSELECT message\n FROM messages\n WHERE pi_processed(processed, receiver) = ?\n```\n\nThis is functionally equivalent to:\n\n```\nSELECT message\n FROM messages\n WHERE processed = 'N'\n AND receiver = ?\n```\n\nSo far, so ugly. If you go for this approach, you’d better need the partial index desperately.\n\nTo make this approach work in Db2 we need two components: (1) the `EXCLUDE NULL KEYS` clause (no-brainer); (2) a way to map processed rows to `NULL` without using a user-defined function so it can be used in a Db2 index.\n\nAlthough the second one might seem to be hard, it is actually very simple: Db2 can do expression based indexing, just not on user-defined functions. The mapping we need can be accomplished with regular SQL expressions:\n\n```\nCASE WHEN processed = 'N' THEN receiver\n ELSE NULL\nEND\n```\n\nThis implements the very same mapping as the `pi_processed` function above. Remember that `CASE` expressions are first class citizens in SQL—they can be used in Db2 index definitions (on LUW just since 10.5):\n\n```\nCREATE INDEX messages_not_processed_pi\n ON messages (CASE WHEN processed = 'N' THEN receiver\n ELSE NULL\n END)\nEXCLUDE NULL KEYS;\n```\n\nThis index uses the `CASE` expression to map not to be indexed rows to `NULL` and the `EXCLUDE NULL KEYS` feature to prevent those row from being stored in the index. Voilà: a partial index in Db2 LUW 10.5.\n\nTo use the index, just use the `CASE` expression in the `where` clause and check the execution plan:\n\n```\nSELECT *\n FROM messages\n WHERE (CASE WHEN processed = 'N' THEN receiver\n ELSE NULL\n END) = ?;\n```\n\n```\nExplain Plan\n-------------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 49686\n 2 | TBSCAN MESSAGES | 900 of 999999 ( .09%) | 49686\n\nPredicate Information\n 2 - SARG (Q1.PROCESSED = 'N')\n SARG (Q1.RECEIVER = ?)\n```\n\nOh, that’s a big disappointment: the optimizer didn’t take the index. It does a full table scan instead. What’s wrong?\n\nIf you have a very close look at the execution plan above, which I created with my [`last_explained` view](/sql/explain-plan/db2/getting-an-execution-plan), you might see something suspicious.\n\nLook at the predicate information. What happened to the `CASE` expression that we used in the query? The Db2 optimizer was smart enough rewrite the expression as `WHERE processed = 'N' AND receiver = ?`. Isn’t that great? Absolutely!…except that this smartness has just ruined my attempt to use the partial index. That’s what I meant when I said that `CASE` expressions are first class citizens in SQL: the database has a pretty good understanding what they do and can transform them.\n\nWe need a way to apply our magic `NULL`-mapping but we can’t use functions (can’t be indexed) nor can we use `CASE` expressions, because they are optimized away. Dead-end? Au contraire: it’s pretty easy to confuse an optimizer. All you need to do is to obfuscate the `CASE` expression so that the optimizer doesn’t transform it anymore. Adding zero to a numeric column is always my first attempt in such cases:\n\n```\nCASE WHEN processed = 'N' THEN receiver + 0\n ELSE NULL\nEND\n```\n\nThe `CASE` expression is essentially the same, I’ve just added zero to the `RECEIVER` column, which is numeric. If I use this expression in the index and the query, I get this execution plan:\n\n`ID | Operation | Rows | Cost\n 1 | RETURN | | 13071\n 2 | FETCH MESSAGES | 40000 of 40000 | 13071\n 3 | RIDSCN | 40000 of 40000 | 1665\n 4 | SORT (UNQIUE) | 40000 of 40000 | 1665\n 5 | **IXSCAN MESSAGES_NOT_PROCESSED_PI** | 40000 of 999999 | 1646\n\nPredicate Information\n 2 - SARG ( CASE WHEN (Q1.PROCESSED = 'N') THEN (Q1.RECEIVER + 0)\n ELSE NULL END = ?)\n 5 - START ( CASE WHEN (Q1.PROCESSED = 'N') THEN (Q1.RECEIVER + 0)\n ELSE NULL END = ?)\n STOP ( CASE WHEN (Q1.PROCESSED = 'N') THEN (Q1.RECEIVER + 0)\n ELSE NULL END = ?)`\n\nThe partial index is used as intended. The `CASE` expression appears unchanged in the predicate information section.\n\nI haven’t checked any other ways to emulate partial indexes in Db2 (e.g., using partitions like in more recent Oracle versions).\n\nAs always: just because you can do something doesn’t mean you should. This approach is so ugly—even more ugly than the Oracle workaround—that you must desperately need a partial index to justify this maintenance nightmare. Further it will stop working whenever the optimizer becomes smart enough to optimize `+0` away. However, then you just need put an even more ugly obfuscation in there.\n\n## `INCLUDE` Clause Only for Unique Indexes\n\nWith the `INCLUDE` clause you can add extra columns to an index for the sole purpose to allow in [index-only scan](/sql/clustering/index-only-scan-covering-index) when these columns are selected. I knew the `INCLUDE` clause before because SQL Server offers it too, but there are some differences:\n\n- In SQL Server `INCLUDE` columns are [only added to the leaf nodes](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-index-transact-sql) of the index—not in the root and branch nodes. This limits the impact on the B-tree’s depth when adding many or long columns to an index. This also allows to bypass some limitations (number of columns, total index row length, allowed data types). That doesn’t seem to be the case in Db2.\n- In Db2 the `INCLUDE` clause is only valid for unique indexes. It allows you to enforce the uniqueness of the key columns only—the `INCLUDE` columns are just not considered when checking for uniqueness. This is the same in SQL Server except that SQL Server supports `INCLUDE` columns on non-unique indexes too (to leverage the above-mentioned benefits).\n\n## Almost No `NULLS FIRST`/`LAST` Support until 11.1\n\nThe `NULLS FIRST` and `NULLS LAST` modifiers to the `order by` clause allow you to specify whether `NULL` values are considered as larger or smaller than non-`NULL` values during sorting. Strictly speaking, you must always specify the desired order when sorting nullable columns because the SQL standard doesn’t specify a default. As you can see in the following chart, the default order of `NULL` is indeed different across various databases:\n\nAlthough Db2 (LUW) accepted `NULLS FIRST` and `NULLS LAST` for a while it is only fully supported since release 11.1. Previous releases only accepted a `NULLS FIRST/LAST` clause if the clause happened to request the default order anyway. Even in release 11.1, `NULLS FIRST/LAST` is not valid in a `CREATE INDEX` statement.\n\n## SQL:2008 `FETCH FIRST` but not `OFFSET` (until 11.1)\n\nDb2 supports the `fetch first … rows only` clause for a while now—kind-of impressive considering it was “just” added with the SQL:2008 standard. However, Db2 doesn’t support the `offset` clause, which was introduced with the very same release of the SQL standard. Although it might look like an arbitrary omission, it is in fact a very wise move that I deeply respect. `offset` is the root of so much evil. In the next section, I’ll explain how to live without `offset`.\n\n**UPDATE:** Db2 11.1 supports `offset` even without the below mentioned compatibility vector.\n\nSide node: If you have code using `offset` that you cannot change, you can still activate the MySQL compatibility vector that makes `limit` and `offset` available in Db2. Funny enough, combining `fetch first` with `offset` is then still not possible (that would be standard compliant).\n\n## Decent Row-Value Predicates Support\n\nSQL row-values are multiple scalar values grouped together by braces to form a single logical value. `IN`-lists are a common use-case:\n\n```\nWHERE (col_a, col_b) IN (SELECT col_a, col_b FROM…)\n```\n\nThis is supported by pretty much every database. However, there is a second, hardly known use-case that has pretty poor support in today’s SQL databases: [key-set pagination](/sql/partial-results/fetch-next-page) or `offset`-less pagination. Keyset pagination uses a `where` clause that basically says “I’ve seen everything up till here, just give me the next rows”. In the simplest case it looks like this:\n\n```\nSELECT …\n FROM …\n WHERE time_stamp < ?\n ORDER BY time_stamp DESC\n FETCH FIRST 10 ROWS ONLY\n```\n\nImagine you’ve already fetched a bunch of rows and need to get the next few ones. For that you’d use the `time_stamp` value of the last entry you’ve got for the bind value (`?`). The query then just return the rows from there on. But what if there are two rows with the very same `time_stamp` value? Then you need a tiebreaker: a second column—preferably a unique column—in the `order by` and `where` clauses that unambiguously marks the place till where you have the result. This is where row-value predicates come in:\n\n```\nSELECT …\n FROM …\n WHERE (time_stamp, id) < (?, ?)\n ORDER BY time_stamp DESC, id DESC\n FETCH FIRST 10 ROWS ONLY\n```\n\nThe `order by` clause is extended to make sure there is a well-defined order if there are equal `time_stamp` values. The `where` clause just selects what’s after the row specified by the `time_stamp` and `id` pair. It couldn’t be any simpler to express this selection criteria. Unfortunately, neither the Oracle database nor SQLite or SQL Server understand this syntax—even though it’s in the SQL standard since 1992! However, it is possible to [apply the same logic without row-value predicates](/sql/partial-results/fetch-next-page)—but that’s rather inconvenient and easy to get wrong.\n\nEven if a database understands the row-value predicate, it’s not necessarily understanding these predicates good enough to make proper use of indexes that support the `order by` clause. This is where MySQL fails—although it applies the logic correctly and delivers the right result, it does not use an index for that and is thus rather slow. In the end, Db2 (LUW) (since 10.1) and PostgreSQL (since 8.4) are the only two databases that support row-value predicates in the way it should be.\n\nThe fact that Db2 LUW has everything you need for convenient keyset pagination is also the reason why there is absolutely no reason to complain about the missing `offset` functionality. In fact I think that `offset` should not have been added to the SQL standard and I’m happy to see a vendor that resisted the urge to add it because its became part of the standard. Sometimes the standard is wrong—just sometimes, not very often ;) I can’t change the standard—all I can do is teaching [how to do it right](/no-offset) and start campaigns like [#NoOffset](/no-offset).\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 17468, "slov": 2840, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:33", "sha256": "17bc4b730caef46369f833134ed88606820fdafebb889d3abb30e829f6d7f07b", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/sql-training/inhouse", "https://www.ibm.com/us-en/marketplace/db2-express-c", "https://www.ibm.com/docs/en/db2/11.5.x?topic=facility-tools-collecting-analyzing-explain-information", "https://github.com/fatalmind/DB2-last-explained", "https://raw.githubusercontent.com/fatalmind/DB2-last-explained/master/last_explained.sql", "https://www.ibm.com/docs/en/db2/11.5.x?topic=statements-create-index", "https://sql-performance-explained.com/l", "https://learn.microsoft.com/en-us/sql/t-sql/statements/create-index-transact-sql", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2015-02/modern-sql", "titulek": "Modern SQL in PostgreSQL [and other databases]", "h1": "Modern SQL in PostgreSQL [and other databases]", "popis": "SQL is out of fashion—partly due to the NoSQL movement, but mostly because SQL is used like 20 years ago.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2015-02/modern-sql", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Modern SQL in PostgreSQL [and other databases]", "og:description": "SQL is out of fashion—partly due to the NoSQL movement, but mostly because SQL is used like 20 years ago.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Modern SQL in PostgreSQL [and other databases]"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Modern SQL in PostgreSQL [and other databases]\n\n---\n\nSQL has gone out of fashion lately—partly due to the NoSQL movement, but mostly because SQL is often still used like 20 years ago. As a matter of fact, the SQL standard continued to evolve during the past decades resulting in the current release of 2011. In this session, we will go through the most important additions since the widely known SQL-92, explain how they work and how PostgreSQL supports and extends them. We will cover common table expressions and window functions in detail and have a very short look at the temporal features of SQL:2011 and the related features of PostgreSQL.”\n\nThis is the abstract for the talk I’ve given at [FOSDEM](https://archive.fosdem.org/2015/schedule/event/modern_sql_in_postgresql/) in Brussels on Saturday. The PostgreSQL community was so kind to host this talk in their ([way too small](https://x.com/beschl/status/561858608619864064)) devroom—thus the references to PostgreSQL. However, the talk is build upon standard SQL and covers features that are commonly available in Db2 (LUW), Oracle, SQL Server and SQLite. MySQL does not yet support any of those features except [`OFFSET`, which is evil](/no-offset).\n\nOne last thing before going on to the slides: [*Use The Index, Luke* has a shop](/shop). Stickers, coasters, books, mugs. [Have a look](/shop).\n\nFind the [slides on SlideShare](https://www.slideshare.net/slideshow/modern-sql/44086611).\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2051, "slov": 291, "odkazu": 54, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:34", "sha256": "6ba2440adb911913076498d03fc7e827fc7cfae78cb16f2c65587c956b278b21", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://archive.fosdem.org/2015/schedule/event/modern_sql_in_postgresql/", "https://x.com/beschl/status/561858608619864064", "https://www.slideshare.net/slideshow/modern-sql/44086611", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2016-07-29/on-ubers-choice-of-databases", "titulek": "On Uber’s Choice of Databases", "h1": "On Uber’s Choice of Databases", "popis": "Uber provides bad advice about PostreSQL vs. MySQL", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2016-07-29/on-ubers-choice-of-databases", "jazyk": "en", "robots_meta": "", "og": {"og:title": "On Uber’s Choice of Databases", "og:description": "Uber provides bad advice about PostreSQL vs. MySQL", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "On Uber’s Choice of Databases"}, {"uroven": 4, "text": "Translations"}, {"uroven": 2, "text": "On UPDATE"}, {"uroven": 2, "text": "On SELECT"}, {"uroven": 2, "text": "On Index Rebalancing"}, {"uroven": 2, "text": "On Physical Replication"}, {"uroven": 2, "text": "On Developers"}, {"uroven": 2, "text": "On Success"}, {"uroven": 2, "text": "On Uber’s Choice of Databases"}, {"uroven": 4, "text": "Links"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# On Uber’s Choice of Databases\n\n---\n\n#### Translations\n\nA Japanese translation of this article is available [here](https://pgsqldeepdive.blogspot.com/2016/08/on-ubers-choice-of-databases-uber.html).\n\nA Chinese translation of this article is available [here](https://www.infoq.cn/article/the-database-selection-of-uber/).\n\nA few days ago Uber published the article “[Why Uber Engineering Switched from Postgres to MySQL](https://www.uber.com/blog/postgres-to-mysql-migration/)”. I didn’t read the article right away because my inner nerd told me to do some home improvements instead. While doing so my mailbox was filling up with questions like “Is PostgreSQL really that lousy?”. Knowing that PostgreSQL is not generally lousy, these messages made me wonder what the heck is written in this article. This post is an attempt to make sense out of Uber’s article.\n\nIn my opinion Uber’s article basically says that they found MySQL to be a better fit for *their environment* as PostgreSQL. However, the article does a lousy job to transport this message. Instead of writing “PostgreSQL has some limitations for `update`-heavy use-cases” the article just says “Inefficient architecture for writes,” for example. In case you don’t have an *update-heavy* use-case, don’t worry about the problems described in Uber’s article.\n\nIn this post I’ll explain why I think Uber’s article must not be taken as general advice about the choice of databases, why MySQL might still be a good fit for Uber, and why success might cause more problems than just scaling the data store.\n\n## On UPDATE\n\nThe first problem Uber’s article describes in great, yet incomplete detail is that PostgreSQL *always* needs to update *all indexes* on a table when *updating* rows in the table. MySQL with InnoDB, on the other hand, needs to update only those indexes that contain updated columns. The PostgreSQL approach causes more disk IOs for updates that change non-indexed columns (“Write Amplification” in the article). If this is such a big problem to Uber, these updates might be a big part of their overall workload.\n\nHowever, there is a little bit more speculation possible based upon something that is *not* written in Uber’s article: The article doesn’t mention PostgreSQL Heap-Only-Tuples (HOT). From the [PostgreSQL source](https://github.com/postgres/postgres/blob/master/src/backend/access/heap/README.HOT), HOT is useful for the special case “where a tuple is repeatedly updated in ways that do not change its indexed columns.” In that case, PostgreSQL is able to do the `update` without touching any index if the new row-version can be stored in the same page as the previous version. The latter condition can be tuned using the [fillfactor](https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-STORAGE-PARAMETERS) setting. Assuming Uber’s Engineering is aware of this means that HOT is no solution to their problem because the `updates` they run at high frequency affect at least one indexed column.\n\nThis assumption is also backed by the following sentence in the article: “if we have a table with a dozen indexes defined on it, an update to a field that is only covered by a single index must be propagated into all 12 indexes to reflect the `ctid` for the new row”. It explicitly says “only covered by a single index” which is the edge case—just one index—otherwise PostgreSQL’s HOT would solve the problem.\n\n*[Side note: I’m genuinely curious whether the number of indexes they have could be reduced—[index redesign](https://winand.at/sql-tuning/index-redesign) in my challenge. However, it is perfectly possible that those indexes are used sparingly, yet important when they are used.]*\n\nIt seems that they are running many updates that change at least one indexed column, but still relatively few indexed columns compared to the “dozen” indexes the table has. If this is a predominate use-case, the article’s argument to use MySQL over PostgreSQL makes sense.\n\n## On SELECT\n\nThere is one more statement about their use-case that caught my attention: the article explains that MySQL/InnoDB uses clustered indexes and also admits that “This design means that InnoDB is at a slight disadvantage to Postgres when doing a secondary key lookup, since two indexes must be searched with InnoDB compared to just one for Postgres.” I’ve previously written about this problem [(“the *clustered index penalty*”) in context of SQL Server](/blog/2014-01/unreasonable-defaults-primary-key-clustering-key).\n\nWhat caught my attention is that they describe the *clustered index penalty* as a “slight disadvantage”. In my opinion, it is a pretty big disadvantage if you run many queries that use secondary indexes. If it is only a slight disadvantage to them, it might suggest that those indexes are used rather seldom. That would mean, they are mostly searching by primary key (then there is no *clustered index penalty* to pay). Note that I wrote “searching” rather than “selecting”. The reason is that the *clustered index penalty* affects any statement that has a `where` clause—not just `select`. That also implies that the high frequency updates are mostly based on the primary key.\n\nFinally there is another omission that tells me something about their queries: they don’t mention PostgreSQL’s limited ability to do [index-only scans](https://wiki.postgresql.org/wiki/What%E2%80%99s_new_in_PostgreSQL_9.2#Index-only_scans). Especially in an update-heavy database, the PostgreSQL implementation of index-only scans is pretty much useless. I’d even say this is the single issue that affects most of my clients. I’ve already [blogged about this in 2011](/blog/2011-06-24/dear-database-vendors). In 2012, [PostgreSQL 9.2 got limited support of index-only scans](https://wiki.postgresql.org/wiki/What%27s_new_in_PostgreSQL_9.2#Index-only_scans) (works only for mostly static data). [In 2014 I even raised one aspect of my concern at PgCon](https://wiki.postgresql.org/wiki/Pgcon2014unconferenceBitmapIndexOnlyScan). However, Uber doesn’t complain about that. Select speed is not their problem. I guess query speed is generally solved by running the selects on the replicas (see below) and possibly limited by mostly doing primary key side.\n\nBy now, their use-case seems to be a better fit for a key/value store. And guess what: InnoDB is a pretty solid and popular key/value store. There are even packages that bundle InnoDB with some ([very limited](https://www.slideshare.net/slideshow/modern-sql/44086611)) SQL front-ends: MySQL and MariaDB are the most popular ones, I think. Excuse the sarcasm. But seriously: if you basically need a key/value store and occasionally want to run a simple SQL query, MySQL (or MariaDB) is a reasonable choice. I guess it is at least a better choice than any random NoSQL key/value store that just started offering an even more limited SQL-ish query language. Uber, on the other hand just builds their own thing (“[Schemaless](https://www.uber.com/blog/schemaless-part-one-mysql-datastore/)”) on top of InnoDB and MySQL.\n\n## On Index Rebalancing\n\nOne last note about how the article describes indexing: it uses the word “rebalancing” in context of B-tree indexes. It even links to a Wikipedia article on “[Rebalancing after deletion](https://en.wikipedia.org/wiki/B-tree#Rebalancing_after_deletion).” Unfortunately, the Wikipedia article doesn’t generally apply to database indexes because the algorithm described on Wikipedia maintains the requirement that each node has to be at least half-full. To improve concurrency, PostgreSQL uses the [Lehman, Yao variation of B-trees](https://www.csd.uoc.gr/~hy460/pdf/p650-lehman.pdf), which lifts this requirement and thus allows sparse indexes. As a side note, PostgreSQL still removes empty pages from the index (see [slide 15 of “Indexing Internals”](https://www.pgcon.org/2016/schedule/attachments/434_Index-internals-PGCon2016.pdf)). However, this is really just a side issue.\n\nWhat really worries me is this sentence: “An essential aspect of B-trees are that they must be periodically rebalanced, …” Here I’d like to clarify that this is not a periodic process one that runs every day. The index balance is maintained with every single index change (even worse, hmm?). But the article continues “…and these rebalancing operations can completely change the structure of the tree as sub-trees are moved to new on-disk locations.” If you now think that the “rebalancing” involves a lot of data moving, you misunderstood it.\n\nThe important operation in a B-tree is the *node split*. As you might guess, a node split takes place when a node cannot host a new entry that belongs into this node. To give you a ballpark figure, this might happen once for about 100 inserts. The node split allocates a new node, moves half of the entries to the new node and connects the new node to the previous, next and parent nodes. This is where Lehman, Yao save a lot of locking. In some cases, the new node cannot be added to the parent node straight away because the parent node doesn’t have enough space for the new child entry. In this case, the parent node is split and everything repeats.\n\nIn the worst case, the splitting bubbles up to the root node, which will then be split as well and a new root node will be put above it. Only in this case, a B-tree ever becomes deeper. Note that a root node split *effectively* shifts the whole tree down and therefore keeps the balance. However, this doesn’t involve a lot of data moving. In the worst case, it might touch three nodes on each level and the new root node. To be explicit: most real world indexes have no more than 5 levels. To be even more explicit: the worst case—root node split—might happen about five times for a billion inserts. On the other cases it will not need to go the whole tree up. After all, index maintenance is not “periodic”, not even very frequent, and is never completely changing the structure of the tree. At least not *physically on disk*.\n\n## On Physical Replication\n\nThat brings me to the next major concern the article raises about PostgreSQL: physical replication. The reason the article even touches the index “rebalancing” topic is that Uber once hit a PostgreSQL replication bug that caused data corruption on the downstream servers (the bug “only affected certain releases of Postgres 9.2 and has been fixed for a long time now”).\n\nBecause PostgreSQL 9.2 only offers physical replication in core, a replication bug “can cause large parts of the tree to become completely invalid.” To elaborate: if a node split is replicated incorrectly so that it doesn’t point to the right child nodes anymore, this sub-tree is invalid. This is absolutely true—like any other “if there is a bug, bad things happen” statement. You don’t need to change a lot of data to break a tree structure: a single bad pointer is enough.\n\nThe Uber article mentions other issues with physical replication: huge replication traffic—partly due to the write amplification caused by updates—and the downtime required to update to new PostgreSQL versions. While the first one makes sense to me, I really cannot comment on the second one (but there were some [statements on the PostgreSQL-hackers mailing list](https://www.postgresql.org/message-id/20160727002711.GI4028%40tamriel.snowman.net)).\n\nFinally, the article also claims that “Postgres does not have true replica MVCC support.” Luckily the article links to the PostgreSQL documentation where this problem (and remediations) are explained. The problem is basically that the master doesn’t know what the replicas are doing and might thus delete data that is still required on a replica to complete a query.\n\nAccording to the [PostgreSQL documentation](https://www.postgresql.org/docs/current/hot-standby.html#HOT-STANDBY-CONFLICT), there are two ways to cope with this issue: (1) delaying the application of the replication stream for a configurable timeout so the read transaction gets a chance to complete. If a query doesn’t finish in time, kill the query and continue applying the replication stream. (2) configure the replicas to send feedback to the master about the queries they are running so that the master does not vacuum row versions still needed by any slave. Uber’s article rules the first option out and doesn’t mention the second one at all. Instead the article blames the Uber developers.\n\n## On Developers\n\nTo quote it in all its glory: “For instance, say a developer has some code that has to email a receipt to a user. Depending on how it’s written, the code may implicitly have a database transaction that’s held open until after the email finishes sending. While it’s always bad form to let your code hold open database transactions while performing unrelated blocking I/O, the reality is that most engineers are not database experts and may not always understand this problem, especially when using an ORM that obscures low-level details like open transactions.”\n\nUnfortunately, I understand and even agree with this argument. Instead of “most engineers are not database experts” I’d even say that most developers have very little understanding of databases because every developer that touches SQL needs to know about transactions—not just database experts.\n\nGiving SQL training to developers is my main business. I do it at companies of all sizes. If there is one thing I can say for sure is that the knowledge about SQL is ridiculously low. In context of the “open transaction” problem just mentioned I can conform that hardly any developer even knows that read only transactions are a real thing. Most developers just know that transactions can be used to back out writes. I’ve encountered this misunderstanding often enough that I’ve prepared slides to explain it and I just [uploaded these slides for the curious reader](https://www.slideshare.net/slideshow/sql-transactions-what-they-are-good-for-and-how-they-work/64488618).\n\n## On Success\n\nThis leads me to the last problem I’d like to write about: the more people a company hires, the closer their qualification will be to the average. To exaggerate, if you hire the whole planet, you’ll have the exact average. Hiring more people really just increases the sample size.\n\nThe two ways to beat the odds are: (1) Only hire the best. The difficult part with this approach is to wait if no above-average candidates are available; (2) Hire the average and train them on the job. This needs a pretty long warm-up period for the new staff and might also bind existing staff for the training. The problem with both approaches is that they take time. If you don’t have time—because your business is rapidly growing—you have to take the average, which doesn’t know a lot about databases ([empirical data from 2014](/blog/2014-02/results-three-minutes-sql-performance-quiz)). In other words: for a rapidly growing company, technology is easier to change than people.\n\nThe success factor also affects the technology stack as requirements change over time. At an early stage, start-ups need out-of-the-box technology that is immediately available and flexible enough to be used for their business. SQL is a good choice here because it is actually flexible (you can query your data in any way) and it is easy to find people knowing SQL at least a little bit. Great, let’s get started! And for many—probably most—companies, the story ends here. Even if they become moderately successful and their business grows, they might still stay well within the limits of SQL databases forever. Not so for Uber.\n\nA few lucky start-ups eventually outgrow SQL. By the time that happens, they have access to way more (virtually unlimited?) resources and then…something wonderful happens: They realize that they can solve many problems if they replace their general purpose database by a system they develop just for their very own use-case. This is the moment a new NoSQL database is born. At Uber, they call it [Schemaless](https://www.uber.com/blog/schemaless-part-one-mysql-datastore/).\n\n## On Uber’s Choice of Databases\n\nBy now, I believe Uber did not replace PostgreSQL by MySQL as their article suggests. It seems that they actually replaced PostgreSQL by their tailor-made solution, which happens to be backed by MySQL/InnoDB (at the moment).\n\nIt seems that the article just explains why MySQL/InnoDB is a better backend for Schemaless than PostgreSQL. For those of you using Schemaless, take their advice! Unfortunately, the article doesn’t make this very clear because it doesn’t mention how their requirements changed with the introduction of Schemaless compared to [2013, when they migrated from MySQL to PostgreSQL](https://www.yumpu.com/en/document/view/53683323/migrating-uber-from-mysql-to-postgresql).\n\nSadly, the only thing that sticks in the reader’s mind is that PostgreSQL is lousy.\n\n#### Links\n\n- Uber’s recent (2016) article [Why Uber Engineering Switched from Postgres to MySQL](https://www.uber.com/blog/postgres-to-mysql-migration/)\n- Discussions on [Hacker News](https://news.ycombinator.com/item?id=12166585), [Reddit](https://www.reddit.com/r/programming/comments/4uph84/why_uber_engineering_switched_from_postgres_to/), and the [PostgreSQL-hackers mailing list](https://www.postgresql.org/message-id/579795DF.10502%40commandprompt.com).\n- Uber’s 2013 article [Migrating Uber from MySQL to PostgreSQL](https://www.yumpu.com/en/document/view/53683323/migrating-uber-from-mysql-to-postgresql) (same author)\n- [Video where Uber also touches the data corruption issue they had](https://vimeo.com/145842299)\n- [Results of the SQL Performance Quiz: 60% fail](/blog/2014-02/results-three-minutes-sql-performance-quiz)\n- Slides [Transactions: What they are good for and how they work](https://www.slideshare.net/slideshow/sql-transactions-what-they-are-good-for-and-how-they-work/64488618)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-â� sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 18595, "slov": 2809, "odkazu": 75, "kodovani": "windows-1250", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:35", "sha256": "b13e76e231473ee212a13e8d045b4721b31f5658fbb5d90686de44fd8654f655", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://pgsqldeepdive.blogspot.com/2016/08/on-ubers-choice-of-databases-uber.html", "https://www.infoq.cn/article/the-database-selection-of-uber/", "https://www.uber.com/blog/postgres-to-mysql-migration/", "https://github.com/postgres/postgres/blob/master/src/backend/access/heap/README.HOT", "https://www.postgresql.org/docs/current/sql-createtable.html", "https://winand.at/sql-tuning/index-redesign", "https://wiki.postgresql.org/wiki/What%E2%80%99s_new_in_PostgreSQL_9.2", "https://wiki.postgresql.org/wiki/What's_new_in_PostgreSQL_9.2", "https://wiki.postgresql.org/wiki/Pgcon2014unconferenceBitmapIndexOnlyScan", "https://www.slideshare.net/slideshow/modern-sql/44086611", "https://www.uber.com/blog/schemaless-part-one-mysql-datastore/", "https://en.wikipedia.org/wiki/B-tree", "https://www.csd.uoc.gr/~hy460/pdf/p650-lehman.pdf", "https://www.pgcon.org/2016/schedule/attachments/434_Index-internals-PGCon2016.pdf", "https://www.postgresql.org/message-id/20160727002711.GI4028@tamriel.snowman.net", "https://www.postgresql.org/docs/current/hot-standby.html", "https://www.slideshare.net/slideshow/sql-transactions-what-they-are-good-for-and-how-they-work/64488618", "https://www.yumpu.com/en/document/view/53683323/migrating-uber-from-mysql-to-postgresql", "https://news.ycombinator.com/item?id=12166585", "https://www.reddit.com/r/programming/comments/4uph84/why_uber_engineering_switched_from_postgres_to/", "https://www.postgresql.org/message-id/579795DF.10502@commandprompt.com", "https://vimeo.com/145842299", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2016-11/big-news-in-databases", "titulek": "Big News In Databases: Fall 2016", "h1": "Big News In Databases", "popis": "MySQL and MariaDB become modern, Parallel PostgreSQL, SQL Server running on Linux, Oracle as cloud-only database, OFFSET in DB2 and row-values in SQLite.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2016-11/big-news-in-databases", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Big News In Databases: Fall 2016", "og:description": "MySQL and MariaDB become modern, Parallel PostgreSQL, SQL Server running on Linux, Oracle as cloud-only database, OFFSET in DB2 and row-values in SQLite.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Big News In Databases"}, {"uroven": 2, "text": "MySQL and MariaDB Become Modern"}, {"uroven": 2, "text": "Parallel Execution in PostgreSQL 9.6"}, {"uroven": 2, "text": "SQL Server on Linux (Beta)"}, {"uroven": 2, "text": "Oracle 12cR2 Currently Cloud Only"}, {"uroven": 2, "text": "DB2 Learns OFFSET…Unfortunately"}, {"uroven": 2, "text": "SQLite Gets Row-Values"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Big News In Databases\n\n---\n\nThere’s been a lot of big news in 2016, also when it comes to databases. Let’s have a look at the really BIG news.\n\n## MySQL and MariaDB Become Modern\n\nFor a long time, MySQL and MariaDB were mostly limited to the functionality of SQL-92. Now, both of them have decided to move forward by supporting the `[`WITH`](https://modern-sql.com/feature/with)` and `OVER` clauses in their next major release (MySQL 8.0, MariaDB 10.2). The [MariaDB beta release](https://mariadb.org/mariadb/all-releases/) already supports both features while the current [MySQL “lab release”](https://labs.mysql.com/) only currently supports the [`WITH`](https://modern-sql.com/feature/with) clause.\n\n## Parallel Execution in PostgreSQL 9.6\n\nCommercial databases have been able to do it for decades, but in the open source database scene it is quite unique: Since [release 9.6, PostgeSQL](https://www.postgresql.org/docs/9.6/release-9-6.html) can execute single queries on multiple cores and thus make better use of modern hardware for data-intensive queries. At the moment, only some special cases can take advantage of in-query parallelism. The next releases will gradually extend this functionality. Speaking of next releases: The next major PostgreSQL release will be 10.\n\n## SQL Server on Linux (Beta)\n\nA beta of the next version of SQL Server (currently called “vNext”) was released, [also for Linux](https://web.archive.org/web/20161122081353/https://www.microsoft.com/en-us/sql-server/sql-server-vnext-including-Linux). On supported distributions (Red Hat, Ubuntu) the installation is carried out by the regular package manager. Furthermore, Microsoft provides Docker images. The “[What’s New](https://learn.microsoft.com/en-us/sql/sql-server/what-s-new-in-sql-server-2017)” list of vNext is rather modest from a developer’s perspective. However, SQL Server is finally getting `STRING_AGG`. It’s also worth noting that `CREATE OR ALTER` was added to SQL Server 2016 SP1, which was released at the same time that vNext beta went public.\n\n## Oracle 12cR2 Currently Cloud Only\n\nFirst off, Version 12.2 of the Oracle Database hast already been released. Interestingly, you cannot download it. [Cloud first](https://www.crn.com/news/cloud/300081139/oracle-confirms-12-2-database-release-will-be-cloud-only-at-first-analyst-predicts-move-will-frustrate-customers) seems to be the new strategy for Oracle. For developers the new release is not very exciting anyway: Error handling for `CASE` and `LISTAGG`, approximate aggregates and of course more JSON. Find the full list in the “[New Features](https://docs.oracle.com/en/database/oracle/oracle-database/12.2/newft/index.html)” documentation.\n\n## DB2 Learns `OFFSET`…Unfortunately\n\nDB2 for Linux, UNIX and Windows (abbrevated LUW) has gotten [release 11.1](https://www.ibm.com/docs/en/db2/11.1.0?topic=database-whats-new-db2-version-111-ga) earlier this year. The general theme of the new SQL features was compatibility. It seems like IBM aims to support every single SQL dialect out there, and one part of this is that DB2 supports the SQL:2011 `OFFSET` clause even without enabling the MySQL compatibility vector. This is a big setback from my [No-Offset movement](/no-offset)!\n\n## SQLite Gets Row-Values\n\nSQLite is compensating for this by introducing [row values](https://www.sqlite.org/rowvalue.html) support in version 3.15.0—the SQL-92 feature that often makes [life without `OFFSET`](/no-offset) more easy. If you don’t know about No-Offset yet, you should definitively read [this article](/no-offset).\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 4175, "slov": 577, "odkazu": 62, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:36", "sha256": "b166dd05976fddedda6d490804ea6c701e283789b7df3686cbc5d2947d4e8a43", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://modern-sql.com/feature/with", "https://mariadb.org/mariadb/all-releases/", "https://labs.mysql.com/", "https://www.postgresql.org/docs/9.6/release-9-6.html", "https://www.microsoft.com/en-us/sql-server/sql-server-vnext-including-Linux", "https://learn.microsoft.com/en-us/sql/sql-server/what-s-new-in-sql-server-2017", "https://www.crn.com/news/cloud/300081139/oracle-confirms-12-2-database-release-will-be-cloud-only-at-first-analyst-predicts-move-will-frustrate-customers", "https://docs.oracle.com/en/database/oracle/oracle-database/12.2/newft/index.html", "https://www.ibm.com/docs/en/db2/11.1.0?topic=database-whats-new-db2-version-111-ga", "https://www.sqlite.org/rowvalue.html", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2017-05/new-sql-standard-oracle-122-acidrain", "titulek": "Big News In Databases: new SQL standard, cloud wars, ACIDRain (Spring 2017)", "h1": "Big News In Databases — Spring 2017", "popis": "New SQL standard released, SQL Server is the database of the year 2016, Oracle’s questionable cloud strategy, and security issues caused by wrong transaction use.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2017-05/new-sql-standard-oracle-122-acidrain", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Big News In Databases: new SQL standard, cloud wars, ACIDRain (Spring 2017)", "og:description": "New SQL standard released, SQL Server is the database of the year 2016, Oracle’s questionable cloud strategy, and security issues caused by wrong transaction use.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Big News In Databases — Spring 2017"}, {"uroven": 2, "text": "A new SQL standard was released (SQL:2016)"}, {"uroven": 2, "text": "Oracle Database 12.2 on premises, cloud prices double for AWS and Azure"}, {"uroven": 2, "text": "Database of the year"}, {"uroven": 2, "text": "ACIDRain: Study highlights security risk of wrong transaction use"}, {"uroven": 2, "text": "From my Twitter timeline"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Big News In Databases — Spring 2017\n\n---\n\nHere is the most noteworthy news since [my last “Big News In Databases” post from November 2016](/blog/2016-11/big-news-in-databases).\n\n## A new SQL standard was released (SQL:2016)\n\nIn December 2016, ISO released a new version of the SQL standard. It introduces new features such as row pattern matching, `listagg`, date and time formatting, and JSON support. I’ve already written about `[listagg](https://modern-sql.com/feature/listagg)` and made a [presentation about row pattern matching](https://modern-sql.com/feature/match_recognize).\n\n[Subscribe the modern-sql.com blog](https://winand.at/lists) for further updates on the new standard.\n\n## Oracle Database 12.2 on premises, cloud prices double for AWS and Azure\n\nOracle’s cloud strategy was already topic in my [previous post](/blog/2016-11/big-news-in-databases): Although the latest database release 12.2 was in November 2016, it was not available for download at that time—it was only available as a service in the Oracle cloud.\n\nIn January 2017, [Oracle effectively doubled the license cost for the Oracle databases in Amazon’s and Microsoft’s cloud environments](https://oracle-base.com/blog/2017/01/28/oracles-cloud-licensing-change-be-warned/). And how does Microsoft react? On May 10, [Microsoft announced the availability of MySQL and PostgreSQL as managed services in the Azure cloud](https://techcrunch.com/2017/05/10/microsoft-launches-azure-database-for-mysql-and-postgressql/).\n\n[Begun the cloud war has](https://www.youtube.com/watch?v=g6aD-m7Cw84). One party opens up, another isolates itself. The marked leader watches.\n\nIn light of these developments, the release of the Oracle database 12.2 [download](https://www.oracle.com/database/technologies/oracle-database-software-downloads.html) in March is just a side note.\n\n## Database of the year\n\nIn January, [DB-Engines.com (“TIOBE of databases”) published their database of the year 2016](https://db-engines.com/en/blog_post/67). According to [their ranking method](https://db-engines.com/en/ranking_definition), SQL Server had the greatest gains in 2016 and is thus the database of the year 2016. Second and third place went to MySQL and PostgreSQL.\n\nAn interesting side note from their announcement: “It is the first time we see three RDBMS winning that competition, in the past we had at least two NoSQL systems among the winners.”\n\n## ACIDRain: Study highlights security risk of wrong transaction use\n\nOne of the consequences of database normalization is that transactions are needed to work safely. SQL has had transactions for a long time. The latest change in this area was the introduction of transaction isolation levels—25 years ago.\n\nA [new study](https://www.bailis.org/papers/acidrain-sigmod2017.pdf) recently analyzed how transactions are used in “12 popular self-hosted eCommerce applications written in four languages and deployed on over 2M websites.” The study found that 11 of them make incorrect use of transactions and “allow attackers to corrupt store inventory, over-spend gift cards, and steal inventory.”\n\nThe relevance of this thread (coined *ACIDRain attack*) is on the rise as more and more applications expose functionality via APIs that can be used to programmatically exploit concurrency related vulnerabilities.\n\n## From my [Twitter timeline](https://x.com/MarkusWinand)\n\n- [Recording of my webinar “Shaping the Oracle Optimizers Search Space”](https://vimeo.com/195884916).\n- I blogged: [`with` clause: performance impacts](https://modern-sql.com/feature/with/performance).\n- [Recording of my “Modern SQL” presentation at Voxxed Days Bucharest.](https://www.youtube.com/watch?v=_3KVYtUAEC0)\n- [I’ve done a conformance test with MySQL 8.0.1. Seems like MySQL is getting the best WITH support of all tested DBs (RECURSIVE not tested!)](https://x.com/MarkusWinand/status/852862475699707904) [Bill Karwin used this result in his Percona Live presentation “Recursive Query Throwdown in MySQL 8”](https://www.slideshare.net/slideshow/recursive-query-throwdown/75838632)\n- A client migrated from MySQL to PostgreSQL and [wrote about it](https://web.archive.org/web/20181122212934/https://garage.socialisten.at/2017/04/how-swat-io-migrated-from-mysql-to-postgresql-in-2-years/)\n- [SQL is 43 years old - here’s 8 reasons we still use it today](https://web.archive.org/web/20250917024119/https://blog.sqlizer.io/posts/sql-43/)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 5026, "slov": 645, "odkazu": 68, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:37", "sha256": "b61f05a3b108e7713b5154134af2462892f082b1f910df98311cf5a731666ac5", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://modern-sql.com/feature/listagg", "https://modern-sql.com/feature/match_recognize", "https://winand.at/lists", "https://oracle-base.com/blog/2017/01/28/oracles-cloud-licensing-change-be-warned/", "https://techcrunch.com/2017/05/10/microsoft-launches-azure-database-for-mysql-and-postgressql/", "https://www.youtube.com/watch?v=g6aD-m7Cw84", "https://www.oracle.com/database/technologies/oracle-database-software-downloads.html", "https://db-engines.com/en/blog_post/67", "https://db-engines.com/en/ranking_definition", "https://www.bailis.org/papers/acidrain-sigmod2017.pdf", "https://x.com/MarkusWinand", "https://vimeo.com/195884916", "https://modern-sql.com/feature/with/performance", "https://www.youtube.com/watch?v=_3KVYtUAEC0", "https://x.com/MarkusWinand/status/852862475699707904", "https://www.slideshare.net/slideshow/recursive-query-throwdown/75838632", "https://garage.socialisten.at/2017/04/how-swat-io-migrated-from-mysql-to-postgresql-in-2-years/", "https://blog.sqlizer.io/posts/sql-43/", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2017-11/cloud-wars-ibm-db2-renaming-major-database-releases", "titulek": "Big News In Databases: Cloud Wars, IBM’s Renaming Insanity, Three Major Releases", "h1": "Big News In Databases — Fall 2017", "popis": "Google embraces SQL, SQL Server price reduction on AWS, IBM renames their database, SQL Server 2017 and PostgreSQL 10 released", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2017-11/cloud-wars-ibm-db2-renaming-major-database-releases", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Big News In Databases: Cloud Wars, IBM’s Renaming Insanity, Three Major Releases", "og:description": "Google embraces SQL, SQL Server price reduction on AWS, IBM renames their database, SQL Server 2017 and PostgreSQL 10 released", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Big News In Databases — Fall 2017"}, {"uroven": 2, "text": "SQL on The Rise"}, {"uroven": 2, "text": "The Cloud War Continues"}, {"uroven": 2, "text": "IBM’s Renaming Insanity"}, {"uroven": 3, "text": "Other Vendors Rethink Release Numbering"}, {"uroven": 2, "text": "New Database Releases"}, {"uroven": 2, "text": "News on my Sites"}, {"uroven": 2, "text": "From Twitter, in Great Brevity (follow me on Twitter)"}, {"uroven": 2, "text": "About the Author"}, {"uroven": 2, "text": "Footnotes"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Big News In Databases — Fall 2017\n\n---\n\nDon’t fall behind: Here’s the most important database news from the last six months.\n\n## SQL on The Rise\n\nNoSQL pioneer Google writes that their [Spanner database is becoming a SQL system](https://dl.acm.org/doi/10.1145/3035918.3056103) ([summary](https://blog.acolyer.org/2017/07/03/spanner-becoming-a-sql-system/)). [Salesforce uses Artificial Intelligence to translate natural language to SQL](https://techcrunch.com/2017/08/29/salesforce-is-using-ai-to-democratize-sql-so-anyone-can-query-databases-in-natural-language/). [Even some ORM](https://korban.net/posts/postgres/2017-11-02-the-case-against-orms/)0[vendors say it is better to use SQL](https://korban.net/posts/postgres/2017-11-02-the-case-against-orms/). Seems like SQL has a positive vibe.\n\nThe highly popular article “[Why SQL is beating NoSQL, and what this means for the future of data](https://www.tigerdata.com/blog/why-sql-beating-nosql-what-this-means-for-future-of-data-time-series-database-348b777b847a)” is a very nice write-up of why SQL had become frowned upon, and how it is now gaining new popularity right.\n\n## The Cloud War Continues\n\nIn the [previous edition](/blog/2017-05/new-sql-standard-oracle-122-acidrain), I reported about the [sudden **spike** in license costs for the Oracle database in Amazon’s AWS and Microsoft’s Azure cloud environments](/blog/2017-05/new-sql-standard-oracle-122-acidrain#oracle-122).\n\nIn July the opposite happened for users of Microsoft SQL Server: the cost of running [the Standard Edition in Amazon’s AWS cloud was **reduced** by between 29 and 52 percent](https://aws.amazon.com/blogs/aws/aws-price-reduction-sql-server-standard-edition-on-ec2/?nc1=f_ls).\n\n## IBM’s Renaming Insanity\n\nThere is a [saying](https://www.martinfowler.com/bliki/TwoHardThings.html) that there are only two hard things in computer science: (0) [cache invalidation](https://en.wikipedia.org/wiki/Cache_invalidation), (1) [naming things](https://www.mediawiki.org/wiki/Naming_things), (2) and [off-by-one errors](https://en.wikipedia.org/wiki/Off-by-one_error). In June, IBM [renamed the products in the *Db2* family](https://datageek.blog/2017/06/23/ibms-june-announcements-about-db2/) and thereby demonstrated how to cause great harm by choosing poor names.\n\n| Old Name | New Name |\n| --- | --- |\n| DB2 for LUW | Db2 |\n| DB2 for z/OS | Db2 for z/OS |\n| DB2 for iSeries | Db2 for i |\n\nNote the subtle but groundbreaking innovation to write the “b” in *Db2* as a lower case letter.\n\nAll sarcasm aside: Previously, *DB2* was a common element in the names of different products of the same family. The “for” addendum made a distinction between each product. As these products offer different features,1 the distinction is quite important.\n\nThe new name *Db2* doesn’t allow this distinction anymore because it represents the whole family as well as one specific product. This lack of differentiation becomes a real problem when searching the internet: webpages about the former product *DB2 for LUW* might not contain “*LUW*” anymore. Reducing the *iSeries* addendum to *i* doesn’t improve searching either.\n\nWikipedia says “[A name is a term used for identification.](https://en.wikipedia.org/wiki/Name)” I doubt the new names fulfill this purpose sufficiently.\n\nOne thing is for sure: the new naming is an upgrade for the LUW version. The reverse of this conclusion shines an interesting light on the other variants. IBM also looses grounds in the just published [**Gartner Magic Quadrant for Operational Databases 2017**](https://www.gartner.com/doc/reprints?id=1-3JD7HF0&ct=161005&st=sb)—it’s now far behind SAP and Amazon Web Services (AWS).\n\n### Other Vendors Rethink Release Numbering\n\n[I have already mentioned that the next MySQL major release after 5.7 will be **MySQL 8.0**](/blog/2017-05/new-sql-standard-oracle-122-acidrain). In the meantime, a [release candidate is available](https://dev.mysql.com/downloads/mysql/).\n\nThe next major release of the **Oracle Database will be 18c** (instead of 12.2.0.2). [New releases will be annual and the version will be the last two digits of the release year](https://mikedietrichde.com/2017/08/09/news-new-oracle-database-release-schedule/) (see also: [**release roadmap**](https://oracle-help.com/articles/naming-convention-oracle-18c/)).\n\nStarting with the just released **PostgreSQL 10**, there is [**no dot** in the major versions of PostgreSQL](https://www.postgresql.org/about/news/postgresql-10-released-1786/) anymore.\n\n## New Database Releases\n\nIn the past six month there were three major releases among the most popular SQL databases.\n\nSQL Server 2017 (October 2017)\n\nMy personal picks from the [“new features” list](https://learn.microsoft.com/en-us/sql/sql-server/what-s-new-in-sql-server-2017):[It’s](https://learn.microsoft.com/en-us/sql/linux/sql-server-linux-overview)**[available on Linux](https://learn.microsoft.com/en-us/sql/linux/sql-server-linux-overview)**. [Free for developing](https://learn.microsoft.com/en-us/sql/sql-server/editions-and-components-of-sql-server-2017), [including Docker images](https://learn.microsoft.com/en-us/sql/linux/install-upgrade/quickstart-install-docker). **Licenses are** “[**platform agnostic**, so customers can run the software on either Windows or Linux.](https://download.microsoft.com/download/B/C/0/BC0B2EA7-D99D-42FB-9439-2C56880CAFF4/SQL_Server_2017_Licensing_Datasheet.pdf)”[Batch mode **adaptive joins**](https://learn.microsoft.com/en-us/sql/relational-databases/performance/intelligent-query-processing): decide to use nested loops or hash join during execution (like [Oracle’s adaptive joins](https://blogs.oracle.com/optimizer/optimizer-adaptive-features-in-oracle-database-12c-release-2), but more limited2).[Graph processing capabilities](https://learn.microsoft.com/en-us/sql/relational-databases/graphs/sql-graph-overview): a **`match` clause** that reminds one of the [Cypher Query Language](https://en.wikipedia.org/wiki/Cypher_Query_Language).The [`string_agg` function](https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql): similar to the [standard function `listagg`](https://modern-sql.com/feature/listagg), but without `on overflow` clause.\n\nPostgreSQL 10 (October 2017)\n\nMy favorite [new features](https://www.postgresql.org/docs/10/release-10.html):[**Parallel query** improvements](https://wiki.postgresql.org/wiki/New_in_postgres_10#Additional_Parallelism_in_Query_Execution): Merge Join, Bitmap Heap Scan, Index [Only] Scan, and more.[Multi-column optimizer statistics](https://www.postgresql.org/docs/10/sql-createstatistics.html), so the optimizer understands cross column correlations.[ICU collations](https://www.enterprisedb.com/blog/more-robust-collations-icu-support-postgresql-10): operating system independent rules for comparing character strings.\n\nMariaDB 10.2 (May 2017)\n\n[MariaDB](https://mariadb.com/docs/release-notes/community-server/old-releases/10.2/what-is-mariadb-102)3[10.2](https://mariadb.com/docs/release-notes/community-server/old-releases/10.2/what-is-mariadb-102) introduces two very important features that will also appear in MySQL 8.0:[**Window functions**](https://mariadb.com/docs/server/reference/sql-functions/special-functions/window-functions): the `over` clause.The [**`with` clause**](https://mariadb.com/docs/server/reference/sql-statements/data-manipulation/selecting-data/common-table-expressions/with): both, recursive and [non-recursive](https://modern-sql.com/feature/with) variants.\n\n## News on my Sites\n\nArticles I published or updated:\n\n- I updated the PDF edition of “[**SQL Performance Explained**](https://sql-performance-explained.com/l?utm_source=use-the-index-luke.com&utm_campaign=blog-201711-big-news&utm_medium=web&utm_content=news-on-my-sites)” (all languages). If you bought it in the past, now is a good time to [**re-download it**](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-201711-big-news&utm_medium=web&utm_content=news-on-my-sites#request-download). (If not, [**you can buy it here**](https://sql-performance-explained.com/l?utm_source=use-the-index-luke.com&utm_campaign=blog-201711-big-news&utm_medium=web&utm_content=news-on-my-sites) ;)\n- [I’ve updated the **3 minute SQL indexing quiz**: Can you spot the five most common SQL indexing mistakes?](/3-minute-quiz)\n- New article: [`extract` — Get a Field from a Date or Time Value](https://modern-sql.com/feature/extract)\n- New article: [What’s New in SQL:2016](https://modern-sql.com/blog/2017-06/whats-new-in-sql-2016)\n\n## From Twitter, in Great Brevity ([follow me on Twitter](https://x.com/MarkusWinand))\n\n- [The next Oracle Database Express Edition will be 18c XE. Limits: 12GB storage, 2GB RAM](https://x.com/ChrisRSaxon/status/915225979290763264) For comparison, [IBM Db2 Express-C](https://www.ibm.com/us-en/marketplace/db2-express-c) has no storage limit, 16GB RAM, and 2 cores. [Addendum for the trolls](https://x.com/MarkusWinand/status/925028128849788928): Yes, the free open source databases such as PostgreSQL and MySQL have no limits for the same price.\n- [What do SQL statements really mean, and how can we prove RDBMS query rewrites are safe? Until now, we couldn’t…](https://blog.acolyer.org/2017/10/05/hottsql-proving-query-rewrites-with-univalent-sql-semantics/)\n- [10 Cool SQL Optimisations That do not Depend on the Cost Model](https://blog.jooq.org/10-cool-sql-optimisations-that-do-not-depend-on-the-cost-model/)\n- TIL: Although SQLite’s default collation is case-sensitive, it doesn’t affect LIKE. [LIKE’s case-sensitivity is controlled by a PRAGMA instead](https://sqlite.org/pragma.html#pragma_case_sensitive_like)\n- [SQL Island — text adventure game to learn SQL](https://sql-island.informatik.uni-kl.de/)\n- [Explaining isolation levels based on the states that are observable by a client application](https://blog.acolyer.org/2017/08/29/seeing-is-believing-a-client-centric-specification-of-database-isolation/)\n- [How Postgres Makes Transactions Atomic](https://brandur.org/postgres-atomicity)\n- [“ACIDRain: concurrency-related attacks on database-backed web applications” Warszawski & Bailis ’17](https://blog.acolyer.org/2017/08/07/acidrain-concurrency-related-attacks-on-database-backed-web-applications/)\n- [Practical Guide to SQL Transaction Isolation … a really good one.](https://begriffs.com/posts/2017-08-01-practical-guide-sql-isolation.html)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).\n\n## Footnotes\n\n1. 0 [Object-relational mapping](https://en.wikipedia.org/wiki/Object-relational_mapping) tools such as [Sequel](https://github.com/jeremyevans/sequel) (mentioned in the article), Hibernate, Doctrine, …\n2. 1 IBM itself publishes “[The SQL reference for cross-platform development](https://www.ibm.com/support/pages/sql-reference-cross-platform-development-0)” to document the common SQL functionality for developers.\n3. 2 The main limitation is the “batch mode” which is mostly used for queries accessing column store indexes. See “[What You Need to Know about the Batch Mode Window Aggregate Operator in SQL Server 2016: Part 1](https://web.archive.org/web/20240814201331/https://www.itprotoday.com/innovations-of-the-2010s/what-you-need-to-know-about-the-batch-mode-window-aggregate-operator-in-sql-server-2016-part-1)” for a good intro.\n4. 3 MariaDB is the MySQL clone continued by the original creator of MySQL after Oracle indirectly acquired MySQL through Sun in 2009.", "znaku_textu": 11908, "slov": 1421, "odkazu": 112, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:37", "sha256": "c28c2e7f78459557e7569818800282a6b516d52d0cbb8c32beb25fecf478f81a", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://dl.acm.org/doi/10.1145/3035918.3056103", "https://blog.acolyer.org/2017/07/03/spanner-becoming-a-sql-system/", "https://techcrunch.com/2017/08/29/salesforce-is-using-ai-to-democratize-sql-so-anyone-can-query-databases-in-natural-language/", "https://korban.net/posts/postgres/2017-11-02-the-case-against-orms/", "https://www.tigerdata.com/blog/why-sql-beating-nosql-what-this-means-for-future-of-data-time-series-database-348b777b847a", "https://aws.amazon.com/blogs/aws/aws-price-reduction-sql-server-standard-edition-on-ec2/?nc1=f_ls", "https://www.martinfowler.com/bliki/TwoHardThings.html", "https://en.wikipedia.org/wiki/Cache_invalidation", "https://www.mediawiki.org/wiki/Naming_things", "https://en.wikipedia.org/wiki/Off-by-one_error", "https://datageek.blog/2017/06/23/ibms-june-announcements-about-db2/", "https://en.wikipedia.org/wiki/Name", "https://www.gartner.com/doc/reprints?ct=161005&id=1-3JD7HF0&st=sb", "https://dev.mysql.com/downloads/mysql/", "https://mikedietrichde.com/2017/08/09/news-new-oracle-database-release-schedule/", "https://oracle-help.com/articles/naming-convention-oracle-18c/", "https://www.postgresql.org/about/news/postgresql-10-released-1786/", "https://learn.microsoft.com/en-us/sql/sql-server/what-s-new-in-sql-server-2017", "https://learn.microsoft.com/en-us/sql/linux/sql-server-linux-overview", "https://learn.microsoft.com/en-us/sql/sql-server/editions-and-components-of-sql-server-2017", "https://learn.microsoft.com/en-us/sql/linux/install-upgrade/quickstart-install-docker", "https://download.microsoft.com/download/B/C/0/BC0B2EA7-D99D-42FB-9439-2C56880CAFF4/SQL_Server_2017_Licensing_Datasheet.pdf", "https://learn.microsoft.com/en-us/sql/relational-databases/performance/intelligent-query-processing", "https://blogs.oracle.com/optimizer/optimizer-adaptive-features-in-oracle-database-12c-release-2", "https://learn.microsoft.com/en-us/sql/relational-databases/graphs/sql-graph-overview", "https://en.wikipedia.org/wiki/Cypher_Query_Language", "https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql", "https://modern-sql.com/feature/listagg", "https://www.postgresql.org/docs/10/release-10.html", "https://wiki.postgresql.org/wiki/New_in_postgres_10", "https://www.postgresql.org/docs/10/sql-createstatistics.html", "https://www.enterprisedb.com/blog/more-robust-collations-icu-support-postgresql-10", "https://mariadb.com/docs/release-notes/community-server/old-releases/10.2/what-is-mariadb-102", "https://mariadb.com/docs/server/reference/sql-functions/special-functions/window-functions", "https://mariadb.com/docs/server/reference/sql-statements/data-manipulation/selecting-data/common-table-expressions/with", "https://modern-sql.com/feature/with", "https://sql-performance-explained.com/l", "https://sql-performance-explained.com/", "https://modern-sql.com/feature/extract", "https://modern-sql.com/blog/2017-06/whats-new-in-sql-2016", "https://x.com/MarkusWinand", "https://x.com/ChrisRSaxon/status/915225979290763264", "https://www.ibm.com/us-en/marketplace/db2-express-c", "https://x.com/MarkusWinand/status/925028128849788928", "https://blog.acolyer.org/2017/10/05/hottsql-proving-query-rewrites-with-univalent-sql-semantics/", "https://blog.jooq.org/10-cool-sql-optimisations-that-do-not-depend-on-the-cost-model/", "https://sqlite.org/pragma.html", "https://sql-island.informatik.uni-kl.de/", "https://blog.acolyer.org/2017/08/29/seeing-is-believing-a-client-centric-specification-of-database-isolation/", "https://brandur.org/postgres-atomicity", "https://blog.acolyer.org/2017/08/07/acidrain-concurrency-related-attacks-on-database-backed-web-applications/", "https://begriffs.com/posts/2017-08-01-practical-guide-sql-isolation.html", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://en.wikipedia.org/wiki/Object-relational_mapping", "https://github.com/jeremyevans/sequel", "https://www.ibm.com/support/pages/sql-reference-cross-platform-development-0", "https://www.itprotoday.com/innovations-of-the-2010s/what-you-need-to-know-about-the-batch-mode-window-aggregate-operator-in-sql-server-2016-part-1", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2017-11/spanish-anyone", "titulek": "Spanish Translation and Other News", "h1": "Spanish Anyone?", "popis": "“Use The Index, Luke!” and “SQL Performance Explained” have been translated into Spanish.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2017-11/spanish-anyone", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Spanish Translation and Other News", "og:description": "“Use The Index, Luke!” and “SQL Performance Explained” have been translated into Spanish.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Spanish Anyone?"}, {"uroven": 2, "text": "A BIG THANK YOU"}, {"uroven": 2, "text": "Also Updated: The 3-Minute Quiz!"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Spanish Anyone?\n\n---\n\nThe Spanish translation of my book [*SQL Performance Explained*](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-201711-spanish&utm_medium=web) has just been published. It’s the fifth language so far … now there’s a [German](https://sql-performance-explained.de?utm_source=use-the-index-luke.com&utm_campaign=blog-201711-spanish&utm_medium=web), [English](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-201711-spanish&utm_medium=web), [French](https://sql-au-coeur-des-performances.fr/?utm_source=use-the-index-luke.com&utm_campaign=blog-201711-spanish&utm_medium=web), [Japanese](https://sql-performance-explained.jp/?utm_source=use-the-index-luke.com&utm_campaign=blog-201711-spanish&utm_medium=web) and [Spanish](https://rendimiento-sql-explicado.es/?utm_source=use-the-index-luke.com&utm_campaign=blog-201711-spanish&utm_medium=web) version of the book!\n\nYou can buy it directly from the [book website](https://rendimiento-sql-explicado.es/?utm_source=use-the-index-luke.com&utm_campaign=blog-201711-spanish&utm_medium=web) (PDF or paperback), and some it’s also [available through some European Amazon stores](https://rendimiento-sql-explicado.es/r/local-amazon?utm_source=use-the-index-luke.com&utm_campaign=blog-201711-spanish&utm_medium=web) (paperback only). The prices are the same as for the other languages: **€9.95 for the PDF**, €29.95 for the hard copy, **€34.95 for PDF+paperback**. If you order from the [book website, you get **free shipping (worldwide!)**](https://rendimiento-sql-explicado.es/?utm_source=use-the-index-luke.com&utm_campaign=blog-201711-spanish&utm_medium=web)\n\nAs for the other languages, all of the Spanish **content is available for free at [https://use-the-index-luke.com/es/](/es)**.\n\nAs part of this translation effort, we (the translators and myself) also updated the content to the latest database releases: Db2 11.1, MySQL 5.7 ([carefully phrased so it stays correct for 8.0](/sql/sorting-grouping/order-by-asc-desc-nulls-last#mysql-ignores-asc-desc)), Oracle 12c R2, and PostgreSQL 10.\n\nAs the book focuses on concepts, only a few changes were needed. Here are some of the more important ones:\n\n- [MySQL 5.7 supports function-based indexes via generated columns](/sql/where-clause/functions/case-insensitive-search#overview-fbi-via-computed). The explanations for this were already in the book because SQL Server uses the same approach to function-based indexes — so we just had to mention that this works in MySQL 5.7 too.\n- [SQL Server 2016 increased the maximum key length for indexes.](/sql/clustering/index-only-scan-covering-index#overview_index_row_length) Index keys were generally limited to 16 columns with 900 bytes in total. Now it’s 32 columns. Non-clustered indexes can now have up to 1700 bytes.\n- [Oracle 12c supports `fetch first … rows only`](/sql/partial-results/top-n-queries#overview_top_n) This was also a trivial change because the PostgreSQL examples were already using `fetch first … rows only`.\n\nNo big deal, right? If you own a hard copy, don’t throw it away yet ;) If you have the PDF edition, you can [download an updated version here](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-201711-spanish&utm_medium=web#request-download) (link works for all languages).\n\n## A BIG THANK YOU\n\nI would like to send a BIG THANK YOU to the translators and reviewers! Thanks [Guillaume](http://blog.guillaume.lelarge.info/) and thanks [Hayato](https://x.com/dblmkt) for the continued efforts. Special thanks to [Martin](https://www.linkedin.com/in/martin-le-tarnec), the translator of the Spanish edition, and [Álvaro](https://x.com/ahachete), the technical reviewer and mastermind behind [ToroDB — Bringing MongoDB to SQL](https://web.archive.org/web/20230527025320/https://www.torodb.com/).\n\n## Also Updated: The 3-Minute Quiz!\n\nIn unrelated news: I’ve also updated the very popular [3-Minute SQL Indexing Quiz: Can you spot the five most common SQL indexing mistakes?](/3-minute-quiz)\n\n60% of the participants actually **fail** the quiz — it can’t be that hard, can it? Don’t forget to challenge your colleagues ;)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 4844, "slov": 606, "odkazu": 68, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:39", "sha256": "9851f48a5139b67a7a95f50d8fa34dbebd14e1286133da11bd641b7745bf5427", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://sql-performance-explained.com/", "https://sql-performance-explained.de/", "https://sql-au-coeur-des-performances.fr/", "https://sql-performance-explained.jp/", "https://rendimiento-sql-explicado.es/", "https://rendimiento-sql-explicado.es/r/local-amazon", "http://blog.guillaume.lelarge.info/", "https://x.com/dblmkt", "https://www.linkedin.com/in/martin-le-tarnec", "https://x.com/ahachete", "https://www.torodb.com/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2018-07/upcoming-advanced-sql-training", "titulek": "Upcoming Training: SQL Performance Kick-Start and modern SQL", "h1": "Upcoming Training: SQL Performance Kick-Start and modern SQL", "popis": "My training “SQL Performance Kick-Start” is part of my 5-day advanced SQL training in Vienna (17-21 Sep).", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2018-07/upcoming-advanced-sql-training", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Upcoming Training: SQL Performance Kick-Start and modern SQL", "og:description": "My training “SQL Performance Kick-Start” is part of my 5-day advanced SQL training in Vienna (17-21 Sep).", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Upcoming Training: SQL Performance Kick-Start and modern SQL"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# Upcoming Training: SQL Performance Kick-Start and modern SQL\n\n---\n\nI haven’t blogged here in a while. It doesn’t mean *Use The Index, Luke!* is abandoned or anything the like. Au contraire, I’m having some topics in the pipeline I’m hoping to blog soon about. Furthermore, *Use The Index, Luke!* is regularly updated to reflect changes in newer databases releases.\n\nThe last updates were done a few weeks back when MySQL 8.0 was released (see my blog posts “[One Giant Leap For SQL: MySQL 8.0 Released](https://modern-sql.com/blog/2018-04/mysql-8.0)” and “[Big News In Databases — Summer 2018](https://winand.at/newsletter/2018-07/sql-over-the-cloud-fsyncgate)”). Feel free to subscribe my [modern SQL](https://modern-sql.com/) blog too ([RSS](https://modern-sql.com/feed), [EMail](https://winand.at/lists)) so you don’t miss any news.\n\nBut what I actually wanted to tell you about is my upcoming **[advanced SQL training](https://winand.at/sql-training/5-day-training/aug-sept-2018) in Vienna (Austria) from September 17 to 21 2018**. Yes, that’s full week of SQL goodness.\n\nThe training covers the full content of my book “[SQL Performance Explained](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2018-07-training&utm_medium=web)” and a lot of the “[modern SQL](https://modern-sql.com/)” topics I’m currently writing and [talking](https://winand.at/events) about (window functions, recursion, …) but also barely known basics like the [three-valued logic of SQL](https://modern-sql.com/concept/three-valued-logic). You can find [all details and register (without obligation) at my “commercial” website winand.at](https://winand.at/sql-training/5-day-training/aug-sept-2018).\n\n[Check it out now!](https://winand.at/sql-training/5-day-training/aug-sept-2018)\n\nFeel free to [contact me](/contact) (office (at) winand.at) if you have any questions.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2487, "slov": 328, "odkazu": 58, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:44", "sha256": "7d2090df552bfd84699dce6fe01f9fc49207e25e4df5d219a99e28b24bd225af", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://modern-sql.com/blog/2018-04/mysql-8.0", "https://winand.at/newsletter/2018-07/sql-over-the-cloud-fsyncgate", "https://modern-sql.com/", "https://modern-sql.com/feed", "https://winand.at/lists", "https://winand.at/sql-training/5-day-training/aug-sept-2018", "https://sql-performance-explained.com/", "https://winand.at/events", "https://modern-sql.com/concept/three-valued-logic", "https://bsky.app/profile/winand.at", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes", "titulek": "Index INCLUDE Clause: How it works and when to use it", "h1": "A Close Look at the Index Include Clause", "popis": "The INCLUDE clause for CREATE INDEX is available in some SQL databases: Microsoft SQL Server, PostgreSQL, and IBM Db2 (LUW)", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Index INCLUDE Clause: How it works and when to use it", "og:description": "The INCLUDE clause for CREATE INDEX is available in some SQL databases: Microsoft SQL Server, PostgreSQL, and IBM Db2 (LUW)", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "A Close Look at the Index Include Clause"}, {"uroven": 4, "text": "Translations"}, {"uroven": 2, "text": "Recap: B-tree Indexes"}, {"uroven": 4, "text": "Note"}, {"uroven": 2, "text": "Recap: Index-Only Scan"}, {"uroven": 4, "text": "B-tree Indexes Help Many Clauses"}, {"uroven": 4, "text": "Note"}, {"uroven": 2, "text": "The Include Clause"}, {"uroven": 4, "text": "“Covering Index”"}, {"uroven": 4, "text": "Length Limitations"}, {"uroven": 4, "text": "If you like this page, you might also like …"}, {"uroven": 2, "text": "Filtering on Include Columns"}, {"uroven": 4, "text": "Important"}, {"uroven": 2, "text": "Unique Indexes with Include Clause"}, {"uroven": 2, "text": "Compatibility"}, {"uroven": 2, "text": "PostgreSQL: No Filtering Before Visibility Check"}, {"uroven": 2, "text": "About the Author"}, {"uroven": 2, "text": "Footnotes"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# A Close Look at the Index `Include` Clause\n\n---\n\n#### Translations\n\n中文 [对索引Include子句的深入分析](http://www.postgres.cn/v2/news/viewone/1/521)\n\nفارسی[نگاهی عمقی به ؚباعت include ŘŻŘą ایندکس‌ها](https://davat.dev/%d9%86%da%af%d8%a7%d9%87%db%8c-%d8%b9%d9%85%d9%82%db%8c-%d8%a8%d9%87-%d8%b9%d8%a8%d8%a7%d8%b1%d8%aa-include-%d8%af%d8%b1-%d8%a7%db%8c%d9%86%d8%af%da%a9%d8%b3%d9%87%d8%a7/)\n\nSome database—namely Microsoft SQL Server, IBM Db2, and also PostgreSQL since release 11—offer an `include` clause in the `create index` statement. The introduction of this feature to PostgreSQL is the trigger for this long overdue explanation of the `include` clause.\n\nBefore going into the details, let’s start with a short recap on how (non-clustered) B-tree indexes work and what the all-mighty index-only scan is.\n\nContents:\n\n1. Recap: B-tree Indexes\n2. Recap: Index-Only Scan\n3. The `Include` Clause\n4. Filtering on `Include` Columns\n5. Unique Indexes with `Include` Clause\n6. Compatibility\n7. PostgreSQL: No Filtering Before Visibility Check\n\n## Recap: B-tree Indexes\n\nTo understand the `include` clause, you must first understand that using an index affects up to three layers of data structures:\n\n- The B-tree\n- The doubly linked list at the leaf node level of the B-tree\n- The table\n\nThe first two structures together form an index so they could be combined into a single item, i.e. the “B-tree index”. I prefer to keep them separate as they serve different needs and have a different impact on performance. Moreover, explaining the `include` clause requires making this distinction.\n\nIn the general case, the database software starts traversing the B-tree to find the first matching entry at the leaf node level (1). It then follows the doubly linked list until it has found all matching entries (2) and finally it fetches each of those matching entries from the table (3). Actually, the last two steps can be interleaved, but that is not relevant for understanding the general concept.\n\nThe following formulas give you a rough idea of how many read operations each of these steps needs. The sum of these three components is the total effort of an index access.0\n\n- The B-tree: *log100()*, often less than 5\n- The doubly linked list: * / 100*\n- The table: **1\n\nWhen loading a few rows, the B-tree makes the greatest contribution to the overall effort. As soon as you need to fetch just a handful of rows from the table, this step takes the lead. In either case—few or many rows—the doubly linked list is usually a minor factor because it stores rows with similar values next to each other so that a single read operation can fetch 100 or even more rows. The formula reflects this by the respective divisor.2\n\n#### Note\n\nIf you are thinking “That’s why we have clustered indexes”, please read my article: [*Unreasonable Defaults: Primary Key as Clustering Key*](/blog/2014-01/unreasonable-defaults-primary-key-clustering-key).\n\nThe most generic idea about optimization is to do less work to achieve the same goal. When it comes to index access, this means that the database software omits accessing a data structure if it doesn’t need any data from it.3\n\n*You can read more about the inner workings of B-tree indexes in [Chapter 1*Anatomy of an SQL Index*](/sql/anatomy) of [SQL Performance Explained](https://sql-performance-explained.com?utm_source=use-the-index-luke.com&utm_campaign=blog-2019-04-include&utm_medium=web&utm_content=btree).*\n\n## Recap: Index-Only Scan\n\nThe index-only scan does exactly that: it omits the table access if the required data is available in the doubly linked list of the index.\n\nConsider the following index and query I borrowed from [*Index-Only Scan: Avoiding Table Access*](/sql/clustering/index-only-scan-covering-index).\n\n```\nCREATE INDEX idx\n ON sales\n ( subsidiary_id, eur_value )\n```\n\n```\nSELECT SUM(eur_value)\n FROM sales\n WHERE subsidiary_id = ?\n```\n\nAt first glance, you may wonder why the column `eur_value` is in the index definition at all—it is not mentioned in the `where` clause.\n\n#### B-tree Indexes Help Many Clauses\n\nIt is a common misconception that indexes only help the `where` clause.\n\nB-tree indexes can also help the `order by`, `group by`, `select` and other clauses. It is just the B-tree part of an index—not the doubly linked list—that cannot be used by other clauses.\n\nThe crucial point in this example is that the B-tree index happens to have all required columns—the database software doesn’t need to access the table itself. This is what we refer to as an *index-only scan*.\n\nApplying the formulas above, the performance benefit of this is very small if only a few rows satisfy the `where` clause. On the other hand, if the `where` clause accepts many rows, e.g. millions, the number of read operations is essentially reduced by a factor of 100.\n\n#### Note\n\nIt is not uncommon that an index-only scan improves performance by one or two orders of magnitude.\n\nThe example above uses the fact that the doubly-linked list—the leaf nodes of the B-tree—contains the `eur_value` column. Although the other nodes of the B-tree store that column too, this query has no use for the information in these nodes.\n\n## The `Include` Clause\n\nThe `include` clause allows us to make a distinction between columns we would like to have in the entire index (key columns) and columns we only need in the leaf nodes (`include` columns). That means it allows us to remove columns from the non-leaf nodes if we don’t need them there.\n\n#### “Covering Index”\n\nThe term “covering index” is sometimes used in the context of index-only scans or `include` clauses. As this term is often used with a different meaning, I generally avoid it.\n\nWhat matters is whether a given index can support a given query by means of an index-only scan. Whether or not that index has an `include` clause or contains *all* table columns is not relevant.\n\nUsing the `include` clause, we could refine the index for this query:\n\n```\nCREATE INDEX idx\n ON sales ( subsidiary_id )\n INCLUDE ( eur_value )\n```\n\nThe query can still use this index for an index-only scan, thus yielding essentially the same performance.\n\nBesides the obvious differences in the picture, there is also a more subtle difference: the order of the leaf node entries does not take the `include` columns into account. The index is solely ordered by its key columns.4 This has two consequences: `include` columns cannot be used to prevent sorting nor are they considered for uniqueness (see below).\n\n#### Length Limitations\n\nThe maximum length an index entry can have is limited. That means, you cannot always put all columns you want into an index.\n\nSome products—in particular SQL Server—put tighter limits on the key part of the index as they do for the total index entry length with `include` columns.5 In such systems, you can revert to the `include` clause if you cannot put all required columns into the index key. Even though these columns cannot be used as access predicates, they still allow to check conditions on these columns without accessing the table.\n\nCompared to the original index definition, the new definition with the `include` clause has some advantages:\n\n- The tree might have fewer levels (<~40%) As the tree nodes above the doubly linked list do not contain the `include` columns, the database can store more branches in each block so that the tree might have fewer levels.\n- The index is slightly smaller (<~3%) As the non-leaf nodes of the tree don’t contain `include` columns, the overall size of that index is slightly less. However, the leaf node level of the index needs the most space anyway so that the potential savings in the remaining nodes is very little.\n- It documents its purpose This is definitely the most underestimated benefit of the `include` clause: the reason why the column is in the index is document in the index definition itself.\n\nLet me elaborate on the last item.\n\nWhen extending an existing index, it is very important to know exactly why the index is currently defined the way it happens to be defined. The freedoms you have in changing the index without breaking any other queries is a direct result of this knowledge.\n\nThe following query demonstrates this:\n\n```\nSELECT *\n FROM sales\n WHERE subsidiary_id = ?\n ORDER BY ts DESC\n FETCH FIRST 1 ROW ONLY\n```\n\nAs before, for a given subsidiary this query fetches the most recent `sales` entry (`ts` is for time stamp).\n\nTo optimize this query, it would be great to have an index that starts with the key columns `(subsidiary_id, ts)`. With this index, the database software can directly navigate to the latest entry for that subsidiary and return it right away. There is no need to read and sort all of the entries for that subsidiary because the doubly linked list is sorted according to the index key, i.e. the last entry for any given subsidiary must have the greatest `ts` value for that subsidiary. With this approach, the query is essentially as fast as a primary key lookup. See [*Indexing Order By*](/sql/sorting-grouping/indexed-order-by) and [*Querying Top-N Rows*](/sql/partial-results/top-n-queries) for more details about this technique.\n\n#### If you like this page, you might also like …\n\n… to [subscribe my **mailing lists**](https://winand.at/lists), [get **free stickers**](https://use-the-index-luke.com/shop), [buy **my book**](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=blog-2019-04-include&utm_medium=web&utm_content=include) or [join a **training**](https://winand.at/sql-training/open-online-class).\n\nBefore adding a new index for this query, we should check if there is an existing index that can be changed (extended) to support this trick. This is generally a good practice because extending an existing index has a smaller impact on the maintenance overhead than adding a new index. However, when changing an existing index, we need to make sure that we do not make that index less useful for other queries.\n\nIf we look at the original index definition, we encounter a problem:\n\n```\nCREATE INDEX idx\n ON sales\n ( subsidiary_id, eur_value )\n```\n\nTo make this index support the `order by` clause of the above query, we would need to insert the `ts` column between the two existing columns:\n\n```\nCREATE INDEX idx\n ON sales\n ( subsidiary_id, ts, eur_value )\n```\n\nHowever, that might render this index less useful for queries that need the `eur_value` column in the second position, e.g. if it was in the `where` or `order by` clause. Changing this index involves a considerable risk: breaking other queries unless we know that there are no such queries. If we don’t know, it is often best to keep the index as it is and create another one for the new query.\n\nThe picture changes completely if we look at the index with the `include` clause.\n\n```\nCREATE INDEX idx\n ON sales ( subsidiary_id )\n INCLUDE ( eur_value )\n```\n\nAs the `eur_value` column is in the `include` clause, it is not in the non-leaf nodes and thus neither useful for navigating the tree nor for ordering. Adding a new column to the end of the key part is relatively safe.\n\n```\nCREATE INDEX idx\n ON sales ( subsidiary_id, ts )\n INCLUDE ( eur_value )\n```\n\nEven though there is still a small risk of negative impacts for other queries, it is usually worth taking that risk.6\n\nFrom the perspective of index evolution, it is thus very helpful to put columns into the `include` clause if this is all you need. Columns that are just added to enable an index-only scan are the prime candidates for this.\n\n## Filtering on `Include` Columns\n\nUntil now we have focused on how the `include` clause can enable index-only scans. Let’s also look at another case where it is beneficial to have an extra column in the index.\n\n```\nSELECT *\n FROM sales\n WHERE subsidiary_id = ?\n AND notes LIKE '%search term%'\n```\n\nI’ve made the search term a literal value to show the leading and trailing wildcards—of course you would use a bind parameter in your code.\n\nNow, let’s think about the right index for this query. Obviously, the `subsidiary_id` needs to be in the first position. If we take the previous index from above, it already satisfies this requirement:\n\n```\nCREATE INDEX idx\n ON sales ( subsidiary_id, ts )\n INCLUDE ( eur_value )\n```\n\nThe database software can use that index with the three-step procedure as described at the beginning: (1) it will use the B-tree to find the first index entry for the given subsidiary; (2) it will follow the doubly linked list to find all sales for that subsidiary; (3) it will fetch all related sales from the table, remove those for which the `like` pattern on the `notes` column doesn’t match and return the remaining rows.\n\nThe problem is the last step of this procedure: the table access loads rows without knowing if they will make it into the final result. Quite often, the table access is the biggest contributor to the total effort of running a query. Loading data that is not even selected is a huge performance no-no.\n\n#### Important\n\nAvoid loading data that doesn’t affect the result of the query.\n\nThe challenge with this particular query is that it uses an in-fix `like` pattern. Normal B-tree indexes don’t support *searching* such patterns. However, B-tree indexes still support *filtering* on such patterns. Note the emphasis: *searching* vs. *filtering*.\n\nIn other words, if the `notes` column was present in the doubly linked list, the database software could apply the `like` pattern before fetching that row from the table (not PostgreSQL, see below). This prevents the table access if the `like` pattern doesn’t match. If the table has more columns, there is still a table access to fetch those columns for the rows that satisfy the `where` clause—due to the `select *`.\n\n```\nCREATE INDEX idx\n ON sales ( subsidiary_id, ts )\n INCLUDE ( eur_value, notes )\n```\n\nIf there are more columns in the table, the index does not enable an index-only scan. Nonetheless, it can bring the performance close to that of an index-only scan if the portion of rows that match the `like` pattern is very low. In the opposite case—if all rows match the pattern—the performance is a little bit worse due to the increased index size. However, the breakeven is easy to reach: for an overall performance improvement, it is often enough that the `like` filter removes a small percentage of the rows. Your mileage will vary depending on the size of the involved columns.\n\n## Unique Indexes with `Include` Clause\n\nLast but not least there, is an entirely different aspect of the `include` clause: unique indexes with an `include` clause only consider the key columns for the uniqueness.\n\nThat allows us to create unique indexes that have additional columns in the leaf nodes, e.g. for an index-only scan.\n\n```\nCREATE UNIQUE INDEX …\n ON … ( id )\n INCLUDE ( payload )\n```\n\nThis index protects against duplicate values in the `id` column,7 yet it supports an index-only scan for the next query.\n\n```\nSELECT payload\n FROM …\n WHERE id = ?\n```\n\nNote that the `include` clause is not strictly required for this behavior: databases that make a proper distinction between *unique constraints* and *unique indexes* just need an index with the unique key columns as the leftmost columns—additional columns are fine.\n\nFor the Oracle Database, the corresponding syntax is this:\n\n```\nCREATE INDEX …\n ON … ( id, payload )\n```\n\n```\nALTER TABLE … ADD UNIQUE ( id )\n USING INDEX …\n```\n\n## Compatibility\n\n1. a Use `unique (…) using index …` with an index that has more columns\n\n## PostgreSQL: No Filtering Before Visibility Check\n\nThe PostgreSQL database has a limitation when it comes to applying filters on the index level. The short story is that it doesn’t do it, except in a few cases. Even worse, some of those cases only work when the respective data is stored in the key part of the index, not in the `include` clause. That means moving columns to the `include` clause may negatively affect performance, even if the above described logic still applies.\n\nThe long story starts with the fact that PostgreSQL keeps old row versions in the table until they become invisible to all transactions and the vacuum process removes them at some later point in time. To know whether a row version is visible (to a given transaction) or not, each table has two extra attributes that indicate when a row version was created and deleted: [`xmin` and `xmax`](https://www.postgresql.org/docs/11/ddl-system-columns.html). The row is only visible if the current transaction falls within the `xmin`/`xmax` range.8\n\nUnfortunately, the `xmin`/`xmax` values are not stored in indexes.9\n\nThat means that whenever PostgreSQL is looking at an index entry, it cannot tell whether or not that entry is visible to the current transaction. It could be a deleted entry or an entry that has not yet been committed. The canonical way to find out is to look into the table and check the `xmin`/`xmax` values.\n\nA consequence is that there is no such thing as an index-only scan in PostgreSQL. No matter how many columns you put into an index, PostgreSQL will always need to check the visibility, which is not available in the index.\n\nYet there is an `Index Only Scan` operation in PostgreSQL—but that still needs to check the visibility of each row version by accessing data outside the index. Instead of going to the table, the `Index Only Scan` first checks the so-called visibility map. This visibility map is very dense so the number of read operations is (hopefully) less than fetching `xmin`/`xmax` from the table. However, the visibility map does not always give a definite answer: the visibility map either states that that the row is known to be visible, or that the visibility is not known. In the latter case, the `Index Only Scan` still needs to fetch `xmin`/`xmax` from the table (shown as “Heap Fetches” in `explain analyze`).\n\nAfter this short visibility digression, we can return to filtering on the index level.\n\nSQL allows arbitrary complex expressions in the `where` clause. These expressions might also cause runtime errors such as “division by zero”. If PostgreSQL would evaluate such expression before confirming the visibility of the respective entry, even invisible rows could cause such errors. To prevent this, PostgreSQL generally checks the visibility *before* evaluating such expressions.\n\nThere is one exception to this general rule. As the visibility cannot be checked while *searching* an index, operators that can be used for *searching* must always be safe to use. These are the operators that are defined in the respective operator class. If a simple comparison filter uses an operation from such an operator class, PostgreSQL can apply that filter before checking the visibility because it knows that these operators are safe to use. The crux is that only *key columns* have an operator class associated with them. Columns in the `include` clause don’t—filters based on them are not applied before their visibility is confirmed. This is my understanding from [a thread on the PostgreSQL hackers mailing list](https://www.postgresql.org/message-id/flat/7DF52167-4379-4A1E-A957-90D774EBDF21%40winand.at).\n\nFor a demonstration, take the previous index and query:\n\n```\nCREATE INDEX idx\n ON sales ( subsidiary_id, ts )\n INCLUDE ( eur_value, notes )\n```\n\n```\nSELECT *\n FROM sales\n WHERE subsidiary_id = ?\n AND notes LIKE '%search term%'\n```\n\nThe execution plan—edited for brevity—could look like this:\n\n```\n QUERY PLAN\n----------------------------------------------\nIndex Scan using idx on sales (actual rows=16)\n Index Cond: (subsidiary_id = 1)\n Filter: (notes ~~ '%search term%')\n Rows Removed by Filter: 240\n Buffers: shared hit=54\n```\n\nThe `like` filter is shown in `Filter`, not in `Index Cond`. That means it was applied at table level. Also, the number of shared hits is rather high for fetching 16 rows.\n\nIn a `Bitmap Index/Heap Scan` the phenomenon becomes more obvious.\n\n```\n QUERY PLAN\n-----------------------------------------------\nBitmap Heap Scan on sales (actual rows=16)\n Recheck Cond: (idsubsidiary_id= 1)\n Filter: (notes ~~ '%search term%')\n Rows Removed by Filter: 240\n Heap Blocks: exact=52\n Buffers: shared hit=54\n -> Bitmap Index Scan on idx (actual rows=256)\n Index Cond: (subsidiary_id = 1)\n Buffers: shared hit=2\n```\n\nThe `Bitmap Index Scan` does not mention the `like` filter at all. Instead it returns 256 rows—way more than the 16 that satisfy the `where` clause.\n\nNote that this is not a particularity of the `include` column *in this case*. Moving the `include` columns into the index key gives the same result.\n\n```\nCREATE INDEX idx\n ON sales ( subsidiary_id, ts, eur_value, notes)\n```\n\n```\n QUERY PLAN\n-----------------------------------------------\nBitmap Heap Scan on sales (actual rows=16)\n Recheck Cond: (subsidiary_id = 1)\n Filter: (notes ~~ '%search term%')\n Rows Removed by Filter: 240\n Heap Blocks: exact=52\n Buffers: shared hit=54\n -> Bitmap Index Scan on idx (actual rows=256)\n Index Cond: (subsidiary_id = 1)\n Buffers: shared hit=2\n```\n\nThis is because the `like` operator is not part of the operator class so it is not considered to be safe.\n\nIf you use an operation from the operator class, e.g. equals, the execution plan changes.\n\n```\nSELECT *\n FROM sales\n WHERE subsidiary_id = ?\n AND notes = 'search term'\n```\n\nThe `Bitmap Index Scan` now applies all conditions from the `where` clause and only passes the remaining 16 rows on to the `Bitmap Heap Scan`.\n\n```\n QUERY PLAN\n----------------------------------------------\nBitmap Heap Scan on sales (actual rows=16)\n Recheck Cond: (subsidiary_id = 1\n AND notes = 'search term')\n Heap Blocks: exact=16\n Buffers: shared hit=18\n -> Bitmap Index Scan on idx (actual rows=16)\n Index Cond: (subsidiary_id = 1\n AND notes = 'search term')\n Buffers: shared hit=2\n```\n\nNote that this requires the respective column to be a key column. If you move the `notes` column back to the `include` clause, it has no associated operator class so the equals operator is not considered safe anymore. Consequently, PostgreSQL postpones applying this filter to the table access until after the visibility is checked.\n\n```\n QUERY PLAN\n-----------------------------------------------\nBitmap Heap Scan on sales (actual rows=16)\n Recheck Cond: (id = 1)\n Filter: (notes = 'search term')\n Rows Removed by Filter: 240\n Heap Blocks: exact=52\n Buffers: shared hit=54\n -> Bitmap Index Scan on idx (actual rows=256)\n Index Cond: (id = 1)\n Buffers: shared hit=2\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).\n\n## Footnotes\n\n1. 0 We are assuming 100 index entries per page/block.\n2. 1 Worst case scenario: all rows of interest are in different blocks, i.e. the worst possible clustering factor.\n3. 2 The doubly linked list can become the limiting factor nevertheless, e.g. in an index-only scan or more generally expressed when the number of rows fetched from the table is far less than the number of rows read from the doubly linked list.\n4. 3 The `INDEX FAST FULL SCAN` of the Oracle Database is an extreme case in which only one part of one structure is used: the leaf nodes of the B-tree, i.e. the doubly linked list without its links. As a side note: I still wonder why `INDEX FAST FULL SCAN` is only used as index-only scan by the Oracle Database.\n5. 4 The reason for this is quite simple: When inserting a new row, the tree only supports searching on the key columns. That means that even if the leaf nodes were ordered according to all columns, there is no way to directly navigate to the spot where the new row would go. The database software would need to check all rows with the same key value.\n6. 5 Example in SQL Server: maximum key length 900/1700 bytes, maximum total index entry length 8060 bytes.\n7. 6 The major risk is that the clustering factor gets worse—in particular in the Oracle Database. See [*Automatically Optimized Clustering Factor*](/sql/sorting-grouping/indexed-order-by#sb-order-by-clustering-factor). The other risk is the length of the doubly linked list.\n8. 7 Except duplicate `null` values, which are accepted by unique constraints. See [`Null` in Unique Constraints](https://modern-sql.com/concept/null#unique) on [modern-sql.com](https://modern-sql.com/).\n9. 8 That is of course simplified. Read “[How Postgres Makes Transactions Atomic](https://brandur.org/postgres-atomicity)” to learn how the snapshots work in PostgreSQL.\n10. 9 Just adding `xmin`/`xmax` via include is tempting, but “index creation on system columns is not supported”. Maintaining `xmax` in the index would require every `update`/`delete` to update all indexes.", "znaku_textu": 24641, "slov": 4084, "odkazu": 84, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:45", "sha256": "d5872a68e59a88fa5a9b68d28b2b74a722802f278ac7d0a8125b136c3937172e", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "http://www.postgres.cn/v2/news/viewone/1/521", "https://davat.dev/%D9%86%DA%AF%D8%A7%D9%87%DB%8C-%D8%B9%D9%85%D9%82%DB%8C-%D8%A8%D9%87-%D8%B9%D8%A8%D8%A7%D8%B1%D8%AA-include-%D8%AF%D8%B1-%D8%A7%DB%8C%D9%86%D8%AF%DA%A9%D8%B3%D9%87%D8%A7/", "https://sql-performance-explained.com/", "https://winand.at/lists", "https://winand.at/sql-training/open-online-class", "https://www.postgresql.org/docs/11/ddl-system-columns.html", "https://www.postgresql.org/message-id/flat/7DF52167-4379-4A1E-A957-90D774EBDF21@winand.at", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://modern-sql.com/concept/null", "https://brandur.org/postgres-atomicity", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/2024-12/date-time-prefix-rewrite", "titulek": "Index Usage For EXTRACT(YEAR FROM …), YEAR(…) etc.", "h1": "Automatic Rewrite of Date and Time Ranges", "popis": "Some systems convert expressions like EXTRACT(YEAR FROM COL) = 2024 into a range condition.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/blog/2024-12/date-time-prefix-rewrite", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Index Usage For EXTRACT(YEAR FROM …), YEAR(…) etc.", "og:description": "Some systems convert expressions like EXTRACT(YEAR FROM COL) = 2024 into a range condition.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Automatic Rewrite of Date and Time Ranges"}, {"uroven": 4, "text": "Caution"}, {"uroven": 2, "text": "About the Author"}, {"uroven": 2, "text": "Footnotes"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Automatic Rewrite of Date and Time Ranges\n\n---\n\nThe following chart shows which DBMS rewrites `where` clause expressions that access the year part of a `date` or `timestamp` (or the like) into a range expression such as `ts >= DATE'2024-01-01' AND ts < DATE'2025-01-01'`. This enables the use of a sort-based index on the `ts` column.\n\n1. a Unconditionally rewritten — even if only a matching function-based index exists\n\nThe yellow check marks mean that the rewrite is always done—even if there was a function-based index1 on the original expression in the `where` clause.\n\nThis rewrite is generally applicable if the most significant parts of a `date`, `timestamp` are used for filtering. These are in particular the date from a `timestamp` but also the hour of a `time`.\n\n1. a Unconditionally rewritten — even if only a matching function-based index exists\n\nI generally recommend to use the “inclusive lower, exclusive upper bound“ pattern explicitly in the `where` clause.\n\n#### Caution\n\nDue to the current use of web-content to train AI models, I will publish less content to the web (including RSS). The [mailing lists](https://winand.at/lists) will continue to get the full content. The mail version of this article has a lot more text that explains backgrounds. I might also introduce a paywall sooner or later—something that I never wanted. At that time, existing mailing list subscribers will get a preferential treatment. [Subscribe here while it is still free](https://winand.at/lists).\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).\n\n## Footnotes\n\n1. 0 E.g. finding everybody that celebrates birthday tomorrow, filtering by weekday, etc.\n2. 1 No matter if the expression is indexed directly or via [a generated column](https://modern-sql.com/caniuse/generated-always-as).\n3. 2 Well, the FBI could include the `ts` columns additionally—but that would be really big waste of space", "znaku_textu": 2455, "slov": 377, "odkazu": 53, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:46", "sha256": "d9344d464f99d62b30b16792242213fca888988f02175df30d3937a2560b0b26", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://modern-sql.com/caniuse/generated-always-as", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/blog/feed", "titulek": "Use The Index, Luke!", "h1": "", "popis": "", "klicova_slova": "", "kanonicka": "", "jazyk": "", "robots_meta": "", "og": {}, "jsonld": [], "drobecky": [], "osnova": [], "markdown": "Use The Index, Luke!https://use-the-index-luke.com/A Guide to SQL Performance for Developersenhttps://use-the-index-luke.com/static/icon-400x400.pnghttps://use-the-index-luke.com/static/logo-280x150.pnghttps://use-the-index-luke.com/static/logo-280x150.pngUse The Index, Luke!https://use-the-index-luke.com/Index Usage For EXTRACT(YEAR FROM …), YEAR(…) etc.https://use-the-index-luke.com/blog/2024-12/date-time-prefix-rewrite/blog/2024-12/date-time-prefix-rewrite10 Dec 2024 00:00:00 GMTIndex INCLUDE Clause: How it works and when to use ithttps://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes/blog/2019-04/include-columns-in-btree-indexes30 Apr 2019 00:00:00 GMTUpcoming Training: SQL Performance Kick-Start and modern SQLhttps://use-the-index-luke.com/blog/2018-07/upcoming-advanced-sql-training/blog/2018-07/upcoming-advanced-sql-training31 Jul 2018 00:00:00 GMTSpanish Translation and Other Newshttps://use-the-index-luke.com/blog/2017-11/spanish-anyonehttp://use-the-index-luke.com/blog/2017-11/spanish-anyone13 Nov 2017 00:00:00 GMTBig News In Databases: Cloud Wars, IBM’s Renaming Insanity, Three Major Releaseshttps://use-the-index-luke.com/blog/2017-11/cloud-wars-ibm-db2-renaming-major-database-releaseshttp://use-the-index-luke.com/blog/2017-11/cloud-wars-ibm-db2-renaming-major-database-releases06 Nov 2017 00:00:00 GMTBig News In Databases: new SQL standard, cloud wars, ACIDRain (Spring 2017)https://use-the-index-luke.com/blog/2017-05/new-sql-standard-oracle-122-acidrainhttp://use-the-index-luke.com/blog/2017-05/new-sql-standard-oracle-122-acidrain11 May 2017 00:00:00 GMT", "znaku_textu": 1619, "slov": 191, "odkazu": 0, "kodovani": "iso-8859-2", "kodovani_deklarovane": null, "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:53:49", "sha256": "63e232703bb1f34b9f0b8e7942898f490314047560a30f8fb06510f502295e76", "hloubka": 1, "zdroj_objevu": "odkaz", "ze_seznamu": false, "mime": "application/rss+xml", "odkazy_externi": []} {"url": "https://use-the-index-luke.com/contact", "titulek": "Contact Markus Winand from Use The Index, Luke!", "h1": "Contact Form", "popis": "Contact Markus Winand from Use The Index, Luke! via email or web form.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/contact", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Contact Markus Winand from Use The Index, Luke!", "og:description": "Contact Markus Winand from Use The Index, Luke! via email or web form.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Contact Form"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Contact Form\n\n---\n\nPlease leave your message below. If you prefer, you can also send an email to **office (at) winand.at**.\n\nThe transferred information is only used to answer your inquiry and is not given to any third parties.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 871, "slov": 118, "odkazu": 51, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:47", "sha256": "954c97a69a6758c3c458d43847cada596b7e85571432e2859f1ddeb7cc2123f7", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/legal", "titulek": "Legal", "h1": "Legal", "popis": "Legal Stuff about Use The Index, Luke! by Markus Winand, Vienna, Austria.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/legal", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Legal", "og:description": "Legal Stuff about Use The Index, Luke! by Markus Winand, Vienna, Austria.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Legal"}, {"uroven": 2, "text": "Disclosure"}, {"uroven": 3, "text": "Amazon Associate"}, {"uroven": 2, "text": "Memberships"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Legal\n\n---\n\nuse-the-index-luke.com is operated by\n\n```\nMarkus Winand\nMaderspergerstrasse 1-3/9/11\n1160 Wien\nAUSTRIA\n```\n\n## Disclosure\n\nPhone:+43 1 9444047Email:office (at) winand.atVAT-ID-Nr.:ATU65157359GTC:[https://www.winand.at/gtc/](https://winand.at/gtc)Applicable law:GewerbeordnungLegal form:Sole entrepreneurBusiness purpose:Services in automatic data processing and information technology\n\n### Amazon Associate\n\nAs an Amazon Associate I or my trade partner earn from qualifying purchases.\n\n## Memberships\n\nMember of the [Chamber of Commerce of Austria](https://www.wkoecg.at/ecg.aspx?firmaid=95af0cf3-ebfe-420d-be1a-0888d4d6434b).\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1269, "slov": 142, "odkazu": 53, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:48", "sha256": "290d8632fc2a759e25a259b22b34f0fb068cd5a1a381ea4a5395df6a5c0dde01", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/gtc", "https://www.wkoecg.at/ecg.aspx?firmaid=95af0cf3-ebfe-420d-be1a-0888d4d6434b", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/legal/no-warranty", "titulek": "NO WARRANTY", "h1": "NO WARRANTY", "popis": "Use The Index, Luke!by Markus Winand — Disclaimer: NO WARRANTY for any information provided", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/legal/no-warranty", "jazyk": "en", "robots_meta": "", "og": {"og:title": "NO WARRANTY", "og:description": "Use The Index, Luke!by Markus Winand — Disclaimer: NO WARRANTY for any information provided", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "NO WARRANTY"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# NO WARRANTY\n\n---\n\nWhile every precaution has been taken in the preparation of this website, the author assume no responsibility for errors and omissions, or for damages resulting from the use of the information contained herein.\n\nThe website solely reflects the author’s views. The database vendors mentioned have neither supported the work financially nor verified the content.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1025, "slov": 135, "odkazu": 51, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:49", "sha256": "8f77e3197b00a063d12c21cc47c6244e8fe80339025dc73b30757cb682a609c3", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/legal/privacy", "titulek": "Privacy and GDPR", "h1": "Privacy and GDPR", "popis": "Use The Index, Luke!by Markus Winand — Privacy: We don't serve cookies to browsers!", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/legal/privacy", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Privacy and GDPR", "og:description": "Use The Index, Luke!by Markus Winand — Privacy: We don't serve cookies to browsers!", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Privacy and GDPR"}, {"uroven": 2, "text": "Your Right According to The General Data Protection Regulation (GDPR)"}, {"uroven": 2, "text": "Payment via PayPal"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Privacy and GDPR\n\n---\n\nThis site serves no cookies to browsers.\n\nThis site does not load resources (images, JavaScript, fonts, …) from 3rd party servers.\n\nData submitted via the [contact form](/contact) is not shared with any 3rd party.\n\n[Quiz](/3-minute-quiz) results statistically analyzed and anonymously published (also the raw data).\n\n## Your Right According to The General Data Protection Regulation (GDPR)\n\nIn case I have personal data of you, you can execute your rights (right to information, right to erasure, …) by contacting me—preferably via e-mail. You can find all contact details on the [legal](/legal) page.\n\n## Payment via PayPal\n\nI’m using PayPal to receive payments. If you pay via PayPal, you are providing data to PayPal. PayPal will provide some of these data back to me (e.g. e-mail address, name, ...) but not all of it (e.g. not credit card numbers). Data you provide to PayPal are subject to [PayPal’s privacy terms](https://www.paypal.com/us/legalhub/paypal/privacy-full).\n\nOther payment options available upon [request](/contact).\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1695, "slov": 239, "odkazu": 52, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:49", "sha256": "97af9f0f41c076785df51be7301f16cee976a32e63df4cb954aa6d2d1fd4b39c", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://www.paypal.com/us/legalhub/paypal/privacy-full", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/legal/trademarks", "titulek": "Trademarks", "h1": "Trademarks", "popis": "Use The Index, Luke!by Markus Winand — Trademarks used on this site", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/legal/trademarks", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Trademarks", "og:description": "Use The Index, Luke!by Markus Winand — Trademarks used on this site", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Trademarks"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Trademarks\n\n---\n\nMany of the names used by manufacturers and sellers to distinguish their products are trademarked. Wherever such designations appear in this book, and we were aware of a trademark claim, the names have been printed in all caps or initial caps.\n\n- **DB2** is a registered trademark of **IBM Corporation**.\n- **Oracle**, **Java** and **MySQL** are registered trademarks of **Oracle and/or its affiliates**.\n- **Microsoft** and **SQL Server** are either registered trademarks or trademarks of **Microsoft Corporation** in the United States and/or other countries.\n- **PostgreSQL** is a registered trademark of **PostgreSQL Global Development Group**.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1267, "slov": 175, "odkazu": 51, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:50", "sha256": "80b52177d3ae6008c4e50f12321d8c725ea7760ad93ad5176d6682d126553f55", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/shop", "titulek": "Use The Index, Luke! Shop: Stickers, Coasters, Mugs and Books", "h1": "Take a Look — I Put The Squirrel on Everything!", "popis": "Stickers, coasters, books and coffee mugs – cool stuff that supports the work on Use The Index, Luke!", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/shop", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Use The Index, Luke! Shop: Stickers, Coasters, Mugs and Books", "og:description": "Stickers, coasters, books and coffee mugs – cool stuff that supports the work on Use The Index, Luke!", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Take a Look — I Put The Squirrel on Everything!"}, {"uroven": 2, "text": "Stickers are Free!"}, {"uroven": 2, "text": "Coaster Package"}, {"uroven": 2, "text": "SQL Performance Explained — English PDF Edition"}, {"uroven": 2, "text": "Coaster Plus PDF-Book Package"}, {"uroven": 2, "text": "SQL Performance Explained — English Print Edition"}, {"uroven": 2, "text": "Coffee Mug Package"}, {"uroven": 2, "text": "Double Mug Package"}, {"uroven": 2, "text": "Mug+Book Package"}, {"uroven": 2, "text": "Other Packages"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Take a Look — I Put The Squirrel on Everything!\n\n---\n\nCheck out the Use The Index, Luke! [merchandise](https://www.youtube.com/watch?v=PQEVgbMqq7o) – cool stuff that supports my work on the site.\n\nAll prices include **free shipping worldwide**. It’s safe and easy to pay using PayPal (see [privacy](/legal/privacy)).\n\nAs mandated by EU law, you have a 14 days right to withdraw ([learn more](/withdrawal)).\n\n## Stickers are Free!\n\nI’m mailing you the *Use The Index, Luke!* und *ModernSQL* stickers and coasters for free.\n\nOffer valid once per person and year. No cash-redemption or the like. The submitted data is only used for mailing and kept a year to detect duplicates.\n\n## Coaster Package\n\nA supply of coasters to protect your desk from the drink of your choice. The coasters feature the *Use The Index, Luke!* mascot on the front and [NoOffset](/no-offset) on the back. You get:\n\n- 8 Use The Index, Luke! coasters (two sided) Ø 107mm/~4.2″; 1.4mm thick\n- 8 Modern SQL coasters (two sided) 93x93mm/~3.7″; 1.4mm thick\n- 4 stickers One of each: *Use The Index, Luke!*, NoOffset, Modern SQL and No-Self-Join\n\n[Buy for €5.99](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=7B27RTMFULHLA)\n(free shipping)\n\n## SQL Performance Explained — English PDF Edition\n\nThe PDF edition of my book *SQL Performance Explained*. The book is also available in [French](https://sql-au-coeur-des-performances.fr/?utm_source=use-the-index-luke.com&utm_campaign=shop&utm_medium=web&utm_content=pdf-package), [Japanese](https://sql-performance-explained.jp/?utm_source=use-the-index-luke.com&utm_campaign=shop&utm_medium=web&utm_content=pdf-package) and [German](https://sql-performance-explained.de?utm_source=use-the-index-luke.com&utm_campaign=shop&utm_medium=web&utm_content=pdf-package) and is ready for immediate download. More info and reviews can be found on the [SQL Performance Explained website](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=shop&utm_medium=web&utm_content=pdf-package). You get:\n\n- 1 SQL Performance Explained PDF version\n\n[Buy for €9.95](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=3M9KEMWCVX4HA)\n(download)\n\n## Coaster Plus PDF-Book Package\n\nAlong with the stickers and the coasters, you also get the PDF version of my book *SQL Performance Explained*.\n\n- 1 *SQL Performance Explained* PDF version\n- 16 two-sided coasters\n- 4 stickers One of each: *Use The Index, Luke!*, NoOffset, Modern SQL and No-Self-Join\n\n[Buy for €15.99](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=YB2FQ4SD365HE)\n(free shipping)\n\n+ PDF\n\n## SQL Performance Explained — English Print Edition\n\nThe print edition of my book *SQL Performance Explained*. The book is also available in [French](https://sql-au-coeur-des-performances.fr/?utm_source=use-the-index-luke.com&utm_campaign=shop&utm_medium=web&utm_content=print-package), [Japanese](https://sql-performance-explained.jp/?utm_source=use-the-index-luke.com&utm_campaign=shop&utm_medium=web&utm_content=print-package) and [German](https://sql-performance-explained.de?utm_source=use-the-index-luke.com&utm_campaign=shop&utm_medium=web&utm_content=print-package). You’ll find more information and reviews on the [SQL Performance Explained website](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=shop&utm_medium=web&utm_content=print-package). You get:\n\n- 1 SQL Performance Explained Paperback (ISBN: 978-3-95030782-5)\n\n[Buy for €39.90](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=S7A4G5PKMRPN6)\n(free shipping)\n\n## Coffee Mug Package\n\nThe *Use The Index, Luke!* mug is symmetric in design for lefties and righties, and has a squirrel-colored interior for that special touch. You get:\n\n- 1 *coffee mug* Ø 7.8×12cm/~Ø 3″×4.7″; volume: 300ml/~10oz\n- 1 *SQL Performance Explained* PDF version\n- 16 two-sided coasters\n- 4 stickers One of each: *Use The Index, Luke!*, NoOffset, Modern SQL and No-Self-Join\n\n[Buy for €29.99](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=LN9XEVZBA2FF2)\n(free shipping)\n\n## Double Mug Package\n\nSave on two: get double the mug package goodness, ready to share with a friend…or even more for you!\n\n- 2 *coffee mugs* Ø 7.8×12cm/~Ø 3″×4.7″; volume: 300ml/~10oz\n- 2 *SQL Performance Explained* PDF version\n- 32 two-sided coasters\n- 8 stickers Two of each: *Use The Index, Luke!*, NoOffset, Modern SQL and No-Self-Join\n\n[Buy for €49.99](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=CU6AXNPMDL3M2)\n(free shipping)\n\n## Mug+Book Package\n\nFor the more old-fashioned reader, we also offer a mug for your favorite beverage and a book for your reading pleasure. Note: wing chair and cigar are not included. You get:\n\n- 1 *coffee mug*\n- 1 *SQL Performance Explained* in print and PDF\n- 16 two-sided coasters\n- 4 stickers One of each: *Use The Index, Luke!*, NoOffset, Modern SQL and No-Self-Join\n\n[Buy for €59.99](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=L5MQPMJB6TJUN)\n(free shipping)\n\n## Other Packages\n\nA good part of the prices is to cover shipping costs. The above combinations were carefully put together to optimize postal fees. If you’d like to order my merchandise in bigger quantities, please [drop me a note](/contact). The per-unit price might drop significantly if I can put more units into a single parcel.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 5959, "slov": 761, "odkazu": 75, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:13:52", "sha256": "6fbf6eaad6d0415d3feb82a696b2d6afa723de887f42970401fe67d636c1cf74", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://www.youtube.com/watch?v=PQEVgbMqq7o", "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=7B27RTMFULHLA", "https://sql-au-coeur-des-performances.fr/", "https://sql-performance-explained.jp/", "https://sql-performance-explained.de/", "https://sql-performance-explained.com/", "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=3M9KEMWCVX4HA", "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=YB2FQ4SD365HE", "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=S7A4G5PKMRPN6", "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=LN9XEVZBA2FF2", "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=CU6AXNPMDL3M2", "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=L5MQPMJB6TJUN", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/anatomy", "titulek": "Anatomy of an SQL Index: What is an SQL Index", "h1": "Anatomy of an SQL Index", "popis": "What does an index look like and how does it work? Learn about the B-tree, why an index doesn’t get unbalanced but can still become slow.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/anatomy", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Anatomy of an SQL Index: What is an SQL Index", "og:description": "What does an index look like and how does it work? Learn about the B-tree, why an index doesn’t get unbalanced but can still become slow.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Anatomy of an SQL Index"}, {"uroven": 2, "text": "Clustered Indexes (SQL Server, MySQL/InnoDB)"}, {"uroven": 4, "text": "If you like this page, you might also like …"}, {"uroven": 2, "text": "Contents"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Anatomy of an SQL Index\n\n---\n\n*“An index makes the query fast”* is the most basic explanation of an index I have ever seen. Although it describes the most important aspect of an index very well, it is—unfortunately—not sufficient for this book. This chapter describes the index structure in a less superficial way but doesn’t dive too deeply into details. It provides just enough insight for one to understand the SQL performance aspects discussed throughout the book.\n\nAn index is a distinct structure in the database that is built using the `create index` statement. It requires its own disk space and holds a copy of the indexed table data. That means that an index is pure redundancy. Creating an index does not change the table data; it just creates a new data structure that refers to the table. A database index is, after all, very much like the index at the end of a book: it occupies its own space, it is highly redundant, and it refers to the actual information stored in a different place.\n\n## Clustered Indexes (SQL Server, MySQL/InnoDB)\n\nSQL Server and MySQL (using InnoDB) take a broader view of what “*index*” means. They refer to tables that consist of the index structure only as *clustered indexes*. These tables are called Index-Organized Tables (IOT) in the Oracle database.\n\n[Chapter 5, “*Clustering Data: The Second Power of Indexing*”](/sql/clustering), describes them in more detail and explains their advantages and disadvantages.\n\nSearching in a database index is like searching in a printed telephone directory. The key concept is that all entries are arranged in a well-defined order. Finding data in an ordered data set is fast and easy because the sort order determines each entry’s position.\n\n#### If you like this page, you might also like …\n\n… to [subscribe my **mailing lists**](https://winand.at/lists), [get **free stickers**](https://use-the-index-luke.com/shop), [buy **my book**](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=ch-anatomy&utm_medium=web) or [join a **training**](https://winand.at/sql-training/open-online-class).\n\nA database index is, however, more complex than a printed directory because it undergoes constant change. Updating a printed directory for every change is impossible for the simple reason that there is no space between existing entries to add new ones. A printed directory bypasses this problem by only handling the accumulated updates with the next printing. An SQL database cannot wait that long. It must process `insert`, `delete` and `update` statements immediately, keeping the index order without moving large amounts of data.\n\nThe database combines two data structures to meet the challenge: a doubly linked list and a search tree. These two structures explain most of the database’s performance characteristics.\n\n## Contents\n\n1. *[The Leaf Nodes](/sql/anatomy/the-leaf-nodes)* — A doubly linked list\n2. *[The B-Tree](/sql/anatomy/the-tree)* — It’s a balanced tree\n3. *[Slow Indexes, Part I](/sql/anatomy/slow-indexes)* — Two ingredients make the index slow\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3675, "slov": 559, "odkazu": 57, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:40", "sha256": "1677ab4818ebfc3d5a6902829b12561262a4c4f3f326dad8199d26cb689e16d0", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://sql-performance-explained.com/", "https://winand.at/sql-training/open-online-class", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/anatomy/slow-indexes", "titulek": "Slow Indexes in RDBMS", "h1": "Slow Indexes, Part I", "popis": "SQL queries might be slow even when using an index. Just because the database uses the index doesn’t mean it’s the best possible index for that query.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/anatomy/slow-indexes", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Slow Indexes in RDBMS", "og:description": "SQL queries might be slow even when using an index. Just because the database uses the index doesn’t mean it’s the best possible index for that query.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Anatomy of an Index"], "osnova": [{"uroven": 1, "text": "Slow Indexes, Part I"}, {"uroven": 4, "text": "If you like this page, you might also like …"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Slow Indexes, Part I\n\n---\n\nDespite the efficiency of the tree traversal, there are still cases where an index lookup doesn’t work as fast as expected. This contradiction has fueled the myth of the *“degenerated index”* for a long time. The myth proclaims an index rebuild as the miracle solution. [Appendix B*Myth Directory*](/sql/myth-directory) covers this and other myths in detail. For now, you can take it for granted that rebuilding an index does not improve performance on the long run. The real reason trivial statements can be slow—even when using an index—can be explained on the basis of the previous sections.\n\nThe first ingredient for a slow index lookup is the leaf node chain. Consider the search for “57” in [Figure 1.3](/sql/anatomy/the-tree#TreeTraversal) again. There are obviously two matching entries in the index. At least two entries are the same, to be more precise: the next leaf node could have further entries for “57”. The database *must* read the next leaf node to see if there are any more matching entries. That means that an index lookup not only needs to perform the tree traversal, it also needs to follow the leaf node chain.\n\n#### If you like this page, you might also like …\n\n… to [subscribe my **mailing lists**](https://winand.at/lists), [get **free stickers**](https://use-the-index-luke.com/shop), [buy **my book**](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=sec-slow-index&utm_medium=web) or [join a **training**](https://winand.at/sql-training/open-online-class).\n\nThe second ingredient for a slow index lookup is accessing the table. Even a single leaf node might contain many hits—often hundreds. The corresponding table data is usually scattered across many table blocks (see [Figure 1.1*Index Leaf Nodes and Corresponding Table Data*](/sql/anatomy/the-leaf-nodes#fig-LeafNodes)). That means that there is an additional table access for each hit.\n\nAn index lookup requires three steps: (1) the tree traversal; (2) following the leaf node chain; (3) fetching the table data. The tree traversal is the only step that has an upper bound for the number of accessed blocks—the index depth. The other two steps might need to access many blocks—they cause a slow index lookup.\n\nThe origin of the “slow indexes” myth is the misbelief that an index lookup just traverses the tree, hence the idea that a slow index must be caused by a “broken” or “unbalanced” tree. The truth is that you can actually ask most databases how they use an index. The Oracle database is rather verbose in this respect and has three distinct operations that describe a basic index lookup:\n\nINDEX UNIQUE SCAN\n\nThe `INDEX UNIQUE SCAN` performs the tree traversal only. The Oracle database uses this operation if a unique constraint ensures that the search criteria will match no more than one entry.\n\nINDEX RANGE SCAN\n\nThe `INDEX RANGE SCAN` performs the tree traversal *and* follows the leaf node chain to find all matching entries. This is the fall­back operation if multiple entries could possibly match the search criteria.\n\nTABLE ACCESS BY INDEX ROWID\n\nThe `TABLE ACCESS BY INDEX ROWID` operation retrieves the row from the table. This operation is (often) performed for every matched record from a preceding index scan operation.\n\nThe important point is that an `INDEX RANGE SCAN` can potentially read a large part of an index. If there is one more table access for each row, the query can become slow even when using an index.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 4093, "slov": 645, "odkazu": 59, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:41", "sha256": "cedfed10203f1c9f48bd22bfd913f99ec438edaa69e22ea93f540e6d031cc758", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://sql-performance-explained.com/", "https://winand.at/sql-training/open-online-class", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/anatomy/the-leaf-nodes", "titulek": "The Leaf Nodes of an SQL Index", "h1": "The Index Leaf Nodes", "popis": "The index leaf nodes are an ordered list. SQL Databases use the leaf nodes to fetch rows in index order.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/anatomy/the-leaf-nodes", "jazyk": "en", "robots_meta": "", "og": {"og:title": "The Leaf Nodes of an SQL Index", "og:description": "The index leaf nodes are an ordered list. SQL Databases use the leaf nodes to fetch rows in index order.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Anatomy of an Index"], "osnova": [{"uroven": 1, "text": "The Index Leaf Nodes"}, {"uroven": 4, "text": "If you like this page, you might also like …"}, {"uroven": 2, "text": "Figure 1.1 Index Leaf Nodes and Corresponding Table Data"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# The Index Leaf Nodes\n\n---\n\nThe primary purpose of an index is to provide an ordered representation of the indexed data. It is, however, not possible to store the data sequentially because an `insert` statement would need to move the following entries to make room for the new one. Moving large amounts of data is very time-consuming so the `insert` statement would be very slow. The solution to the problem is to establish a logical order that is independent of physical order in memory.\n\n#### If you like this page, you might also like …\n\n… to [subscribe my **mailing lists**](https://winand.at/lists), [get **free stickers**](https://use-the-index-luke.com/shop), [buy **my book**](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=sec-leaf-nodes&utm_medium=web) or [join a **training**](https://winand.at/sql-training/open-online-class).\n\nThe logical order is established via a doubly linked list. Every node has links to two neighboring entries, very much like a chain. New nodes are inserted between two existing nodes by updating their links to refer to the new node. The physical location of the new node doesn’t matter because the doubly linked list maintains the logical order.\n\nThe data structure is called a*doubly linked list* because each node refers to the preceding and the following node. It enables the database to read the index forwards or backwards as needed. It is thus possible to insert new entries without moving large amounts of data—it just needs to change some pointers.\n\nDoubly linked lists are also used for collections (containers) in many programming languages.\n\n| Programming Language | Name |\n| --- | --- |\n| Java | [java.util.LinkedList](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html) |\n| .NET Framework | [System.Collections.Generic.LinkedList](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1?view=net-7.0) |\n| C++ | [std::list](https://cplusplus.com/reference/list/list/) |\n\nDatabases use doubly linked lists to connect the so-called index *leaf nodes*. Each leaf node is stored in a *database block* or *page*; that is, the database’s smallest storage unit. All index blocks are of the same size—typically a few kilobytes. The database uses the space in each block to the extent possible and stores as many index entries as possible in each block. That means that the index order is maintained on two different levels: the index entries within each leaf node, and the leaf nodes among each other using a doubly linked list.\n\n## Figure 1.1 Index Leaf Nodes and Corresponding Table Data\n\nFigure 1.1 illustrates the index leaf nodes and their connection to the table data. Each index entry consists of the indexed columns (the key, column 2) and refers to the corresponding table row (via `ROWID` or `RID`). Unlike the index, the table data is stored in a heap structure and is not sorted at all. There is neither a relationship between the rows stored in the same table block nor is there any connection between the blocks.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3634, "slov": 529, "odkazu": 61, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:42", "sha256": "7fa1262277734124e1128b0d959d2f5f018c68452a130b43ffb55838e23acfdd", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://sql-performance-explained.com/", "https://winand.at/sql-training/open-online-class", "https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html", "https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1?view=net-7.0", "https://cplusplus.com/reference/list/list/", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/anatomy/the-tree", "titulek": "The Balanced Search Tree (B-Tree) in SQL Databases", "h1": "The Search Tree (B-Tree) Makes the Index Fast", "popis": "SQL Databases use B-Trees for indexes. That are, balanced search trees, not binary trees. A B-Tree can find any entry at the same speed.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/anatomy/the-tree", "jazyk": "en", "robots_meta": "", "og": {"og:title": "The Balanced Search Tree (B-Tree) in SQL Databases", "og:description": "SQL Databases use B-Trees for indexes. That are, balanced search trees, not binary trees. A B-Tree can find any entry at the same speed.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Anatomy of an Index"], "osnova": [{"uroven": 1, "text": "The Search Tree (B-Tree) Makes the Index Fast"}, {"uroven": 2, "text": "Figure 1.2 B-tree Structure"}, {"uroven": 4, "text": "If you like this page, you might also like …"}, {"uroven": 4, "text": "Note"}, {"uroven": 2, "text": "Figure 1.3 B-Tree Traversal"}, {"uroven": 4, "text": "Important"}, {"uroven": 2, "text": "Logarithmic Scalability"}, {"uroven": 4, "text": "Links"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# The Search Tree (B-Tree) Makes the Index Fast\n\n---\n\nThe index leaf nodes are stored in an arbitrary order—the position on the disk does not correspond to the logical position according to the index order. It is like a telephone directory with shuffled pages. If you search for “Smith” but first open the directory at “Robinson”, it is by no means granted that Smith follows Robinson. A database needs a second structure to find the entry among the shuffled pages quickly: a *balanced search tree*—in short: the B-tree.\n\n## Figure 1.2 B-tree Structure\n\nFigure 1.2 shows an example index with 30 entries. The doubly linked list establishes the logical order between the leaf nodes. The root and branch nodes support quick searching among the leaf nodes.\n\nThe figure highlights a branch node and the leaf nodes it refers to. Each branch node entry corresponds to the biggest value in the respective leaf node. Take the first leaf node as an example: the biggest value in this node is 46, which is thus stored in the corresponding branch node entry. The same is true for the other leaf nodes so that in the end the branch node has the values 46, 53, 57 and 83. According to this scheme, a branch layer is built up until all the leaf nodes are covered by a branch node.\n\n#### If you like this page, you might also like …\n\n… to [subscribe my **mailing lists**](https://winand.at/lists), [get **free stickers**](https://use-the-index-luke.com/shop), [buy **my book**](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=sec-tree&utm_medium=web) or [join a **training**](https://winand.at/sql-training/open-online-class).\n\nThe next layer is built similarly, but on top of the first branch node level. The procedure repeats until all keys fit into a single node, the *root node*. The structure is a *balanced search tree* because the tree depth is equal at every position; the distance between root node and leaf nodes is the same everywhere.\n\n#### Note\n\nA B-tree is a balanced tree—not a binary tree.\n\nOnce created, the database maintains the index automatically. It applies every `insert`, `delete` and `update` to the index and keeps the tree in balance, thus causing maintenance overhead for write operations. [Chapter 8, “*Modifying Data*”](/sql/dml), explains this in more detail.\n\n## Figure 1.3 B-Tree Traversal\n\nFigure 1.3 shows an index fragment to illustrate a search for the key “57”. The tree traversal starts at the root node on the left-hand side. Each entry is processed in ascending order until a value is greater than or equal to (>=) the search term (57). In the figure it is the entry 83. The database follows the reference to the corresponding branch node and repeats the procedure until the tree traversal reaches a leaf node.\n\n#### Important\n\nThe B-tree enables the database to find a leaf node quickly.\n\nThe tree traversal is a very efficient operation—so efficient that I refer to it as the *first power of indexing*. It works almost instantly—even on a huge data set. That is primarily because of the tree balance, which allows accessing all elements with the same number of steps, and secondly because of the logarithmic growth of the tree depth. That means that the tree depth grows very slowly compared to the number of leaf nodes. Real world indexes with millions of records have a tree depth of four or five. A tree depth of six is hardly ever seen. The box “*Logarithmic Scalability*” describes this in more detail.\n\n## Logarithmic Scalability\n\nIn mathematics, the logarithm of a number to a given base is the power or exponent to which the base must be raised in order to produce the number [[Wikipedia](https://en.wikipedia.org/wiki/Logarithm)].\n\nIn a search tree the base corresponds to the number of entries per branch node and the exponent to the tree depth. The example index in Figure 1.2 holds up to four entries per node and has a tree depth of three. That means that the index can hold up to 64 (43) entries. If it grows by one level, it can already hold 256 entries (44). Each time a level is *added*, the maximum number of index entries *quadruples*. The logarithm reverses this function. The tree depth is therefore log4(number-of-index-entries).\n\nTree DepthIndex Entries364425651,02464,096716,384865,5369262,144101,048,576\n\nThe logarithmic growth enables the example index to search a million records with ten tree levels, but a real world index is even more efficient. The main factor that affects the tree depth, and therefore the lookup perfor­mance, is the number of entries in each tree node. This number corresponds to—mathematically speaking—the basis of the loga­rithm. The higher the basis, the shallower the tree, the faster the traversal.\n\nDatabases exploit this concept to a maximum extent and put as many entries as possible into each node—often hundreds. That means that every new index level supports a hundred times more entries.\n\n#### Links\n\n[B+tree simulator](https://www.cs.usfca.edu/~galles/visualization/BPlusTree.html)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 5590, "slov": 902, "odkazu": 62, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:43", "sha256": "92f78f81e0461113d3fc70d0c3332e81c5a11a48acd7b0ab020a4683927e27f3", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://sql-performance-explained.com/", "https://winand.at/sql-training/open-online-class", "https://en.wikipedia.org/wiki/Logarithm", "https://www.cs.usfca.edu/~galles/visualization/BPlusTree.html", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/clustering", "titulek": "Data cluster: storing related data close together", "h1": "Clustering Data", "popis": "The “clustered index” is a very powerful SQL tuning tool but often misunderstood and used wrong.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/clustering", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Data cluster: storing related data close together", "og:description": "The “clustered index” is a very powerful SQL tuning tool but often misunderstood and used wrong.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Clustering Data"}, {"uroven": 4, "text": "If you like this page, you might also like …"}, {"uroven": 2, "text": "Column Stores"}, {"uroven": 4, "text": "Note"}, {"uroven": 2, "text": "Contents"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\nClustering DataThe Second Power of Indexing\n\n---\n\nThe term *cluster* is used in various fields. A [star cluster](https://en.wikipedia.org/wiki/Star_cluster), for example, is a group of stars. A [computer cluster](https://en.wikipedia.org/wiki/Computer_cluster), on the other hand, is a group of computers that work closely together—either to solve a complex problem (high-performance computing cluster) or to increase availability (failover cluster). Generally speaking, clusters are related things that appear together.\n\nIn the field of computing there is one more type of cluster—one that is often misunderstood: the data cluster. Clustering data means to store consecutively accessed data closely together so that accessing it requires fewer IO operations. Data clusters are very important in terms of database tuning. Computer clusters, on the other hand, are also very common in a database context—thus making the term *cluster* very ambiguous. The sentence “Let’s use a cluster to improve database performance” is just one example; it might refer to a computer cluster but could also mean a data cluster. In this chapter, cluster generally refers to *data clusters*.\n\n#### If you like this page, you might also like …\n\n… to [subscribe my **mailing lists**](https://winand.at/lists), [get **free stickers**](https://use-the-index-luke.com/shop), [buy **my book**](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=ch-clustering&utm_medium=web) or [join a **training**](https://winand.at/sql-training/open-online-class).\n\nThe simplest data cluster in an SQL database is the row. Databases store all columns of a row in the same database block if possible. Exceptions apply if a row doesn’t fit into a single block—e.g., when LOB types are involved.\n\n## Column Stores\n\n[Column oriented databases](https://en.wikipedia.org/wiki/Column-oriented_DBMS), or column-stores, organize tables in a columned way. This model is beneficial when accessing many rows but only a few columns—a pattern that is very common in data warehouses (OLAP).\n\nIndexes allow one to cluster data. The basis for this was already explained in [Chapter 1, “*Anatomy of an SQL Index*”](/sql/anatomy): the index leaf nodes store the indexed columns in an ordered fashion so that similar values are stored next to each other. That means that indexes build clusters of rows with similar values. This capability to cluster data is so important that I refer to it as the *second power of indexing*.\n\n#### Note\n\nThe [B-tree traversal](/sql/anatomy/the-tree) is the first power of indexing.\n\nClustering is the second power of indexing.\n\nThe following sections explain how to use indexes to cluster data and improve query performance.\n\n## Contents\n\n1. *[Index Filter Predicates Intentionally Used](/sql/clustering/index-filter-predicates)* — to tune `LIKE`\n2. *[Index-Only Scan](/sql/clustering/index-only-scan-covering-index)* — Avoiding table access\n3. *[Index-Organized Table](/sql/clustering/index-organized-clustered-index)* — Clustered indexes without tables\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3660, "slov": 515, "odkazu": 62, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:44", "sha256": "1b7cefd64364bab08b6acd89884beec6e56825b51bff32fdfa7c26bbaf790ac2", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://en.wikipedia.org/wiki/Star_cluster", "https://en.wikipedia.org/wiki/Computer_cluster", "https://winand.at/lists", "https://sql-performance-explained.com/", "https://winand.at/sql-training/open-online-class", "https://en.wikipedia.org/wiki/Column-oriented_DBMS", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/clustering/index-filter-predicates", "titulek": "Indexing LIKE filters (as good as it gets)", "h1": "Index Filter Predicates Used Intentionally", "popis": "Index filter predicates are a quick way to identify tuning opportunities.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/clustering/index-filter-predicates", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Indexing LIKE filters (as good as it gets)", "og:description": "Index filter predicates are a quick way to identify tuning opportunities.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Clustering Data"], "osnova": [{"uroven": 1, "text": "Index Filter Predicates Used Intentionally"}, {"uroven": 4, "text": "If you like this page, you might also like …"}, {"uroven": 4, "text": "Note"}, {"uroven": 2, "text": "The Index Clustering Factor"}, {"uroven": 4, "text": "Warning"}, {"uroven": 2, "text": "Figure 5.1 Intentional Index Filter-Predicates"}, {"uroven": 4, "text": "Tip"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Index Filter Predicates Used Intentionally\n\n---\n\nVery often index [filter predicates](/sql/glossary/index-filter-predicates) indicate improper index usage caused by an incorrect column order in a concatenated index. Nevertheless index filter predicates can be used for a good reason as well—not to improve range scan performance but to group consecutively accessed data together.\n\n`Where` clause predicates that cannot serve as access predicate are good candidates for this technique:\n\n```\nSELECT first_name, last_name, subsidiary_id, phone_number\n FROM employees\n WHERE subsidiary_id = ?\n AND UPPER(last_name) LIKE '%INA%'\n```\n\nRemember that `LIKE` expressions with leading wildcards [cannot use the index tree](/sql/where-clause/searching-for-ranges/like-performance-tuning). That means that indexing `LAST_NAME` doesn’t narrow the scanned index range—no matter if you index `LAST_NAME` or `UPPER(last_name)`. This condition is therefore no good candidate for indexing.\n\n#### If you like this page, you might also like …\n\n… to [subscribe my **mailing lists**](https://winand.at/lists), [get **free stickers**](https://use-the-index-luke.com/shop), [buy **my book**](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=sec-intentional-index-filter&utm_medium=web) or [join a **training**](https://winand.at/sql-training/open-online-class).\n\nHowever the condition on `SUBSIDIARY_ID` is well suited for indexing. We don’t even need to add a new index because the `SUBSIDIARY_ID` is already the leading column in the index for the primary key.\n\nDb2 (LUW)`Explain Plan\n------------------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 40\n 2 | FETCH EMPLOYEES | 33 of 333 ( 9.91%) | 40\n 3 | RIDSCN | 333 of 333 (100.00%) | 12\n 4 | SORT (UNIQUE) | 333 of 333 (100.00%) | 12\n 5 | IXSCAN EMPLOYEES_PK | 333 of 10000 ( 3.33%) | 12\n\nPredicate Information\n 2 - SARG (Q1.SUBSIDIARY_ID = ?)\n SARG ( UPPER(Q1.LAST_NAME) LIKE '%INA%')\n 5 - START (Q1.SUBSIDIARY_ID = ?)\n STOP (Q1.SUBSIDIARY_ID = ?)`Oracle`---------------------------------------------------------------\n|Id | Operation | Name | Rows | Cost |\n---------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 17 | 230 |\n|*1 | TABLE ACCESS BY INDEX ROWID| EMPLOYEES | 17 | **230** |\n|*2 | INDEX RANGE SCAN | EMPLOYEEs_PK| 333 | **2** |\n---------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 1 - filter(UPPER(\"LAST_NAME\") LIKE '%INA%')\n 2 - access(\"SUBSIDIARY_ID\"=TO_NUMBER(:A))`\n\nIn the above execution plan, the cost value raises a hundred times from the `INDEX RANGE SCAN` to the subsequent `TABLE ACCESS BY INDEX ROWID` operation. In other words: the table access causes the most work. It is actually a common pattern and is not a problem by itself. Nevertheless, it is the most significant contributor to the overall execution time of this query.\n\nThe table access is not necessarily a bottleneck if the accessed rows are stored in a single table block because the database can fetch all rows with a single read operation. If the same rows are spread across many different blocks, in contrast, the table access can become a serious performance problem because the database has to fetch many blocks in order to retrieve all the rows. That means the performance depends on the physical distribution of the accessed rows—in other words: it depends on the clustering of rows.\n\n#### Note\n\nThe correlation between index order and table order is a performance benchmark—the so-called *index clustering factor*.\n\nIt is in fact possible to improve query performance by re-ordering the rows in the table so they correspond to the index order. This method is, however, rarely applicable because you can only store the table rows in one sequence. That means you can optimize the table for one index only. Even if you can choose a single index for which you would like to optimize the table, it is still a difficult task because most databases only offer rudimentary tools for this task. So-called *row sequencing* is, after all, a rather impractical approach.\n\n## The Index Clustering Factor\n\nThe index clustering factor is an indirect measure of the probability that two succeeding index entries refer to the same table block. The optimizer takes this probability into account when calculating the cost value of the `TABLE ACCESS BY INDEX ROWID` operation.\n\nThis is exactly where the *second power of indexing*—clustering data—comes in. You can add many columns to an index so that they are automatically stored in a well defined order. That makes an index a powerful yet simple tool for clustering data.\n\nTo apply this concept to the above query, we must extend the index to cover all columns from the `where` clause—even if they do not narrow the scanned index range:\n\n```\nCREATE INDEX empsubupnam ON employees\n (subsidiary_id, UPPER(last_name))\n```\n\nThe column `SUBSIDIARY_ID` is the first index column so it can be used as an access predicate. The expression `UPPER(last_name)` covers the `LIKE` filter as *index filter predicate*. Indexing the uppercase representation saves a few CPU cycles during execution, but a straight index on `LAST_NAME` would work as well. You’ll find more about this in the next section.\n\nDb2 (LUW)`Explain Plan\n--------------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 15\n 2 | FETCH EMPLOYEES | 0 of 0 | 15\n 3 | IXSCAN EMPSUBUPNAM2 | 0 of 10000 ( .00%) | 15\n\nPredicate Information\n 3 - START (Q1.SUBSIDIARY_ID = ?)\n STOP (Q1.SUBSIDIARY_ID = ?)\n SARG (Q1.LAST_NAME LIKE '%INA%')`To get the desired execution plan, I had to remove the `UPPER` from the index and the `where`-clause. As of Db2 (LUW) 10.5, function based indexing is a pretty fresh feature—it seems that the optimizer is not yet fully aware of it. Further, using appropriate collations to get case-insensitive behaviour is anyway the better option in Db2.Oracle`--------------------------------------------------------------\n|Id | Operation | Name | Rows | Cost |\n--------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 17 | 20 |\n| 1 | TABLE ACCESS BY INDEX ROWID| EMPLOYEES | 17 | 20 |\n|*2 | INDEX RANGE SCAN | EMPSUBUPNAM| 17 | 3 |\n--------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 2 - access(\"SUBSIDIARY_ID\"=TO_NUMBER(:A))\n filter(UPPER(\"LAST_NAME\") LIKE '%INA%')`\n\nThe new execution plan shows the very same operations as before. The cost value dropped considerably nonetheless. In the predicate information we can see that the `LIKE` filter is already applied during the `INDEX RANGE SCAN`. Rows that do not fulfill the `LIKE` filter are immediately discarded. The table access does not have any filter predicates anymore. That means it does not load rows that do not fulfill the `where` clause.\n\nThe difference between the two execution plans is clearly visible in the “Rows” column. According to the optimizer’s estimate, the query ultimately matches 17 records. The index scan in the first execution plan delivers 333 rows nevertheless. The database must then load these 333 rows from the table to apply the `LIKE` filter which reduces the result to 17 rows. In the second execution plan, the index access does not deliver those rows in the first place so the database needs to execute the `TABLE ACCESS BY INDEX ROWID` operation only 17 times.\n\nYou should also note that the cost value of the `INDEX RANGE SCAN` operation grew from two to three because the additional column makes the index bigger. In view of the performance gain, it is an acceptable compromise.\n\n#### Warning\n\nDon’t introduce a new index for the sole purpose of filter predicates. Extend an existing index instead and keep the [maintenance effort](/sql/dml) low. With some databases you can even add columns to the index for the primary key that are not part of the primary key.\n\nThe following animation demonstrates the difference between the two execution plans:\n\nFigure 5.1 Intentional Index Filter-Predicates\n\nThis trivial example seems to confirm the common wisdom to index every column from the `where` clause. This “wisdom”, however, ignores the relevance of the column order which determines what conditions can be used as access predicates and thus has a huge impact on performance. The decision about column order should therefore never be left to chance.\n\nThe index size grows with the number of columns as well—especially when adding text columns. Of course the performance does not get better for a bigger index even though the [logarithmic scalability](/sql/anatomy/the-tree#sb-log) limits the impact considerably. You should by no means add all columns that are mentioned in the `where` clause to an index but instead only use index filter predicates intentionally to reduce the data volume during an earlier execution step.\n\n#### Tip\n\n- Glossary: [Index filter predicates](/sql/glossary/index-filter-predicates)\n- [Index access and filter predicates explained by example](/sql/where-clause/searching-for-ranges/greater-less-between-tuning-sql-access-filter-predicates)\n- [The impact of accidental index filter predicates demonstrated](/sql/testing-scalability/data-volume)\n- [Why “anywhere” `LIKE` searches aren’t access predicates](/sql/where-clause/searching-for-ranges/like-performance-tuning)\n- Spotting index filter predicates in [Oracle](/sql/explain-plan/oracle/filter-predicates), [PostgreSQL](/sql/explain-plan/postgresql/filter-predicates) and [SQL Server](/sql/explain-plan/oracle/filter-predicates) execution plans.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 9546, "slov": 1442, "odkazu": 65, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:45", "sha256": "c5ded3db9059d2a9d4adb2bae6b126411c594e78e6c42c473e0ec0701630f85b", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://sql-performance-explained.com/", "https://winand.at/sql-training/open-online-class", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/clustering/index-only-scan-covering-index", "titulek": "Covering index: an index containing all queried columns", "h1": "Index-Only Scan: Avoiding Table Access", "popis": "The index-only scan is one of the most important SQL tuning techniques at all—often bringing factors!", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/clustering/index-only-scan-covering-index", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Covering index: an index containing all queried columns", "og:description": "The index-only scan is one of the most important SQL tuning techniques at all—often bringing factors!", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Clustering Data"], "osnova": [{"uroven": 1, "text": "Index-Only Scan: Avoiding Table Access"}, {"uroven": 4, "text": "If you like this page, you might also like …"}, {"uroven": 4, "text": "Note"}, {"uroven": 4, "text": "Important"}, {"uroven": 4, "text": "Warning"}, {"uroven": 4, "text": "Note"}, {"uroven": 4, "text": "Tip"}, {"uroven": 4, "text": "Tip"}, {"uroven": 4, "text": "Tip"}, {"uroven": 2, "text": "INCLUDE: Non-key Columns"}, {"uroven": 4, "text": "Think About It"}, {"uroven": 2, "text": "About the Author"}, {"uroven": 2, "text": "Footnotes"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Index-Only Scan: Avoiding Table Access\n\n---\n\nThe index-only scan is one of the most powerful tuning methods of all. It not only avoids accessing the table to evaluate the `where` clause, but avoids accessing the table completely if the database can find the selected columns in the index itself.\n\nTo cover an entire query, an index must contain *all* columns from the SQL statement—in particular also the columns from the `select` clause as shown in the following example:\n\n```\nCREATE INDEX sales_sub_eur\n ON sales\n ( subsidiary_id, eur_value )\n```\n\n```\nSELECT SUM(eur_value)\n FROM sales\n WHERE subsidiary_id = ?\n```\n\nOf course indexing the `where` clause takes precedence over the other clauses. The column `SUBSIDIARY_ID` is therefore in the first position so it qualifies as an [access predicate](/sql/glossary/index-filter-predicates).\n\n#### If you like this page, you might also like …\n\n… to [subscribe my **mailing lists**](https://winand.at/lists), [get **free stickers**](https://use-the-index-luke.com/shop), [buy **my book**](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=sec-index-only-scan&utm_medium=web) or [join a **training**](https://winand.at/sql-training/open-online-class).\n\nThe execution plan shows the index scan without a subsequent table access (`TABLE ACCESS BY INDEX ROWID`).\n\nDb2 (LUW)`Explain Plan\n---------------------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 21\n 2 | GRPBY (COMPLETE) | 1 of 34804 ( .00%) | 21\n 3 | IXSCAN SALES_SUB_EUR | 34804 of 1009326 ( 3.45%) | 19\n\nPredicate Information\n 3 - START (Q1.SUBSIDIARY_ID = ?)\n STOP (Q1.SUBSIDIARY_ID = ?)`Oracle`----------------------------------------------------------\n| Id | Operation | Name | Rows | Cost |\n----------------------------------------------------------\n| 0 | SELECT STATEMENT | | 1 | 104 |\n| 1 | SORT AGGREGATE | | 1 | |\n|* 2 | INDEX RANGE SCAN| SALES_SUB_EUR | 40388 | 104 |\n----------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 2 - access(\"SUBSIDIARY_ID\"=TO_NUMBER(:A))`\n\nThe index covers the entire query so it is also called a *covering index*.\n\n#### Note\n\nIf an index prevents a table access it is also called a *covering index*.\n\nThe term is misleading, however, because it sounds like an index property. The phrase index-only scan correctly suggests that it is an execution plan operation.\n\nThe index has a copy of the `EUR_VALUE` column so the database can use the value stored in the index. Accessing the table is not required because the index has all of the information to satisfy the query.\n\nAn index-only scan can improve performance enormously. Just look at the row count estimate in the execution plan: the optimizer expects to aggregate more than 40,000 rows. That means that the index-only scan prevents 40,000 table fetches—if each row is in a different table block. If the index has a good [clustering factor](/sql/clustering/index-filter-predicates#sb-clustering-factor)—that is, if the respective rows are well clustered in a few table blocks—the advantage may be significantly lower.\n\nBesides the clustering factor, the number of selected rows limits the potential performance gain of an index-only scan. If you select a single row, for example, you can only save a single table access. Considering that the [tree traversal](/sql/anatomy/the-tree) needs to fetch a few blocks as well, the saved table access might become negligible.\n\n#### Important\n\nThe performance advantage of an index-only scans depends on the number of accessed rows and the index clustering factor.\n\nThe index-only scan is an aggressive indexing strategy. Do not design an index for an index-only scan on suspicion only because it unnecessarily uses memory and increases the maintenance effort needed for `update` statements. See [Chapter 8, “*Modifying Data*”](/sql/dml). In practice, you should first index without considering the `select` clause and only extend the index if needed.\n\nIndex-only scans can also cause unpleasant surprises, for example if we limit the query to recent sales:\n\n```\nSELECT SUM(eur_value)\n FROM sales\n WHERE subsidiary_id = ?\n AND sale_date > ?\n```\n\nWithout looking at the execution plan, one could expect the query to run faster because it selects fewer rows. The `where` clause, however, refers to a column that is not in the index so that the database must access the table to load this column.\n\nDb2 (LUW)`Explain Plan\n-------------------------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 13547\n 2 | GRPBY (COMPLETE) | 1 of 1223 ( .08%) | 13547\n 3 | **FETCH SALES** | 1223 of 34804 ( 3.51%) | 13547\n 4 | RIDSCN | 34804 of 34804 (100.00%) | 32\n 5 | SORT (UNIQUE) | 34804 of 34804 (100.00%) | 32\n 6 | IXSCAN SALES_SUB_EUR | 34804 of 1009326 ( 3.45%) | 19\n\nPredicate Information\n 3 - SARG (? < Q1.SALE_DATE)\n SARG (Q1.SUBSIDIARY_ID = ?)\n 6 - START (Q1.SUBSIDIARY_ID = ?)\n STOP (Q1.SUBSIDIARY_ID = ?)`Oracle`--------------------------------------------------------------\n|Id | Operation | Name | Rows |Cost |\n--------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 1 | 371 |\n| 1 | SORT AGGREGATE | | 1 | |\n|*2 | **TABLE ACCESS BY INDEX ROWID**| SALES | 2019 | 371 |\n|*3 | INDEX RANGE SCAN | SALES_DATE| 10541 | 30 |\n--------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 2 - filter(\"SUBSIDIARY_ID\"=TO_NUMBER(:A))\n 3 - access(\"SALE_DATE\">:B)`\n\nThe table access increases the response time although the query selects fewer rows. The relevant factor is not how many rows the query delivers but how many rows the database must inspect to find them.\n\n#### Warning\n\nExtending the `where` clause can cause “illogical” performance behavior. Check the execution plan before extending queries.\n\nIf an index can no longer be used for an index-only scan, the optimizer will choose the next best execution plan. That means the optimizer might select an entirely different execution plan or, as above, a similar execution plan with another index. In this case it uses an index on `SALE_DATE`, which is a leftover from the [previous chapter](/sql/join/hash-join-partial-objects).\n\nFrom the optimizer’s perspective, this index has two advantages over `SALES_SUB_EUR`. The optimizer believes that the filter on `SALE_DATE` is more selective than the one on `SUBSIDIARY_ID`. You can see that in the respective “Rows” column of the last two execution plans (about 10,000 versus 40,000). These estimations are, however, purely arbitrary because the query uses [bind parameters](/sql/where-clause/bind-parameters). The `SALE_DATE` condition could, for example, select the entire table when providing the date of the first sale.\n\nThe second advantage of the `SALES_DATE` index is that is has a better clustering factor. This is a valid reason because the `SALES` table only grows chronologically. New rows are always appended to the end of the table as long as there are no rows deleted. The table order therefore corresponds to the index order because both are roughly sorted chronologically—the index has a good clustering factor.\n\nWhen using an index with a good clustering factor, the selected tables rows are stored closely together so that the database only needs to read a few table blocks to get all the rows. Using this index, the query might be fast enough without an index-only scan. In this case we should remove the unneeded columns from the other index again.\n\n#### Note\n\nSome indexes have a good clustering factor automatically so that the performance advantage of an index-only scan is minimal.\n\nIn this particular example, there was a happy coincidence. The new filter on `SALE_DATE` not only prevented an index-only scan but also opened a new access path at the same time. The optimizer was therefore able to limit the performance impact of this change. It is, however, also possible to prevent an index only scan by adding columns to other clauses. However adding a column to the `select` clause can never open a new access path which could limit the impact of losing the index-only scan.\n\n#### Tip\n\nMaintain your index-only scans.\n\nAdd comments that remind you about an index-only scan and refer to that page so anyone can read about it.\n\n[Function-based indexes](/sql/where-clause/functions/case-insensitive-search) can also cause unpleasant surprises in connection with index-only scans. An index on `UPPER(last_name)` cannot be used for an index-only scan when selecting the `LAST_NAME` column. In the [previous section](/sql/clustering/index-filter-predicates) we should have indexed the `LAST_NAME` column itself to support the `LIKE` filter and allow it to be used for an index-only scan when selecting the `LAST_NAME` column.\n\n#### Tip\n\nAlways aim to index the original data as that is often the most useful information you can put into an index.\n\nAvoid function-based indexing for expressions that cannot be used as access predicates.\n\nAggregating queries like the one shown above make good candidates for index-only scans. They query many rows but only a few columns, making a slim index sufficient for supporting an index-only scan. The more columns you query, the more columns you have to add to the indexed to support an index-only scan. As a developer you should therefore only select the columns you really need.\n\n#### Tip\n\nAvoid `select *` and fetch only the columns you need.\n\nRegardless of the fact that indexing many rows needs a lot of space, you can also reach the limits of your database. Most databases impose rather rigid limits on the number of columns per index and the total size of an index entry. That means you cannot index an arbitrary number of columns nor arbitrarily long columns. The following overview lists the most important limitations. Nevertheless there are indexes that cover an entire table as we see in the next section.\n\n## `INCLUDE`: Non-key Columns\n\nSQL Server and PostgreSQL 11+ support so-called non-key columns in B-tree indexes. They are—other than the key columns, which we discussed so far—only stored in the leaf nodes and can thus not be used for access predicates.\n\nNon-key columns are specified in the `include` clause:\n\n```\n CREATE INDEX empsubupnam\n ON employees\n (subsidiary_id, last_name)\nINCLUDE(phone_number, first_name)\n```\n\nDb2 (LUW)Db2 (LUW) [limits an index to 64 column with a maximum key length of 25% of the page size.](https://www.ibm.com/docs/en/db2/11.5.x?topic=indexes-designing)Db2 also supports the [`INCLUDE` clause](https://www.ibm.com/docs/en/db2-for-zos/12.0.0?topic=SSEPEK_12.0.0/sqlref/src/tpc/db2z_sql_createindex.htm:/www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.admin.dbobj.doc/doc/t0020190.htm) to add non-key columns to *unique* indexes. This allows you to extend an unique index with additional columns so that the index can be used for an index-only scan without changing semantics of the uniqueness.MySQLMySQL with InnoDB limits the total key length (all columns) to 3072 bytes. Further, the length of each columns is [limited to 767 bytes if `innodb_large_prefix` is not enabled or row formats other than `DYNAMIC` or `COMPRESSED` are used](https://dev.mysql.com/doc/refman/9.7/en/innodb-parameters.html#sysvar_innodb_large_prefix). This was default up to and including MySQL 5.6. MyISAM indexes are limited to [16 columns and a maximum key length of 1000 bytes](https://dev.mysql.com/doc/refman/8.0/en/myisam-storage-engine.html).MySQL has a unique feature called “prefix indexing” (sometimes also called “partial indexing”). This means indexing only the first few characters of a column—so it has nothing to do with the partial indexes described in [Chapter 2](/sql/where-clause). If you index a column that exceeds the allowed column length (767, 1000 or 3072 bytes as described above), MySQL might—depending on the [SQL mode](https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sql-mode-strict) and [row format](https://dev.mysql.com/doc/refman/9.7/en/innodb-parameters.html#sysvar_innodb_large_prefix)—truncate the column accordingly. In this case, the `create index` statement succeeds with the warning “Specified key was too long; max key length is … bytes”. That means that the index doesn’t have a full copy of this column anymore—selecting the column prevents an index-only scan (similar to function-based indexes).You can use MySQL’s prefix indexing explicitly to prevent exceeding the total key length limit if you get the error message “Specified key was too long; max key length is … bytes.” The following example only indexes the first ten characters of the `LAST_NAME` column.`CREATE INDEX .. ON employees (**last_name(10)**)`OracleThe maximum index key length depends on the block size and the index storage parameters ([75% of the database block size minus some overhead](https://docs.oracle.com/en/database/oracle/oracle-database/19/refrn/logical-database-limits.html)). A B-tree index is limited to 32 columns.When using Oracle 11*g* with all defaults in place (8k blocks), the maximum index key length is 6398 bytes. Exceeding this limit causes the error message “ORA-01450: maximum key length (6398) exceeded.”PostgreSQLThe PostgreSQL database supports index-only scans since [release 9.2](https://www.depesz.com/2011/10/08/waiting-for-9-2-index-only-scans/).The length of B-tree entries is limited to 2713 bytes (hardcoded, approx. `BLCKSZ/3`). The respective error message “*index row size ... exceeds btree maximum, 2713*” appears only when executing an `insert` or `update` that exceeds the limit. B-tree indexes can contain up to [32 columns](https://www.postgresql.org/docs/current/indexes-multicolumn.html).SQL Server[Since version 2016, SQL Server supports up to 32 key columns with up to 1700 Bytes (900 Bytes for clustered indexes).](https://learn.microsoft.com/en-us/sql/sql-server/maximum-capacity-specifications-for-sql-server)0 Non-key columns do not account towards this limit.\n\n#### Think About It\n\nQueries that do not select any table columns are often executed with index-only scans.\n\nCan you think of a meaningful example?\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).\n\n## Footnotes\n\n1. 0 Before SQL Server 2016: 16 columns and 900 bytes.", "znaku_textu": 14045, "slov": 2139, "odkazu": 73, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:46", "sha256": "08d3fd30c8700760109bc87614b3f008f826702305b5504a0af5e20d84e80175", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://sql-performance-explained.com/", "https://winand.at/sql-training/open-online-class", "https://www.ibm.com/docs/en/db2/11.5.x?topic=indexes-designing", "https://www.ibm.com/docs/en/db2-for-zos/12.0.0?topic=SSEPEK_12.0.0%2Fsqlref%2Fsrc%2Ftpc%2Fdb2z_sql_createindex.htm%3A%2Fwww.ibm.com%2Fsupport%2Fknowledgecenter%2Fen%2FSSEPGG_11.1.0%2Fcom.ibm.db2.luw.admin.dbobj.doc%2Fdoc%2Ft0020190.htm", "https://dev.mysql.com/doc/refman/9.7/en/innodb-parameters.html", "https://dev.mysql.com/doc/refman/8.0/en/myisam-storage-engine.html", "https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html", "https://docs.oracle.com/en/database/oracle/oracle-database/19/refrn/logical-database-limits.html", "https://www.depesz.com/2011/10/08/waiting-for-9-2-index-only-scans/", "https://www.postgresql.org/docs/current/indexes-multicolumn.html", "https://learn.microsoft.com/en-us/sql/sql-server/maximum-capacity-specifications-for-sql-server", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/clustering/index-organized-clustered-index", "titulek": "Clustered indexes are index-organized tables", "h1": "Index-Organized Tables and Clustered Indexes", "popis": "Clustered indexes are a very important in SQL Server and MySQL/InnoDB. But they come with a penalty.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/clustering/index-organized-clustered-index", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Clustered indexes are index-organized tables", "og:description": "Clustered indexes are a very important in SQL Server and MySQL/InnoDB. But they come with a penalty.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Clustering Data"], "osnova": [{"uroven": 1, "text": "Index-Organized Tables and Clustered Indexes"}, {"uroven": 4, "text": "If you like this page, you might also like …"}, {"uroven": 2, "text": "Figure 5.2 Index-Based Access on a Heap Table"}, {"uroven": 2, "text": "Why Secondary Indexes have no ROWID"}, {"uroven": 2, "text": "Figure 5.3 Secondary Index on an IOT"}, {"uroven": 4, "text": "Important"}, {"uroven": 4, "text": "Important"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Index-Organized Tables and Clustered Indexes\n\n---\n\nThe [index-only scan](/sql/clustering/index-only-scan-covering-index) executes an SQL statement using only the redundant data stored in the index. The original data in the [heap table](/sql/glossary/heap-table) is not needed. If we take that concept to the next level and put all columns into the index, you may wonder why we need the heap table.\n\nSome databases can indeed use an index as primary table store. The Oracle database calls this concept *index-organized tables (IOT)*, other databases use the term *clustered index*. In this section, both terms are used to either put the emphasis on the table or the index characteristics as needed.\n\nAn index-organized table is thus a B-tree index without a heap table. This results in two benefits: (1) it saves the space for the heap structure; (2) every access on a clustered index is automatically an index-only scan. Both benefits sound promising but are hardly achievable in practice.\n\n#### If you like this page, you might also like …\n\n… to [subscribe my **mailing lists**](https://winand.at/lists), [get **free stickers**](https://use-the-index-luke.com/shop), [buy **my book**](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=sec-index-organized-table&utm_medium=web) or [join a **training**](https://winand.at/sql-training/open-online-class).\n\nThe drawbacks of an index-organized table become apparent when creating another index on the same table. Analogous to a regular index, a so-called *secondary index* refers to the original table data—which is stored in the clustered index. There, the data is not stored statically as in a heap table but can move at any time to maintain the index order. It is therefore not possible to store the physical location of the rows in the index-organized table in the secondary index. The database must use a logical key instead.\n\nThe following figures show an index lookup for finding all sales on May 23rd 2012. For comparison, we will first look at Figure 5.2 that shows the process when using a heap table. The execution involves two steps: (1) the `INDEX RANGE SCAN`; (2) the `TABLE ACCESS BY INDEX ROWID`.\n\nFigure 5.2 Index-Based Access on a Heap Table\n\nAlthough the table access might become a bottleneck, it is still limited to one read operation per row because the index has the `ROWID` as a direct pointer to the table row. The database can immediately load the row from the heap table because the index has its exact position. The picture changes, however, when using a secondary index on an index-organized table. A secondary index does not store a physical pointer (`ROWID`) but only the key values of the clustered index—the so-called *clustering key*. Often that is the primary key of the index-organized table.\n\n## Why Secondary Indexes have no `ROWID`\n\nA direct pointer to the table row would be desirable for a secondary index as well. But that is only possible, if the table row stays at fixed storage positions. That is, unfortunately, not possible if the row is part of an index structure, which is kept in order. Keeping the index order needs to move rows occasionally. This is also true for operations that do not affect the row itself. An `insert` statement, for example, might split a leaf node to gain space for the new entry. That means that some entries are moved to a new data block at a different place.\n\nA heap table, on the other hand, doesn’t keep the rows in any order. The database saves new entries wherever it finds enough space. Once written, data doesn’t move in heap tables.\n\nAccessing a secondary index does not deliver a `ROWID` but a logical key for searching the clustered index. A single access, however, is not sufficient for searching clustered index—it requires a full tree traversal. That means that accessing a table via a secondary index searches two indexes: the secondary index once (`INDEX RANGE SCAN`), then the clustered index *for each row* found in the secondary index (`INDEX UNIQUE SCAN`).Figure 5.3 Secondary Index on an IOT\n\nFigure 5.3 makes it clear, that the B-tree of the clustered index stands between the secondary index and the table data.\n\nAccessing an index-organized table via a secondary index is very inefficient, and it can be prevented in the same way one prevents a table access on a heap table: by using an [index-only scan](/sql/clustering/index-only-scan-covering-index)—in this case better described as “secondary-index-only scan”. The performance advantage of an index-only scan is even bigger because it not only prevents a single access but an entire `INDEX UNIQUE SCAN`.\n\n#### Important\n\nAccessing an index-organized table via a secondary index is very inefficient.\n\nUsing this example we can also see that databases exploit all the redundancies they have. Bear in mind that a secondary index stores the clustering key for each index entry. Consequently, we can query the clustering key from a secondary index without accessing the index-organized table:\n\n```\nSELECT sale_id\n FROM sales_iot\n WHERE sale_date = ?\n```\n\n```\n-------------------------------------------------\n| Id | Operation | Name | Cost |\n-------------------------------------------------\n| 0 | SELECT STATEMENT | | 4 |\n|* 1 | INDEX RANGE SCAN| SALES_IOT_DATE | 4 |\n-------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 1 - access(\"SALE_DATE\"=:DT)\n```\n\nThe table `SALES_IOT` is an index-organized table that uses `SALE_ID` as clustering key. Although the index `SALE_IOT_DATE` is on the `SALE_DATE` column only, it still has a copy of the clustering key `SALE_ID` so it can satisfy the query using the secondary index only.\n\nWhen selecting other columns, the database has to run an `INDEX UNIQUE SCAN` on the clustered index for each row:\n\n```\nSELECT eur_value\n FROM sales_iot\n WHERE sale_date = ?\n```\n\n```\n---------------------------------------------------\n| Id | Operation | Name | Cost |\n---------------------------------------------------\n| 0 | SELECT STATEMENT | | 13 |\n|* 1 | INDEX UNIQUE SCAN| SALES_IOT_PK | 13 |\n|* 2 | INDEX RANGE SCAN| SALES_IOT_DATE | 4 |\n---------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 1 - access(\"SALE_DATE\"=:DT)\n 2 - access(\"SALE_DATE\"=:DT)\n```\n\nIndex-organized tables and clustered indexes are, after all, not as useful as it seems at first sight. Performance improvements on the clustered index are easily lost on when using a secondary index. The clustering key is usually longer than a `ROWID` so that the secondary indexes are larger than they would be on a heap table, often eliminating the savings from the omission of the heap table. The strength of index-organized tables and clustered indexes is mostly limited to tables that do not need a second index. Heap tables have the benefit of providing a stationary master copy that can be easily referenced.\n\n#### Important\n\nTables with one index only are best implemented as clustered indexes or index-organized tables.\n\nTables with more indexes can often benefit from heap tables. You can still use index-only scans to avoid the table access. This gives you the `select` performance of a clustered index without slowing down other indexes.\n\nDatabase support for index-organized tables and clustered index is very inconsistent. The following overview explains the most important specifics.\n\nDb2 (LUW)Db2 doesn’t have index-organized tables but uses the term “clustered index“ for a different feature. It uses a heap table, but tries to `insert` new rows in the same block as nearby rows in the index.MySQLThe MyISAM engine only uses heap tables while the InnoDB engine always uses clustered indexes. That means you do not directly have a choice.OracleThe Oracle database uses heap tables by default. Index-organized tables can be created using the `ORGANIZATION INDEX` clause:`CREATE TABLE (\n id NUMBER NOT NULL **PRIMARY KEY**,\n [...]\n) **ORGANIZATION INDEX**`The Oracle database always uses the primary key as the clustering key.PostgreSQLPostgreSQL only uses heap tables.You can, however, use the [`CLUSTER` clause to align the contents of the heap table with an index](https://www.postgresql.org/docs/current/sql-cluster.html).SQL ServerBy default SQL Server uses clustered indexes (index-organized tables) using the primary key as clustering key. Nevertheless you can use arbitrary columns for the clustering key—[even non-unique columns](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms177484(v=sql.105)).To create a heap table you must use the `NONCLUSTERED` clause in the primary key definition:`CREATE TABLE (\n id NUMBER NOT NULL,\n [...]\n CONSTRAINT pk PRIMARY KEY **NONCLUSTERED** (id)\n)`Dropping a clustered index transforms the table into a heap table.SQL Server’s default behavior often causes performance problems when using secondary indexes.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 9087, "slov": 1446, "odkazu": 62, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:47", "sha256": "92efde0cb35e8d543a8456b337b0ff951abb64a546a219fefe574ea95b21b66a", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://sql-performance-explained.com/", "https://winand.at/sql-training/open-online-class", "https://www.postgresql.org/docs/current/sql-cluster.html", "https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms177484(v=sql.105)", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/dml", "titulek": "Drawbacks of indexes: write slowdown", "h1": "Modifying Data", "popis": "Proper indexes can improve query speed hundredfold. But indexes don’t come for free.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/dml", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Drawbacks of indexes: write slowdown", "og:description": "Proper indexes can improve query speed hundredfold. But indexes don’t come for free.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Modifying Data"}, {"uroven": 2, "text": "Contents"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Modifying Data\n\n---\n\nSo far we have only discussed query performance, but SQL is not only about queries. It supports data manipulation as well. The respective commands—`insert`, `delete`, and `update`—form the so-called “data manipulation language” (DML)—a section of the SQL standard. The performance of these commands is for the most part negatively influenced by indexes.\n\nAn index is pure redundancy. It contains only data that is also stored in the table. During write operations, the database must keep those redundancies consistent. Specifically, it means that `insert`, `delete` and `update` not only affect the table but also the indexes that hold a copy of the affected data.\n\n## Contents\n\n1. *[Insert](/sql/dml/insert)* — cannot take direct benefit from indexes\n2. *[Delete](/sql/dml/delete)* — uses indexes for the `where` clause\n3. *[Update](/sql/dml/update)* — does not affect all indexes of the table\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1543, "slov": 220, "odkazu": 55, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:48", "sha256": "c1d299a2781950c350db2e8058efc23af96cdcc312962c1e6e626f6e1b3f72d9", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/dml/delete", "titulek": "More indexes, slower DELETE", "h1": "Delete", "popis": "The more indexes you add to a table, the slower DELETE becomes. Exception: PostgreSQL due to its MVCC approach.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/dml/delete", "jazyk": "en", "robots_meta": "", "og": {"og:title": "More indexes, slower DELETE", "og:description": "The more indexes you add to a table, the slower DELETE becomes. Exception: PostgreSQL due to its MVCC approach.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Modifying Data"], "osnova": [{"uroven": 1, "text": "Delete"}, {"uroven": 2, "text": "Figure 8.2 Delete Performance by Number of Indexes"}, {"uroven": 4, "text": "Tip"}, {"uroven": 2, "text": "Side Effects of MVCC"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Delete\n\n---\n\nUnlike the `insert` statement, the `delete` statement has a `where` clause that can use all the methods described in [Chapter 2, “*The Where Clause*”](/sql/where-clause), to benefit directly from indexes. In fact, the `delete` statement works like a `select` that is followed by an extra step to delete the identified rows.\n\nThe actual deletion of a row is a similar process to inserting a new one—especially the removal of the references from the indexes and the activities to keep the index trees in balance. The performance chart shown in Figure 8.2 is therefore very similar to the one [shown for `insert`](/sql/dml/insert).\n\nFigure 8.2 Delete Performance by Number of Indexes\n\nIn theory, we would expect the best `delete` performance for a table without any indexes—as it is for `insert`. If there is no index, however, the database must read the full table to find the rows to be deleted. That means deleting the row would be fast but finding would be very slow. This case is therefore not shown in Figure 8.2.\n\nNevertheless it can make sense to execute a `delete` statement without an index just as it can make sense to execute a `select` statement without an index if it returns a large part of the table.\n\n#### Tip\n\nEven `delete` and `update` statements have an [execution plan](/sql/explain-plan).\n\nA `delete` statement without `where` clause is an obvious example in which the database cannot use an index, although this is a special case that has its own SQL command: `truncate table`. This command has the same effect as `delete` without `where` except that it deletes all rows in one shot. It is very fast but has two important side effects: (1) it does an implicit `commit` (exceptions: [PostgreSQL](https://www.postgresql.org/docs/current/sql-truncate.html) and SQL Server); (2) it does not execute any triggers.\n\n## Side Effects of MVCC\n\nMultiversion concurrency control (MVCC) is a database mechanism that enables non-blocking concurrent data access and a consistent transaction view. The implementations, however, differ from database to database and might even have considerable effects on performance.\n\nThe PostgreSQL database, for example, only keeps the version information (=visibility information) on the table level: deleting a row just sets the “deleted” flag in the table block. PostgreSQL’s delete performance therefore *does not* depend on the number of indexes on the table. The physical deletion of the table row and the related index maintenance is carried out only during the [VACUUM](https://www.postgresql.org/docs/current/sql-vacuum.html) process.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3194, "slov": 487, "odkazu": 57, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:49", "sha256": "8da31d113ae4b85acde48d4fec3b5341483f5118b2683a00405769a748a7e1ee", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://www.postgresql.org/docs/current/sql-truncate.html", "https://www.postgresql.org/docs/current/sql-vacuum.html", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/dml/insert", "titulek": "More indexes, slower INSERT", "h1": "Insert", "popis": "The more indexes you add, the slower INSERT becomes. Add as many as required but as few as possible.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/dml/insert", "jazyk": "en", "robots_meta": "", "og": {"og:title": "More indexes, slower INSERT", "og:description": "The more indexes you add, the slower INSERT becomes. Add as many as required but as few as possible.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Modifying Data"], "osnova": [{"uroven": 1, "text": "Insert"}, {"uroven": 4, "text": "If you like this page, you might also like …"}, {"uroven": 2, "text": "Figure 8.1 Insert Performance by Number of Indexes"}, {"uroven": 4, "text": "Note"}, {"uroven": 4, "text": "Tip"}, {"uroven": 4, "text": "Think About It"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Insert\n\n---\n\nThe number of indexes on a table is the most dominant factor for `insert` performance. The more indexes a table has, the slower the execution becomes. The `insert` statement is the only operation that cannot directly benefit from indexing because it has no `where` clause.\n\nAdding a new row to a table involves several steps. First, the database must find a place to store the row. For a regular heap table—which has no particular row order—the database can take any table block that has enough free space. This is a very simple and quick process, mostly executed in main memory. All the database has to do afterwards is to add the new entry to the respective data block.\n\nIf there are indexes on the table, the database must make sure the new entry is also found via these indexes. For this reason it has to add the new entry to each and every index on that table. The number of indexes is therefore a multiplier for the cost of an `insert` statement.\n\n#### If you like this page, you might also like …\n\n… to [subscribe my **mailing lists**](https://winand.at/lists), [get **free stickers**](https://use-the-index-luke.com/shop), [buy **my book**](https://sql-performance-explained.com/?utm_source=use-the-index-luke.com&utm_campaign=sec-insert&utm_medium=web) or [join a **training**](https://winand.at/sql-training/open-online-class).\n\nMoreover, adding an entry to an index is much more expensive than inserting one into a heap structure because the database has to keep the index order and tree balance. That means the new entry cannot be written to any block—it belongs to a specific [leaf node](/sql/anatomy/the-leaf-nodes). Although the database uses the [index tree](/sql/anatomy/the-tree) itself to find the correct leaf node, it still has to read a few index blocks for the tree traversal.\n\nOnce the correct leaf node has been identified, the database confirms that there is enough free space left in this node. If not, the database splits the leaf node and distributes the entries between the old and a new node. This process also affects the reference in the corresponding branch node as that must be duplicated as well. Needless to say, the branch node can run out of space as well so it might have to be split too. In the worst case, the database has to split all nodes up to the root node. This is the only case in which the tree gains an additional layer and grows in depth.\n\nThe index maintenance is, after all, the most expensive part of the `insert` operation. That is also visible in Figure 8.1*Insert Performance by Number of Indexes*: the execution time is hardly visible if the table does not have any indexes. Nevertheless, adding a single index is enough to increase the execute time by a factor of a hundred. Each additional index slows the execution down further.\n\n## Figure 8.1 Insert Performance by Number of Indexes\n\n#### Note\n\nThe first index makes the greatest difference.\n\nTo optimize `insert` performance, it is very important to keep the number of indexes small.\n\n#### Tip\n\nUse indexes deliberately and sparingly, and avoid redundant indexes whenever possible. This is also beneficial for `delete` and `update` statements.\n\nConsidering `insert` statements only, it would be best to avoid indexes entirely—this yields by far the best `insert` performance. However tables without indexes are rather unrealistic in real world applications. You usually want to retrieve the stored data again so that you need indexes to improve query speed. Even write-only log tables often have a primary key and a respective index.\n\nNevertheless, the performance without indexes is so good that it can make sense to temporarily drop all indexes while loading large amounts of data—provided the indexes are not needed by any other SQL statements in the meantime. This can unleash a dramatic speed-up which is visible in the chart and is, in fact, a common practice in data warehouses.\n\n#### Think About It\n\nHow would Figure 8.1 change when using an [index organized table](/sql/clustering/index-organized-clustered-index) or [clustered index](/sql/clustering/index-organized-clustered-index)?\n\nIs there any indirect way an `insert` statement could possibly benefit from indexing? That is, could an additional index make an `insert` statement faster?\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 4853, "slov": 772, "odkazu": 61, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:50", "sha256": "763cb8c9af46f0de525316e8902ca9947497240552be7ad8a721b7e559793454", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://sql-performance-explained.com/", "https://winand.at/sql-training/open-online-class", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/dml/update", "titulek": "The more columns you update, the slow it is", "h1": "Update", "popis": "UPDATE must keep all indexes in sync. Fewer indexes makes UPDATE faster. Fewer columns update also.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/dml/update", "jazyk": "en", "robots_meta": "", "og": {"og:title": "The more columns you update, the slow it is", "og:description": "UPDATE must keep all indexes in sync. Fewer indexes makes UPDATE faster. Fewer columns update also.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Modifying Data"], "osnova": [{"uroven": 1, "text": "Update"}, {"uroven": 2, "text": "Figure 8.3 Update Performance by Indexes and Column Count"}, {"uroven": 4, "text": "Think About It"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Update\n\n---\n\nAn `update` statement must relocate the changed index entries to maintain the index order. For that, the database must remove the old entry and add the new one at the new location. The response time is basically the same as for the respective `delete` and `insert` statements together.\n\nThe `update` performance, just like `insert` and `delete`, also depends on the number of indexes on the table. The only difference is that `update` statements do not necessarily affect all columns because they often modify only a few selected columns. Consequently, an `update` statement does not necessarily affect all indexes on the table but only those that contain updated columns.\n\nFigure 8.3 shows the response time for two `update` statements: one that sets all columns and affects all indexes and then a second one that updates a single column so it affects only one index.\n\nFigure 8.3 Update Performance by Indexes and Column Count\n\nThe `update` on all columns shows the same pattern we have already observed in the [previous sections](/sql/dml/insert): the response time grows with each additional index. The response time of the `update` statement that affects only one index does not increase so much because it leaves most indexes unchanged.\n\nTo optimize `update` performance, you must take care to only update those columns that were changed. This is obvious if you write the `update` statement manually. ORM tools, however, might generate `update` statements that set all columns every time. Hibernate, for example, does this when disabling the [*dynamic-update mode*](https://docs.hibernate.org/orm/6.2/userguide/html_single/#pc-managed-state-dynamic-update). Since version 4.0, this mode is enabled by default.\n\nWhen using ORM tools, it is a good practice to occasionally enable query logging in a development environment to verify the generated SQL statements. The tip entitled [“*Enabling SQL Logging*”](/sql/join/nested-loops-join-n1-problem#tip-orm-log-sql) has a short overview of how to enable SQL logging in some widely used ORM tools.\n\n#### Think About It\n\nCan you think of a case where `insert` or `delete` statements do not affect all indexes of a table?\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2786, "slov": 425, "odkazu": 57, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:51", "sha256": "173c85b87101136f3774d60b14291379f58ffec4c71280d47deca03cb50d0abc", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://docs.hibernate.org/orm/6.2/userguide/html_single/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema", "titulek": "Example Schema", "h1": "Example Schema", "popis": "CREATE & INSERT statements to create the Use The Index, Luke example database", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Schema", "og:description": "CREATE & INSERT statements to create the Use The Index, Luke example database", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": [], "osnova": [{"uroven": 1, "text": "Example Schema"}, {"uroven": 2, "text": "Contents"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Example Schema\n\n---\n\nThis appendix contains all the required `create` and `insert` statements to run the examples from the book. For the sake of didactics, the book’s main body does not always include all details for the examples.\n\n## Contents\n\n1. *[Db2 (LUW)](/sql/example-schema/db2)*\n 1. *[The `where` clause](/sql/example-schema/db2/where-clause)*\n 2. *[Testing and Scalability](/sql/example-schema/db2/performance-testing-scalability)*\n 3. *[The Join Operation](/sql/example-schema/db2/join)*\n 4. *[3-Minute Test](/sql/example-schema/db2/3-minute-quiz)*\n2. *[MySQL](/sql/example-schema/mysql)*\n 1. *[The `where` clause](/sql/example-schema/mysql/where-clause)*\n 2. *[The Join Operation](/sql/example-schema/mysql/join)*\n 3. *[Clustering Data](/sql/example-schema/mysql/clustering-data)*\n 4. *[Sorting and Grouping](/sql/example-schema/mysql/sorting-grouping)*\n 5. *[Partial Results](/sql/example-schema/mysql/partial-results)*\n 6. *[3-Minute Test](/sql/example-schema/mysql/3-minute-quiz)*\n3. *[Oracle](/sql/example-schema/oracle)*\n 1. *[The `where` clause](/sql/example-schema/oracle/where-clause)*\n 2. *[Testing and Scalability](/sql/example-schema/oracle/performance-testing-scalability)*\n 3. *[The Join Operation](/sql/example-schema/oracle/join)*\n 4. *[Clustering Data](/sql/example-schema/oracle/clustering-data)*\n 5. *[Sorting and Grouping](/sql/example-schema/oracle/sorting-grouping)*\n 6. *[Partial Results](/sql/example-schema/oracle/partial-results)*\n 7. *[Insert, Delete and Update](/sql/example-schema/oracle/dml)*\n 8. *[3-Minute Test](/sql/example-schema/oracle/3-minute-quiz)*\n4. *[PostgreSQL](/sql/example-schema/postgresql)*\n 1. *[The `where` clause](/sql/example-schema/postgresql/where-clause)*\n 2. *[Testing and Scalability](/sql/example-schema/postgresql/performance-testing-scalability)*\n 3. *[The Join Operation](/sql/example-schema/postgresql/join)*\n 4. *[Sorting and Grouping](/sql/example-schema/postgresql/sorting-grouping)*\n 5. *[Partial Results](/sql/example-schema/postgresql/partial-results)*\n 6. *[Insert, Delete and Update](/sql/example-schema/postgresql/dml)*\n 7. *[3-Minute Test](/sql/example-schema/postgresql/3-minute-quiz)*\n5. *[SQL Server](/sql/example-schema/sql-server)*\n 1. *[The `where` clause](/sql/example-schema/sql-server/where-clause)*\n 2. *[Testing and Scalability](/sql/example-schema/sql-server/performance-testing-scalability)*\n 3. *[The Join Operation](/sql/example-schema/sql-server/join)*\n 4. *[Clustering Data](/sql/example-schema/sql-server/clustering-data)*\n 5. *[Sorting and Grouping](/sql/example-schema/sql-server/sorting-grouping)*\n 6. *[Partial Results](/sql/example-schema/sql-server/partial-results)*\n 7. *[Insert, Delete and Update](/sql/example-schema/sql-server/dml)*\n 8. *[3-Minute Test](/sql/example-schema/sql-server/3-minute-quiz)*\n6. *[SQLite](/sql/example-schema/sqlite)*\n 1. *[The `where` clause](/sql/example-schema/sqlite/where-clause)*\n 2. *[The Join Operation](/sql/example-schema/sqlite/join)*\n 3. *[3-Minute Test](/sql/example-schema/sqlite/3-minute-quiz)*\n7. *[Gupta SQLBase](/sql/example-schema/sqlbase)*\n 1. *[The `where` clause](/sql/example-schema/sqlbase/where-clause)*\n 2. *[The Join Operation](/sql/example-schema/sqlbase/join)*\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3803, "slov": 374, "odkazu": 97, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:52", "sha256": "4da10ceb2313a5f8f068cd1a7a6785fe6fe5816d0510fad9253d0f371cbfe2ff", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/db2", "titulek": "Example Scripts for Db2 (LUW)", "h1": "Db2 (LUW) Example Scripts", "popis": "CREATE & INSERT statements to create the Use The Index, Luke Db2 (LUW) example database.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/db2", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Db2 (LUW)", "og:description": "CREATE & INSERT statements to create the Use The Index, Luke Db2 (LUW) example database.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema"], "osnova": [{"uroven": 1, "text": "Db2 (LUW) Example Scripts"}, {"uroven": 2, "text": "Contents"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Db2 (LUW) Example Scripts\n\n---\n\nThe scripts provided in this appendix are ready to run and were tested on Db2 (LUW) Express-C 9.7 through 11.5.\n\n## Contents\n\n1. *[The `where` clause](/sql/example-schema/db2/where-clause)*\n2. *[Testing and Scalability](/sql/example-schema/db2/performance-testing-scalability)*\n3. *[The Join Operation](/sql/example-schema/db2/join)*\n4. *[3-Minute Test](/sql/example-schema/db2/3-minute-quiz)*\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1063, "slov": 130, "odkazu": 62, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:53", "sha256": "d7349b53952ea7608a9e7cc8131cf993467ad41109a2ae60a0a0b74806093457", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/db2/3-minute-quiz", "titulek": "Example Schema for the 3-Minute Quiz (Db2 (LUW))", "h1": "Db2 (LUW) Example Scripts for “3-Minute Quiz”", "popis": "Db2 (LUW) proof scripts for the 3-Minute Quiz", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/db2/3-minute-quiz", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Schema for the 3-Minute Quiz (Db2 (LUW))", "og:description": "Db2 (LUW) proof scripts for the 3-Minute Quiz", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Db2 (LUW)"], "osnova": [{"uroven": 1, "text": "Db2 (LUW) Example Scripts for “3-Minute Quiz”"}, {"uroven": 2, "text": "Question 1 — DATE Anti-Pattern"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 2 — Indexed Top-N"}, {"uroven": 2, "text": "Question 3 — Column Order"}, {"uroven": 4, "text": "Tip"}, {"uroven": 2, "text": "Question 4 — LIKE"}, {"uroven": 4, "text": "Tip"}, {"uroven": 2, "text": "Question 5 — Index Only Scan"}, {"uroven": 4, "text": "Tip"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Db2 (LUW) Example Scripts for “3-Minute Quiz”\n\n---\n\nThis section contains the `create`, `insert` and `select` statements for the “[Test your SQL Know-How in 3 Minutes](/3-minute-quiz)” test. You may want to test yourself before reading this page.\n\nThe `create` and `insert` statements are available in the [example schema archive](/use-the-index-luke.tar.gz).\n\nThe execution plans shown are abbreviated for better readability.\n\n## Question 1 — DATE Anti-Pattern\n\n```\n--#SET TERMINATOR ;\nCREATE INDEX tbl_idx ON tbl (date_column);\n```\n\n```\n--#SET TERMINATOR ;\nSELECT COUNT(*)\n FROM tbl\n WHERE TO_CHAR(date_column, 'YYYY') = 2025;\n```\n\n```\n--#SET TERMINATOR ;\nSELECT COUNT(*)\n FROM tbl\n WHERE date_column >= DATE'2025-01-01'\n AND date_column < DATE'2026-01-01';\n```\n\nThe first query performs a full index scan (`IXSCAN` with no `START`/`STOP` (but `SARG`) in the Predicate Information)\n\n```\nExplain Plan\n-----------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 27\n 2 | GRPBY (COMPLETE) | 1 of 40 ( 2.50%) | 27\n 3 | IXSCAN TBL_IDX | 40 of 1000 ( 4.00%) | 27\n\nPredicate Information\n 3 - SARG ( TO_CHAR(TIMESTAMP(Q1.DATE_COLUMN, 0), 'YYYY') = '2017')\n```\n\nThe second query can do an index range scan (`START`/`STOP` at the `IXSCAN` operation).\n\n```\nExplain Plan\n------------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 6\n 2 | GRPBY (COMPLETE) | 1 of 100 ( 1.00%) | 6\n 3 | IXSCAN TBL_IDX | 100 of 1000 ( 10.00%) | 6\n\nPredicate Information\n 3 - START ('01/01/2017' <= Q1.DATE_COLUMN)\n STOP (Q1.DATE_COLUMN < '01/01/2018')\n```\n\nNote that Db2 (LUW) properly optimize [`extract` expressions](https://modern-sql.com/feature/extract):\n\n```\nSELECT text, date_column\n FROM tbl\n WHERE EXTRACT(YEAR FROM date_column) = 2017\n```\n\n```\nExplain Plan\n----------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 34\n 2 | FETCH TBL | 19 of 19 (100.00%) | 34\n 3 | RIDSCN | 19 of 19 (100.00%) | 6\n 4 | SORT (UNIQUE) | 19 of 19 (100.00%) | 6\n 5 | IXSCAN TBL_IDX | 19 of 186 ( 10.22%) | 6\n\nPredicate Information\n 2 - SARG ('01/01/2017' <= Q1.DATE_COLUMN)\n SARG (Q1.DATE_COLUMN <= '12/31/2017')\n 5 - START ('01/01/2017' <= Q1.DATE_COLUMN)\n STOP (Q1.DATE_COLUMN <= '12/31/2017')\n```\n\n#### Learn More\n\n- [Using Functions in the `WHERE` clause](/sql/where-clause/functions)\n- [Common Anti-Patterns: `DATE`](/sql/where-clause/obfuscation/dates)\n- [Reading Db2 (LUW) explain plan output](/sql/explain-plan/db2/operations)\n\n## Question 2 — Indexed Top-N\n\n```\n--#SET TERMINATOR ;\nCREATE INDEX tbl_idx ON tbl (a, date_column);\n```\n\n```\n--#SET TERMINATOR ;\nSELECT *\n FROM tbl\n WHERE a = 12\n ORDER BY date_column DESC\n FETCH FIRST 1 ROW ONLY;\n```\n\nThe query uses the index (`IXSCAN`) and fetches in reverse order (`REVERSE`). Note that there is no sort operation.\n\n```\nExplain Plan\n-----------------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 13\n 2 | FETCH TBL | 1 of 7 ( 14.29%) | 21\n 3 | IXSCAN (REVERSE) TBL_IDX | 7 of 186 ( 3.76%) | 6\n\nPredicate Information\n 3 - START (Q1.A = +00012.)\n STOP (Q1.A = +00012.)\n```\n\n## Question 3 — Column Order\n\n```\n--#SET TERMINATOR ;\nCREATE INDEX tbl_idx ON tbl (a, b);\n```\n\n```\n--#SET TERMINATOR ;\nSELECT *\n FROM tbl\n WHERE a = 38\n AND b = 1;\n```\n\n```\n--#SET TERMINATOR ;\nSELECT *\n FROM tbl\n WHERE b = 1;\n```\n\n```\n--#SET TERMINATOR ;\nDROP INDEX tbl_idx ;\n```\n\n```\n--#SET TERMINATOR ;\nCREATE INDEX tbl_idx ON tbl (b, a);\n```\n\n```\n--#SET TERMINATOR ;\nSELECT *\n FROM tbl\n WHERE a = 38\n AND b = 1;\n```\n\n```\n--#SET TERMINATOR ;\nSELECT *\n FROM tbl\n WHERE b = 1;\n```\n\nThe first query can use both indexes efficiently (`IXSCAN` with `START` and `STOP` predicates):\n\n```\nExplain Plan\n-------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 21\n 2 | FETCH TBL | 7 of 7 (100.00%) | 21\n 3 | IXSCAN TBL_IDX | 7 of 186 ( 3.76%) | 6\n\nPredicate Information\n 3 - START (Q1.A = +00038.)\n START (Q1.B = +00001.)\n STOP (Q1.A = +00038.)\n STOP (Q1.B = +00001.)\n```\n\n```\nExplain Plan\n-------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 21\n 2 | FETCH TBL | 7 of 7 (100.00%) | 21\n 3 | IXSCAN TBL_IDX | 7 of 186 ( 3.76%) | 6\n\nPredicate Information\n 3 - START (Q1.B = +00001.)\n START (Q1.A = +00038.)\n STOP (Q1.B = +00001.)\n STOP (Q1.A = +00038.)\n```\n\nThe second query cannot use the first index—the query performs a full table scan (`TBSCAN`):\n\n```\nExplain Plan\n----------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 99\n 2 | TBSCAN TBL | 40 of 1000 ( 4.00%) | 99\n\nPredicate Information\n 2 - SARG (Q1.B = +00001.)\n```\n\nReversing the column order in the index allows the second query to use the index efficiently too (`IXSCAN` with `START` and `STOP` predicates):\n\n```\nExplain Plan\n-----------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 34\n 2 | FETCH TBL | 40 of 40 (100.00%) | 34\n 3 | RIDSCN | 40 of 40 (100.00%) | 6\n 4 | SORT (UNIQUE) | 40 of 40 (100.00%) | 6\n 5 | IXSCAN TBL_IDX | 40 of 1000 ( 4.00%) | 6\n\nPredicate Information\n 2 - SARG (Q1.B = +00001.)\n 5 - START (Q1.B = +00001.)\n STOP (Q1.B = +00001.)\n```\n\n#### Tip\n\n- [The column order in multi-column indexes](/sql/where-clause/the-equals-operator/concatenated-keys)\n\n## Question 4 — LIKE\n\n```\n--#SET TERMINATOR ;\nCREATE INDEX tbl_idx ON tbl (text);\n```\n\n```\n--#SET TERMINATOR ;\nSELECT *\n FROM tbl\n WHERE text LIKE 'TJ%';\n```\n\nThe query can use the index efficiently (`IXSCAN` with `START` and `STOP` predicates):\n\n```\nExplain Plan\n-------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 13\n 2 | FETCH TBL | 1 of 1 (100.00%) | 13\n 3 | IXSCAN TBL_IDX | 1 of 300 ( .33%) | 6\n\nPredicate Information\n 3 - START ('TJ..................................\n STOP (Q1.TEXT <= 'TJ.......................\n```\n\n#### Tip\n\n- [A visual explanation when `LIKE` is slow](/sql/where-clause/searching-for-ranges/like-performance-tuning)\n\n## Question 5 — Index Only Scan\n\n```\nCREATE INDEX tbl_idx ON tbl (a, date_column);\n```\n\n```\nSELECT date_column, count(*)\n FROM tbl\n WHERE a = 38\n GROUP BY date_column;\n```\n\n```\nSELECT date_column, count(*)\n FROM tbl\n WHERE a = 38\n AND b = 1\n GROUP BY date_column;\n```\n\nBoth indexes are used, of course. The difference is that the first query doesn’t access the table, so the first query is much faster.\n\n```\nExplain Plan\n---------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 0\n 2 | GRPBY (COMPLETE) | 2 of 2 (100.00%) | 0\n 3 | IXSCAN TBL_IDX | 2 of 300 ( .67%) | 0\n\nPredicate Information\n 3 - START (Q1.A = +00038.)\n STOP (Q1.A = +00038.)\n```\n\nThe second query must be considerably slower because every row needs a table access — also for those that are filtered by the new condition. Even if the index has a low [clustering factor](/sql/clustering/index-filter-predicates#sb-clustering-factor), it is still about twice as many blocks to read.\n\n```\nExplain Plan\n---------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 6\n 2 | GRPBY (COMPLETE) | 0 of 0 | 6\n 3 | FETCH TBL | 0 of 2 ( .00%) | 6\n 4 | IXSCAN TBL_IDX | 2 of 300 ( .67%) | 0\n\nPredicate Information\n 3 - SARG (Q1.B = +00001.)\n 4 - START (Q1.A = +00038.)\n STOP (Q1.A = +00038.)\n```\n\n#### Tip\n\n- [Chapter 5*Clustering Data: The Second Power of Indexing*](/sql/clustering)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 6918, "slov": 1126, "odkazu": 70, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:53", "sha256": "f7ee656e28d3781e29e4863d375ff5fddc97f7c1d5ffe5b578e5d535cf712ac1", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://modern-sql.com/feature/extract", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/db2/join", "titulek": "Example Scripts for Db2 (LUW) - The Join Operation", "h1": "Db2 (LUW) Example Scripts for “The Join Operation”", "popis": "CREATE & INSERT statements to create the Db2 (LUW) example database for Chapter 4, The Join Operation", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/db2/join", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Db2 (LUW) - The Join Operation", "og:description": "CREATE & INSERT statements to create the Db2 (LUW) example database for Chapter 4, The Join Operation", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Db2 (LUW)"], "osnova": [{"uroven": 1, "text": "Db2 (LUW) Example Scripts for “The Join Operation”"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Db2 (LUW) Example Scripts for “The Join Operation”\n\n---\n\nThis section contains the `create` and `insert` statements to run the examples from [Chapter 4*The Join Operation*](/sql/join) in an IBM Db2 (LUW) database.\n\n```\n--#SET TERMINATOR ;\n\n-- Disable autocommit\nUPDATE COMMAND OPTIONS USING C OFF;\n\nCREATE TABLE sales (\n sale_id NUMERIC(10,0) NOT NULL,\n employee_id NUMERIC(10,0) NOT NULL,\n subsidiary_id NUMERIC(10,0) NOT NULL,\n sale_date DATE NOT NULL,\n eur_value NUMERIC(17,2) NOT NULL,\n product_id NUMERIC(10,0) NOT NULL,\n quantity NUMERIC(10,0) NOT NULL,\n junk CHAR(200),\n CONSTRAINT sales_pk \n PRIMARY KEY (sale_id),\n CONSTRAINT sales_emp_fk \n FOREIGN KEY (subsidiary_id, employee_id)\n REFERENCES employees(subsidiary_id, employee_id)\n) NOT LOGGED INITIALLY;\n\nINSERT INTO sales (sale_id\n , subsidiary_id, employee_id\n , sale_date, eur_value\n , product_id, quantity\n , junk)\nWITH generator (n) AS\n( SELECT 1 n FROM sysibm.sysdummy1\n UNION ALL\n SELECT n + 1 FROM generator\n WHERE n < 1800\n)\nSELECT row_number() OVER (), data.*\n FROM (\n SELECT e.subsidiary_id, e.employee_id\n , CURRENT_DATE - floor(rand() * 365 * 10 ) days sale_date\n , CAST(rand()*1000 AS NUMERIC(17,2)) eur_value\n , CAST(rand()*25 AS NUMERIC(2,0)) + 1 product_id\n , CAST(rand()*5 AS NUMERIC(1,0)) + 1 quantity\n , 'junk'\n FROM employees e\n , generator gen\n WHERE MOD(employee_id, 7) = 4\n AND gen.n < employee_id / 5\n ORDER BY sale_date\n ) data\n WHERE dayofweek(sale_date) NOT IN (1,7);\n\nCOMMIT;\n\nCREATE INDEX sales_sub_emp ON sales (subsidiary_id, employee_id);\n\nRUNSTATS ON TABLE sales;\n```\n\nNotes:\n\n- Logging is disabled (which required disabling auto commit) to preserve space and time.\n- The rows are inserted chronologically to reflect a natural table growth.\n- Only a small fraction of employees have sales at all.\n- No sales on Sundays.\n- [Before version 10](https://www.ibm.com/docs/en/db2/11.5.x?topic=commands-runstats) Db2 needs a fully qualified table name (including schema) for `RUNSTATS`. If you are getting an error, try adding the schema name. You can query for the CURRENT_SCHEMA like this: `SELECT current_schema FROM sysibm.sysdummy1;`\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2740, "slov": 372, "odkazu": 63, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:54", "sha256": "5588c519e7d598c88bbb68b0b8e82b6a6c91d81ce9da9f2557be5cbd4ed5edc4", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://www.ibm.com/docs/en/db2/11.5.x?topic=commands-runstats", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/db2/performance-testing-scalability", "titulek": "Example Scripts for Db2 (LUW) - Testing and Scalability", "h1": "Db2 (LUW) Example Scripts for “Testing and Scalability”", "popis": "CREATE & INSERT statements to create the Db2 (LUW) example database for Chapter 3, Testing and Scalability", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/db2/performance-testing-scalability", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Db2 (LUW) - Testing and Scalability", "og:description": "CREATE & INSERT statements to create the Db2 (LUW) example database for Chapter 3, Testing and Scalability", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Db2 (LUW)"], "osnova": [{"uroven": 1, "text": "Db2 (LUW) Example Scripts for “Testing and Scalability”"}, {"uroven": 4, "text": "Warning"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Db2 (LUW) Example Scripts for “Testing and Scalability”\n\n---\n\nThis section contains the `create`, `insert` and PL/SQL code to run the scalability test from [Chapter 3*Performance and Scalability*](/sql/testing-scalability) in an Db2 (LUW) database.\n\n#### Warning\n\nThese scripts will create large objects in the database and produce a huge amount of redo logs.\n\n```\n--#SET TERMINATOR ;\n\n-- Disable autocommit\nUPDATE COMMAND OPTIONS USING C OFF;\n\nCREATE TABLE scale_data (\n section NUMERIC(10,0) NOT NULL,\n id1 NUMERIC(10,0) NOT NULL,\n id2 NUMERIC(10,0) NOT NULL\n) NOT LOGGED INITIALLY;\n```\n\nNote:\n\n- Auto commit is disabled to disable logging for this table. The commit is done in the next step.\n- There is no primary key (to keep the data generation simple)\n- There is no index (yet). That’s done after filling the table\n- There is no “junk” column because the table is actually not accessed during testing\n\n```\n--#SET TERMINATOR ;\n\nINSERT INTO scale_data (section, id1, id2)\nWITH sections (n) AS\n( SELECT 1 n FROM sysibm.sysdummy1\n UNION ALL\n SELECT n + 1 FROM sections\n WHERE n < 300\n)\n, gen (n) AS\n( SELECT 1 n FROM sysibm.sysdummy1\n UNION ALL\n SELECT n + 1 FROM gen\n WHERE n < 900000\n)\nSELECT sections.n, gen.n, FLOOR(rand() * 100) \n FROM sections\n , gen\n WHERE gen.n < sections.n * 3000;\n\nCOMMIT;\n```\n\nNote:\n\n- This code generates 300 sections, you may need to adjust the number for your environment. If you increase the number of sections, you must also increase the second generator. It must generate at least `3000 x ` records.\n- The table will need some gigabytes\n\n```\n--#SET TERMINATOR ;\n\n-- Disable autocommit\nUPDATE COMMAND OPTIONS USING C OFF;\n\nALTER TABLE scale_data ACTIVATE NOT LOGGED INITIALLY;\n\nCREATE INDEX scale_slow ON scale_data (section, id1, id2);\n\nCOMMIT;\n\nRUNSTATS ON TABLE scale_data;\n```\n\nNote:\n\n- The index will also need some gigabytes\n- [Before version 10](https://www.ibm.com/docs/en/db2/11.5.x?topic=commands-runstats) Db2 needs a fully qualified table name (including schema) for `RUNSTATS`. If you are getting an error, try adding the schema name. You can query for the CURRENT_SCHEMA like this: `SELECT current_schema FROM sysibm.sysdummy1;`\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2779, "slov": 414, "odkazu": 63, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:55", "sha256": "3620710a9287daa90e96ca8a7a1cebdd6af020bca2769dbae8f3a03ee8f83ec0", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://www.ibm.com/docs/en/db2/11.5.x?topic=commands-runstats", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/db2/where-clause", "titulek": "Example Scripts for Db2 (LUW) - The WHERE Clause", "h1": "Db2 (LUW) Example Scripts for “The Where Clause”", "popis": "CREATE & INSERT statements to create the Db2 (LUW) example database for Chapter 2, The Where Clause", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/db2/where-clause", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Db2 (LUW) - The WHERE Clause", "og:description": "CREATE & INSERT statements to create the Db2 (LUW) example database for Chapter 2, The Where Clause", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Db2 (LUW)"], "osnova": [{"uroven": 1, "text": "Db2 (LUW) Example Scripts for “The Where Clause”"}, {"uroven": 2, "text": "The Equals Operator"}, {"uroven": 3, "text": "Surrogate Keys"}, {"uroven": 3, "text": "Concatenated Keys"}, {"uroven": 2, "text": "Functions (Db2 10.5+)"}, {"uroven": 3, "text": "Case-Insensitive Search"}, {"uroven": 3, "text": "User-Defined Functions"}, {"uroven": 2, "text": "Emulating Partial Indexes"}, {"uroven": 3, "text": "Setup"}, {"uroven": 3, "text": "Regular Attempt"}, {"uroven": 3, "text": "Obfuscated Attempt"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Db2 (LUW) Example Scripts for “The Where Clause”\n\n---\n\n## The Equals Operator\n\n### Surrogate Keys\n\nThe following script creates the `EMPLOYEES` table with 1000 entries.\n\nThe script is intended to be run from the `db2` command line. It uses the semicolon (;) as the regular statement terminator, but two semicolons (;;) to terminate PL/SQL code.\n\n`CREATE TABLE employees (\n employee_id NUMERIC NOT NULL,\n first_name VARCHAR(1000) NOT NULL,\n last_name VARCHAR(1000) NOT NULL,\n date_of_birth DATE ,\n phone_number VARCHAR(1000) NOT NULL,\n junk CHAR(254) ,\n CONSTRAINT employees_pk PRIMARY KEY (employee_id)\n);``--#SET TERMINATOR ;;\nCREATE FUNCTION random_string(minlen NUMERIC, maxlen NUMERIC)\nRETURNS VARCHAR(1000)\nLANGUAGE SQL\nNOT DETERMINISTIC\nNO EXTERNAL ACTION\nREADS SQL DATA\nBEGIN\n DECLARE rv VARCHAR(1000) DEFAULT '';\n DECLARE i NUMERIC DEFAULT 0;\n DECLARE len NUMERIC DEFAULT 0;\n\n IF maxlen < 1 OR minlen < 1 OR maxlen < minlen THEN\n RETURN NULL;\n END IF;\n\n SET i = floor(rand()*(maxlen-minlen)) + minlen;\n WHILE (i > 0) DO\n SET rv = rv || chr(97+CAST(rand() * 25 AS INTEGER));\n SET i = i - 1;\n END WHILE;\n RETURN rv;\nEND\n;;\n--#SET TERMINATOR ;``INSERT INTO employees (employee_id, first_name,\n last_name, date_of_birth, \n phone_number, junk)\nWITH generator (n) AS\n( SELECT 1 n FROM sysibm.sysdummy1\n UNION ALL\n SELECT n + 1 FROM generator\n WHERE n < 1000\n)\nSELECT generator.n\n , initcap(lower(random_string(2, 8)))\n , initcap(lower(random_string(2, 8)))\n , CURRENT_DATE - floor(rand() * 365 * 10 + 40 * 365) days\n , floor(rand() * 9000 + 1000)\n , 'junk'\n FROM generator;``UPDATE employees \n SET first_name='MARKUS', \n last_name='WINAND'\n WHERE employee_id=123;``RUNSTATS ON TABLE employees;`\n\nNotes:\n\n- The `JUNK` column is used to have a realistic row length. Because it’s data type is `CHAR`, as opposed to `VARCHAR`, it always needs the 254 bytes it can hold (254 is the limit on Db2 (LUW) Express-C 10.5). Without this column the table would become unrealistically small and many demonstrations would not work.\n- Random data is filled into the table, with exception to my entry, that is updated after the insert.\n- Table [statistics](/sql/where-clause/the-equals-operator/slow-indexes-part-ii#sb-statistics) are gathered so that the [optimizer](/sql/where-clause/the-equals-operator/slow-indexes-part-ii#sb-optimizer) knows a little bit about the table’s content.\n- [Before version 10](https://www.ibm.com/docs/en/db2/11.5.x?topic=commands-runstats) Db2 needs a fully qualified table name (including schema) for `RUNSTATS`. If you are getting an error, try adding the schema name. You can query for the CURRENT_SCHEMA like this: `SELECT current_schema FROM sysibm.sysdummy1;`\n\n### Concatenated Keys\n\nThis script changes the `EMPLOYEES` table so that it reflects the situation after the merger with Very Big Company:\n\n```\n--#SET TERMINATOR ;\n\n-- add subsidiary_id and update existing records\nALTER TABLE employees ADD subsidiary_id NUMERIC;\nUPDATE employees SET subsidiary_id = 30;\nALTER TABLE employees ALTER COLUMN subsidiary_id SET NOT NULL;\n\n-- change the PK\nALTER TABLE employees DROP PRIMARY KEY;\n-- to prevent failur for reason \"7\"\nREORG TABLE employees;\nALTER TABLE employees ADD CONSTRAINT employees_pk \n PRIMARY KEY (employee_id, subsidiary_id);\n\n-- generate more records (Very Big Company)\nINSERT INTO employees (employee_id, first_name,\n last_name, date_of_birth, \n phone_number, subsidiary_id, junk)\nWITH generator (n) AS\n( SELECT 1001 n FROM sysibm.sysdummy1\n UNION ALL\n SELECT n + 1 FROM generator\n WHERE n < 10000\n)\nSELECT generator.n\n , initcap(lower(random_string(2, 8)))\n , initcap(lower(random_string(2, 8)))\n , CURRENT_DATE - floor(rand() * 365 * 10 + 40 * 365) days\n , floor(rand() * 9000 + 1000)\n , floor(rand() * least(mod(generator.n, 2)+0.2,1) * (generator.n-1000)/9000*29) \n , 'junk'\n FROM generator;\n\nRUNSTATS ON TABLE employees;\n```\n\nNotes:\n\n- The new primary key just extended by the `SUBSIDIARY_ID`; that is, the `EMPLOYEE_ID` remains in the first position.\n- The new records are randomly assigned to the subsidiaries 1 through 29.\n- The table and index are analyzed again to make the optimizer aware of the grown data volume.\n\nThe next script introduces the index on `SUBSIDIARY_ID` to support the query for all employees of one particular subsidiary:\n\n```\n--#SET TERMINATOR ;\nCREATE INDEX emp_sub_id ON employees (subsidiary_id);\n```\n\nAlthough that gives decent performance, it’s better to use the index that supports the primary key:\n\n```\n--#SET TERMINATOR ;\n\n-- index to support the new PK\nCREATE UNIQUE INDEX employees_pk_new\n ON employees (subsidiary_id, employee_id);\n\nALTER TABLE employees\n DROP PRIMARY KEY;\n\n-- this will automatically use the new index:\n-- SQL0598W Existing index \"EMPLOYEE_PK_NEW\" is used as the index for \n-- the primary key or a unique key. SQLSTATE=01550\nALTER TABLE employees\n ADD CONSTRAINT employees_pk\n PRIMARY KEY (subsidiary_id, employee_id);\n-- cleanup\nRENAME INDEX employees_pk_new TO employees_pk;\nDROP INDEX emp_sub_id;\n```\n\nNotes:\n\n- A new index is created and used to support the PK.\n- Dropping the primary key automatically drops the automatically created index supporting it.\n- Adding the new primary key makes use of the new index automatically.\n\n## Functions (Db2 10.5+)\n\n### Case-Insensitive Search\n\nThe randomized names were already created in correct case, just update “my” record:\n\n```\n--#SET TERMINATOR ;\n\nUPDATE employees \n SET first_name = 'Markus'\n , last_name = 'Winand'\n WHERE employee_id = 123\n AND subsidiary_id = 30;\n```\n\nThe statement to create the function-based index:\n\n```\n--#SET TERMINATOR ;\nCREATE INDEX emp_up_name\n ON employees (UPPER(last_name));\nDROP INDEX emp_name;\n```\n\n```\nRUNSTATS ON TABLE employees;\n```\n\n### User-Defined Functions\n\nDefine a function that calculates the age and attempts to use it in an index:\n\n```\n--#SET TERMINATOR ;;\nCREATE FUNCTION get_age(date_of_birth DATE) \nRETURNS NUMERIC\nLANGUAGE SQL\nBEGIN\n RETURN YEAR(CURRENT_DATE - date_of_birth);\nEND\n;;\n--#SET TERMINATOR ;\n\nCREATE INDEX invalid ON EMPLOYEES (get_age(date_of_birth));\n```\n\nYou should get the error “*SQL0356N: The index was not created because a key expression was invalid. Key expression: \"1\". Reason code: \"5”*\". Whereas [reason code 5 means](https://www.ibm.com/docs/en/db2/11.5.x?topic=messages-sql0000-0999#sqlmsg__SQL0356N): \"*The key expression included a user-defined function.*\"\n\n## Emulating Partial Indexes\n\n### Setup\n\n```\n--#SET TERMINATOR ;\n\nCREATE TABLE messages (\n id NUMERIC(10,0) NOT NULL,\n processed CHAR(1) NOT NULL,\n receiver NUMERIC(10,0) NOT NULL,\n message CHAR(200) NOT NULL,\n\n CONSTRAINT messages_pk PRIMARY KEY (id)\n);\n\nINSERT INTO messages (id, processed, receiver, message)\nWITH generator(n) AS\n( SELECT 1 n FROM sysibm.sysdummy1\n UNION ALL\n SELECT n + 1 FROM generator\n WHERE n < 999999\n)\nSELECT n id\n , CASE WHEN rand() < 0.09 THEN 'N' ELSE 'Y' END processed\n , floor(rand() * 100) receiver\n , 'junk' message\n FROM generator;\n\nRUNSTATS ON TABLE messages;\n\nDROP INDEX messages_not_processed_pi;\nCREATE INDEX messages_not_processed_pi\n ON messages (CASE WHEN processed = 'N' THEN receiver+0\n ELSE NULL\n END)\nEXCLUDE NULL KEYS;\n\nSELECT *\n FROM messages\n WHERE (CASE WHEN processed = 'N' THEN receiver+0\n ELSE NULL\n END) = ?;\n```\n\n### Regular Attempt\n\n```\nCREATE INDEX messages_not_processed_pi\n ON messages (CASE WHEN processed = 'N' THEN receiver\n ELSE NULL\n END)\nEXCLUDE NULL KEYS;\n\nSELECT *\n FROM messages\n WHERE (CASE WHEN processed = 'N' THEN receiver\n ELSE NULL\n END) = ?;\n```\n\n```\nExplain Plan\n-------------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 49686\n 2 | TBSCAN MESSAGES | 900 of 999999 ( .09%) | 49686\n\nPredicate Information\n 2 - SARG (Q1.PROCESSED = 'N')\n SARG (Q1.RECEIVER = ?)\n```\n\nSame happens when using an expression like `CASE processed WHEN 'N'…`.\n\n### Obfuscated Attempt\n\n```\nDROP INDEX messages_not_processed_pi;\nCREATE INDEX messages_not_processed_pi\n ON messages (CASE WHEN processed = 'N' THEN receiver+0\n ELSE NULL\n END)\nEXCLUDE NULL KEYS;\n\nSELECT *\n FROM messages\n WHERE (CASE WHEN processed = 'N' THEN receiver+0\n ELSE NULL\n END) = ?;\n```\n\n```\nID | Operation | Rows | Cost\n 1 | RETURN | | 13071\n 2 | FETCH MESSAGES | 40000 of 40000 (100.00%) | 13071\n 3 | RIDSCN | 40000 of 40000 (100.00%) | 1665\n 4 | SORT (UNQIUE) | 40000 of 40000 (100.00%) | 1665\n 5 | IXSCAN MESSAGES_NOT_PROCESSED_PI | 40000 of 999999 ( 4.00%) | 1646\n\nPredicate Information\n 2 - SARG ( CASE WHEN (Q1.PROCESSED = 'N') THEN (Q1.RECEIVER + 0) ELSE NULL END = ?)\n 5 - START ( CASE WHEN (Q1.PROCESSED = 'N') THEN (Q1.RECEIVER + 0) ELSE NULL END = ?)\n STOP ( CASE WHEN (Q1.PROCESSED = 'N') THEN (Q1.RECEIVER + 0) ELSE NULL END = ?)\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 8984, "slov": 1304, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:56", "sha256": "c43dc64de2480a252a4ab4d5b65840ee04972aaea98c55eef3fe47965f9996fe", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://www.ibm.com/docs/en/db2/11.5.x?topic=commands-runstats", "https://www.ibm.com/docs/en/db2/11.5.x?topic=messages-sql0000-0999", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/mysql", "titulek": "Example Scripts for MySQL", "h1": "MySQL Example Scripts", "popis": "CREATE & INSERT statements to create the Use The Index, Luke MySQL example database.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/mysql", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for MySQL", "og:description": "CREATE & INSERT statements to create the Use The Index, Luke MySQL example database.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema"], "osnova": [{"uroven": 1, "text": "MySQL Example Scripts"}, {"uroven": 2, "text": "Contents"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# MySQL Example Scripts\n\n---\n\nThe scripts provided in this appendix are ready to run and were tested on MySQL 5.1.\n\n## Contents\n\n1. *[The `where` clause](/sql/example-schema/mysql/where-clause)*\n2. *[The Join Operation](/sql/example-schema/mysql/join)*\n3. *[Clustering Data](/sql/example-schema/mysql/clustering-data)*\n4. *[Sorting and Grouping](/sql/example-schema/mysql/sorting-grouping)*\n5. *[Partial Results](/sql/example-schema/mysql/partial-results)*\n6. *[3-Minute Test](/sql/example-schema/mysql/3-minute-quiz)*\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1152, "slov": 133, "odkazu": 65, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:57", "sha256": "c6c083cc7109ee2b293ea38c0899ce1e2b9cf98b77d06e84cdc4cdf53e09b644", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/mysql/3-minute-quiz", "titulek": "Example Scripts for MySQL - 3-Minuten Test", "h1": "MySQL Example Scripts for “3-Minute Quiz”", "popis": "CREATE & INSERT statements to create the MySQL example database for the 3-Minuten Test", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/mysql/3-minute-quiz", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for MySQL - 3-Minuten Test", "og:description": "CREATE & INSERT statements to create the MySQL example database for the 3-Minuten Test", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "MySQL"], "osnova": [{"uroven": 1, "text": "MySQL Example Scripts for “3-Minute Quiz”"}, {"uroven": 2, "text": "Question 1 — DATE Anti-Pattern"}, {"uroven": 4, "text": "Tip"}, {"uroven": 2, "text": "Question 2 — Indexed Top-N"}, {"uroven": 2, "text": "Question 3 — Column Order"}, {"uroven": 4, "text": "Tip"}, {"uroven": 2, "text": "Question 4 — LIKE"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 5 — Index Only Scan"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# MySQL Example Scripts for “3-Minute Quiz”\n\n---\n\nThis section contains the `create`, `insert` and `select` statements for the “[Test your SQL Know-How in 3 Minutes](/3-minute-quiz)” test. You may want to test yourself before reading this page.\n\nThe `create` and `insert` statements are available in the [example schema archive](/use-the-index-luke.tar.gz).\n\nThe execution plans shown in this section are stripped to the relevant columns.\n\n## Question 1 — DATE Anti-Pattern\n\n```\nCREATE INDEX tbl_idx ON tbl (date_column);\n```\n\n```\nSELECT COUNT(*)\n FROM tbl\n WHERE EXTRACT(YEAR FROM date_column) = 2025;\n```\n\n```\nSELECT COUNT(*)\n FROM tbl\n WHERE date_column >= DATE'2025-01-01'\n AND date_column < DATE'2026-01-01';\n```\n\nThe first execution plan performs a full index scan (`type=index`). The second execution plan, on the other hand, performs an index range scan (`type=range`). Note the the rows column also reflects the more efficient access method.\n\n```\n+-------+---------------+---------+------+--------------------------+\n| type | possible_keys | key | rows | Extra |\n+-------+---------------+---------+------+--------------------------+\n| index | NULL | tbl_idx | 300 | Using where; Using index |\n+-------+---------------+---------+------+--------------------------+\n```\n\n```\n+-------+---------------+---------+------+--------------------------+\n| type | possible_keys | key | rows | Extra |\n+-------+---------------+---------+------+--------------------------+\n| range | tbl_idx | tbl_idx | 271 | Using where; Using index |\n+-------+---------------+---------+------+--------------------------+\n```\n\n#### Tip\n\n- [Using Functions in the `WHERE` clause](/sql/where-clause/functions)\n- [Common Anti-Patterns: `DATE`](/sql/where-clause/obfuscation/dates)\n- [Reading MySQL explain plan output](/sql/explain-plan/mysql/operations)\n\n## Question 2 — Indexed Top-N\n\n```\nCREATE INDEX tbl_idx ON tbl (a, date_column);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE a = 12\n ORDER BY date_column DESC\n LIMIT 1;\n```\n\nThe query uses access type `REF`, which is very similar to the `RANGE` access. However, the interesting part is that there is no `SORT` mentioned in the Extra column.\n\n```\n+------+---------------+---------+-------------+\n| type | possible_keys | key | Extra |\n+------+---------------+---------+-------------+\n| ref | tbl_idx | tbl_idx | Using where | \n+------+---------------+---------+-------------+\n```\n\n## Question 3 — Column Order\n\n```\nCREATE INDEX tbl_idx ON tbl (a, b);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE a = 38\n AND b = 1;\n```\n\n```\nSELECT *\n FROM tbl\n WHERE b = 1;\n```\n\n```\nDROP INDEX tbl_idx ON tbl;\n```\n\n```\nCREATE INDEX tbl_idx ON tbl (b, a);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE a = 38\n AND b = 1;\n```\n\n```\nSELECT *\n FROM tbl\n WHERE b = 1;\n```\n\nThe first query can use both indexes efficiently (`type=ref` or `range`).\n\n```\n+------+---------------+---------+------+-------+\n| type | possible_keys | key | rows | Extra |\n+------+---------------+---------+------+-------+\n| ref | tbl_idx | tbl_idx | 1 | NULL |\n+------+---------------+---------+------+-------+\n```\n\n```\n+------+---------------+---------+------+-------+\n| type | possible_keys | key | rows | Extra |\n+------+---------------+---------+------+-------+\n| ref | tbl_idx | tbl_idx | 1 | NULL |\n+------+---------------+---------+------+-------+\n```\n\nThe second query cannot use the key to access the index—it reads the entire index (`type=ALL`). Changing the column order in the index allows both queries to use the `REF` (or `RANGE`) access method.\n\n```\n+------+---------------+------+------+-------------+\n| type | possible_keys | key | rows | Extra |\n+------+---------------+------+------+-------------+\n| ALL | NULL | NULL | 300 | Using where |\n+------+---------------+------+------+-------------+\n```\n\n```\n+------+---------------+---------+------+-------+\n| type | possible_keys | key | rows | Extra |\n+------+---------------+---------+------+-------+\n| ref | tbl_idx | tbl_idx | 2 | NULL |\n+------+---------------+---------+------+-------+\n```\n\nNote that MySQL might also do a full index scan (`type=Index`). Although this might be better than a full table scan (depends on the data), it is far less efficient than a index range scan (`type=ref` or `range`).\n\n#### Tip\n\n- [The column order in Multi-Column Indexes](/sql/where-clause/the-equals-operator/concatenated-keys)\n- [Reading MySQL explain plan output](/sql/explain-plan/mysql/operations)\n\n## Question 4 — LIKE\n\n```\nCREATE INDEX tbl_idx ON tbl (text);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE text LIKE 'TJ%';\n```\n\nThe execution plan clearly states that it is doing an [index range scan (type=range)](/sql/explain-plan/mysql/operations#ap-plan-mysql-op-idx-tbl). Since there is only wild card character at the very end, the full search text `'TJ'` can be used as [index access predicate](/sql/where-clause/searching-for-ranges/greater-less-between-tuning-sql-access-filter-predicates).\n\n```\n+-------+---------+---------+------+-----------------------+\n| type | key | key_len | ref | Extra |\n+-------+---------+---------+------+-----------------------+\n| range | tbl_idx | 258 | NULL | Using index condition |\n+-------+---------+---------+------+-----------------------+\n```\n\n#### Learn More\n\n- [A visual explanation why LIKE is slow](/sql/where-clause/searching-for-ranges/like-performance-tuning)\n\n## Question 5 — Index Only Scan\n\n```\nCREATE INDEX tbl_idx ON tbl (a, date_column);\n```\n\n```\nSELECT date_column, count(*)\n FROM tbl\n WHERE a = 38\n GROUP BY date_column;\n```\n\n```\nSELECT date_column, count(*)\n FROM tbl\n WHERE a = 38\n AND b = 1\n GROUP BY date_column;\n```\n\nAlthough the index is used efficiently in both queries (access type `REF`), the second query does not mention “Using index” in the extra column. That means the second query is not executed as index-only scan and will perform less efficient as the first.\n\n```\n+------+---------------+---------+--------------------------+\n| type | possible_keys | key | Extra |\n+------+---------------+---------+--------------------------+\n| ref | tbl_idx | tbl_idx | Using where; Using index |\n+------+---------------+---------+--------------------------+\n```\n\n```\n+------+---------------+---------+------------------------------------+\n| type | possible_keys | key | Extra |\n+------+---------------+---------+------------------------------------+\n| ref | tbl_idx | tbl_idx | Using index condition; Using where |\n+------+---------------+---------+------------------------------------+\n```\n\n#### Learn More\n\n- [Chapter 5*Clustering Data: The Second Power of Indexing*](/sql/clustering)\n- [Reading MySQL explain plan output](/sql/explain-plan/mysql/operations)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 5442, "slov": 946, "odkazu": 72, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:14:58", "sha256": "1125fe994538ab47f9b14a5115e44395c76af111dd07409444cb69e8f6501f8d", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/mysql/clustering-data", "titulek": "Example Scripts for MySQL - Clustering Data", "h1": "MySQL Example Scripts for “Clustering Data”", "popis": "CREATE & INSERT statements to create the MySQL example database for Chapter 5, Clustering Data", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/mysql/clustering-data", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for MySQL - Clustering Data", "og:description": "CREATE & INSERT statements to create the MySQL example database for Chapter 5, Clustering Data", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "MySQL"], "osnova": [{"uroven": 1, "text": "MySQL Example Scripts for “Clustering Data”"}, {"uroven": 2, "text": "Index-Organized Tables (Clustered Indexes)"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# MySQL Example Scripts for “Clustering Data”\n\n---\n\nThis section contains the `create` and `insert` code to run the examples from [Chapter 5*Clustering Data: The Second Power of Indexing*](/sql/clustering) in an MySQL database.\n\n## Index-Organized Tables (Clustered Indexes)\n\nThe following creates a second `SALES` Table using the InnoDB engine so that it is created as clustered index. A secondary index is added on the `SALE_DATE` column.\n\n```\nCREATE TABLE sales_inno (\n sale_id NUMERIC NOT NULL,\n employee_id NUMERIC NOT NULL,\n subsidiary_id NUMERIC NOT NULL,\n sale_date DATE NOT NULL,\n eur_value NUMERIC(17,2) NOT NULL,\n junk CHAR(200),\n CONSTRAINT sales_pk \n PRIMARY KEY (sale_id)\n) Engine=InnoDB;\n\nINSERT INTO sales_inno (sale_id\n , subsidiary_id, employee_id\n , sale_date, eur_value, junk)\nSELECT @row := @row + 1 sale_id\n , data.*\n FROM (\n SELECT e.subsidiary_id, e.employee_id\n , CURDATE() - INTERVAL (RAND(0)*3650) DAY sale_date\n , TRUNCATE(RAND(1)*99.90+0.1,2) eur_value\n , 'junk'\n FROM employees e\n , ( SELECT generator_4k.n+1 n\n FROM generator_4k\n WHERE generator_4k.n < 1800\n ) gen\n WHERE MOD(employee_id, 7) = 4\n AND gen.n < employee_id / 5\n ORDER BY sale_date\n ) data, (SELECT @row := 0) init\n WHERE DAYOFWEEK(sale_date) NOT IN (1,7);\n\nCREATE INDEX sales_inno_dt ON sales_inno (sale_date);\n```\n\nNote the “Using Index” indicating an Index-Only Scan:\n\n`EXPLAIN\n SELECT sale_id \n FROM sales_inno\n WHERE sale_date = ?;\n\n+----+------------+------+---------------+------+-------------+\n| id | table | type | key | rows | Extra |\n+----+------------+------+---------------+------+-------------+\n| 1 | sales_inno | ref | sales_inno_dt | 301 | **Using index** |\n+----+------------+------+---------------+------+-------------+`\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2176, "slov": 316, "odkazu": 64, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:00", "sha256": "992e9544e0cbd85705f0de25197aedd594473ed579a6cd35fb53fd0c1342bffe", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/mysql/join", "titulek": "Example Scripts for MySQL - The Join Operation", "h1": "MySQL Example Scripts for “The Join Operation”", "popis": "CREATE & INSERT statements to create the MySQL example database for Chapter 4, The Join Operation", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/mysql/join", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for MySQL - The Join Operation", "og:description": "CREATE & INSERT statements to create the MySQL example database for Chapter 4, The Join Operation", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "MySQL"], "osnova": [{"uroven": 1, "text": "MySQL Example Scripts for “The Join Operation”"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# MySQL Example Scripts for “The Join Operation”\n\n---\n\nThis section contains the `create` and `insert` code to run the examples from [Chapter 4*The Join Operation*](/sql/join) in an MySQL database.\n\n```\nCREATE TABLE sales (\n sale_id NUMERIC NOT NULL,\n employee_id NUMERIC NOT NULL,\n subsidiary_id NUMERIC NOT NULL,\n sale_date DATE NOT NULL,\n eur_value NUMERIC(17,2) NOT NULL,\n product_id NUMERIC NOT NULL,\n quantity NUMERIC NOT NULL,\n junk CHAR(200),\n CONSTRAINT sales_pk \n PRIMARY KEY (sale_id),\n CONSTRAINT sales_emp_fk \n FOREIGN KEY (subsidiary_id, employee_id)\n REFERENCES employees(subsidiary_id, employee_id)\n);\n\nINSERT INTO sales (sale_id\n , subsidiary_id, employee_id\n , sale_date, eur_value\n , product_id, quantity\n , junk)\nSELECT @row := @row + 1 sale_id\n , data.*\n FROM (\n SELECT e.subsidiary_id, e.employee_id\n , CURDATE() - INTERVAL (RAND(0)*3650) DAY sale_date\n , TRUNCATE(RAND(1)*99.90+0.1, 2) eur_value\n , TRUNCATE(RAND(2)*25+1, 0) product_id\n , TRUNCATE(RAND(3)*5+1, 0) quantity\n , 'junk'\n FROM employees e\n , ( SELECT generator_4k.n+1 n\n FROM generator_4k\n WHERE generator_4k.n < 1800\n ) gen\n WHERE MOD(employee_id, 7) = 4\n AND gen.n < employee_id / 5\n ORDER BY sale_date\n ) data, (SELECT @row := 0) init\n WHERE DAYOFWEEK(sale_date) NOT IN (1,7);\n```\n\nNotes:\n\n- The rows are inserted chronologically to reflect a natural table growth.\n- Only a small fraction of employees have sales at all.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2038, "slov": 275, "odkazu": 64, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:01", "sha256": "42cc5f5658073eb19964cbd999ee11f34b0579595b2917737db31c166d8a78af", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/mysql/partial-results", "titulek": "Example Scripts for MySQL - Partial Results", "h1": "MySQL Example Scripts for “Partial Results”", "popis": "CREATE & INSERT statements to create the MySQL example database for Chapter 7, Partial Results", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/mysql/partial-results", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for MySQL - Partial Results", "og:description": "CREATE & INSERT statements to create the MySQL example database for Chapter 7, Partial Results", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "MySQL"], "osnova": [{"uroven": 1, "text": "MySQL Example Scripts for “Partial Results”"}, {"uroven": 2, "text": "Querying Top-N Rows"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# MySQL Example Scripts for “Partial Results”\n\n---\n\nThis section contains the `create` and `insert` statements to run the examples from [Chapter 7*Partial Results*](/sql/partial-results) in a MySQL database.\n\n## Querying Top-N Rows\n\nAn indexed Top-N query doesn’t show a “filesort” operation in the Extras column:\n\n```\nSELECT *\n FROM sales\n ORDER BY sale_date DESC\n LIMIT 10\n```\n\n`+----+-------+-------+-------------+--------+-------+\n| id | table | type | key | rows | Extra |\n+----+-------+-------+-------------+--------+-------+\n| 1 | sales | index | sales_dt_pr | 836092 | | \n+----+-------+-------+-------------+--------+-------+`\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1120, "slov": 167, "odkazu": 64, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:02", "sha256": "a1f7b786bebfac1eebf7b802e65c48831be39ad82dc5b17b5ccd09eb24db5e39", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/mysql/sorting-grouping", "titulek": "Example Scripts for MySQL - Sorting and Grouping", "h1": "MySQL Example Scripts for “Sorting and Grouping”", "popis": "CREATE & INSERT statements to create the MySQL example database for Chapter 6, Sorting and Grouping", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/mysql/sorting-grouping", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for MySQL - Sorting and Grouping", "og:description": "CREATE & INSERT statements to create the MySQL example database for Chapter 6, Sorting and Grouping", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "MySQL"], "osnova": [{"uroven": 1, "text": "MySQL Example Scripts for “Sorting and Grouping”"}, {"uroven": 2, "text": "Indexed Order By"}, {"uroven": 2, "text": "Order By ASC/DESC and NULLS FIRST/LAST"}, {"uroven": 2, "text": "Indexing Group By"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# MySQL Example Scripts for “Sorting and Grouping”\n\n---\n\nThis section contains the code and execution plans for [Chapter 6*Sorting and Grouping*](/sql/sorting-grouping) in a MySQL database.\n\n## Indexed Order By\n\n```\nALTER TABLE sales\n DROP INDEX sales_date;\n\nALTER TABLE sales\n ADD INDEX sales_dt_pr (sale_date, product_id);\n\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date = CURDATE() - INTERVAL 1 DAY\n ORDER BY sale_date, product_id;\n```\n\nThere is no “Extra: Using filesort”:\n\n`+-------------+------+-------------+------+-------------+\n| select_type | type | key | rows | Extra |\n+-------------+------+-------------+------+-------------+\n| SIMPLE | ref | sales_dt_pr | 1 | Using where |\n+-------------+------+-------------+------+-------------+`\n\nThe same execution plan is used when sorting for `PRODUCT_ID` only:\n\n```\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date = CURDATE() - INTERVAL 1 DAY\n ORDER BY product_id;\n```\n\nUsing greater or equals requires an explicit sort:\n\n```\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= CURDATE() - INTERVAL 1 DAY\n ORDER BY product_id;\n```\n\nExecution plan re-formatted for a better fit on the page:\n\n`+-------------+------+-------------+------+----------------+\n| select_type | type | key | rows | Extra |\n+-------------+------+-------------+------+----------------+\n| SIMPLE | ref | sales_dt_pr | 117 | Using where; |\n| | | | | **Using filesort** |\n+-------------+------+-------------+------+----------------+`\n\n## Order By ASC/DESC and NULLS FIRST/LAST\n\nMySQL uses the index backwards, but doesn’t mention it in the execution plan:\n\n```\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= CURDATE() - INTERVAL 1 DAY\n ORDER BY sale_date DESC, product_id DESC;\n```\n\nMixing `ASC` and `DESC` requires explicit sorting:\n\n```\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= CURDATE() - INTERVAL 1 DAY\n ORDER BY sale_date ASC, product_id DESC;\n```\n\nMySQL Accepts `ASC` and `DESC` specification in the index definition, but ignores it.\n\n```\nALTER TABLE sales\n DROP INDEX sales_dt_pr;\n\nALTER TABLE sales\n ADD INDEX sales_dt_pr (sale_date ASC, product_id DESC);\n\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= CURDATE() - INTERVAL 1 DAY\n ORDER BY sale_date ASC, product_id DESC;\n```\n\nTo proof that, it is still avoiding the sort when both columns are sorted ascending.\n\n```\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= CURDATE() - INTERVAL 1 DAY\n ORDER BY sale_date ASC, product_id ASC;\n```\n\n## Indexing Group By\n\nAn indexed `group by` show now sort operation in the execution plan:\n\n```\nEXPLAIN\n SELECT product_id, sum(eur_value)\n FROM sales\n WHERE sale_date = CURDATE() - INTERVAL 1 DAY\n GROUP BY product_id;\n```\n\nA regular `group by` is executed with the sort/group algorithm, because MySQL does not implement Hash-Group as of release 5.6.\n\n```\nEXPLAIN\n SELECT product_id, sum(eur_value)\n FROM sales\n WHERE sale_date >= CURDATE() - INTERVAL 1 DAY\n GROUP BY product_id;\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3327, "slov": 489, "odkazu": 64, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:03", "sha256": "6394a71162ee4cc7c7931c2eeee9a952962ee54b632b83e5919d94f55c6b8a22", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/mysql/where-clause", "titulek": "Example Scripts for MySQL - The WHERE Clause", "h1": "MySQL Example Scripts for “The Where Clause”", "popis": "CREATE & INSERT statements to create the Use The Index, Luke MySQL example database for Chapter 2, The Where Clause", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/mysql/where-clause", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for MySQL - The WHERE Clause", "og:description": "CREATE & INSERT statements to create the Use The Index, Luke MySQL example database for Chapter 2, The Where Clause", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "MySQL"], "osnova": [{"uroven": 1, "text": "MySQL Example Scripts for “The Where Clause”"}, {"uroven": 2, "text": "The Equals Operator"}, {"uroven": 3, "text": "Surrogate Keys"}, {"uroven": 3, "text": "Concatenated Keys"}, {"uroven": 2, "text": "Functions"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# MySQL Example Scripts for “The Where Clause”\n\n---\n\n## The Equals Operator\n\n### Surrogate Keys\n\nCreating the `EMPLOYEES` table with 1000 rows.\n\n```\nCREATE TABLE employees (\n employee_id NUMERIC NOT NULL,\n first_name VARCHAR(255) NOT NULL,\n last_name VARCHAR(255) NOT NULL,\n date_of_birth DATE ,\n phone_number VARCHAR(255) NOT NULL,\n junk CHAR(255) ,\n CONSTRAINT employees_pk PRIMARY KEY (employee_id)\n);\n```\n\n```\nCREATE OR REPLACE VIEW generator_16\nAS SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL\n SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL\n SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL\n SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL\n SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL\n SELECT 15;\n```\n\n```\nCREATE OR REPLACE VIEW generator_256\nAS SELECT ( ( hi.n << 4 ) | lo.n ) AS n\n FROM generator_16 lo, generator_16 hi;\n```\n\n```\nCREATE OR REPLACE VIEW generator_4k\nAS SELECT ( ( hi.n << 8 ) | lo.n ) AS n\n FROM generator_256 lo, generator_16 hi;\n```\n\n```\nCREATE OR REPLACE VIEW generator_64k\nAS SELECT ( ( hi.n << 8 ) | lo.n ) AS n\n FROM generator_256 lo, generator_256 hi;\n```\n\n```\nINSERT INTO employees (employee_id, first_name,\n last_name, date_of_birth, \n phone_number, junk)\nSELECT gen.n +1,\n GROUP_CONCAT(CHAR((RAND() * 25)+97) SEPARATOR ''),\n GROUP_CONCAT(CHAR((RAND() * 25)+97) SEPARATOR ''),\n SUBDATE(CURDATE(), INTERVAL (RAND()*3650 + 40*365) DAY),\n FLOOR(RAND()*9000+1000),\n 'junk'\n FROM generator_4k gen, generator_16 rand\n WHERE gen.n < 1000\n GROUP BY gen.n;\n```\n\n```\nUPDATE employees \n SET first_name='MARKUS', \n last_name='WINAND'\n WHERE employee_id=123;\n```\n\n```\nANALYZE TABLE employees;\n```\n\nNote:\n\n- The `GENERATOR_X` views are row generators as described in the [MySQL Row Generator](/blog/2011-07-30/mysql-row-generator) article.\n- The `JUNK` column is used to have a realistic row length. Because it’s data type is `CHAR`, as opposed to `VARCHAR`, it always stores 255 characters. Without this column the table would become unrealistically small and some demonstrations would not work.\n- Random data is filled into the table, with exception to my entry, that is updated after the insert.\n- Table and index [statistics](/sql/where-clause/the-equals-operator/slow-indexes-part-ii#sb-statistics) are gathered so that the [optimizer](/sql/where-clause/the-equals-operator/slow-indexes-part-ii#sb-optimizer) knows a little bit about the table’s content.\n\n### Concatenated Keys\n\n```\n-- add subsidiary_id and update existing records\nALTER TABLE employees ADD subsidiary_id NUMERIC;\n```\n\n```\nUPDATE employees SET subsidiary_id = 30;\n```\n\n```\nALTER TABLE employees MODIFY subsidiary_id NUMERIC NOT NULL;\n```\n\n```\n-- change the PK\nALTER TABLE employees DROP PRIMARY KEY;\n```\n\n```\nALTER TABLE employees ADD CONSTRAINT employees_pk \n PRIMARY KEY (employee_id, subsidiary_id);\n```\n\n```\n-- generate more records (Very Big Company)\nINSERT INTO employees (employee_id, first_name, \n last_name, date_of_birth, \n phone_number, subsidiary_id, junk)\nSELECT gen.n + 1\n , GROUP_CONCAT(CHAR( RAND()*25 + 97) SEPARATOR '')\n , GROUP_CONCAT(CHAR( RAND()*25 + 97) SEPARATOR '')\n , CURDATE() - INTERVAL (RAND(0)*365*10 + 40*365) DAY\n , FLOOR(RAND()*9000 + 1000)\n , FLOOR(RAND()*(gen.n/9000)*29 + 1)\n , 'junk'\n FROM generator_64k gen, generator_16 rand\n WHERE gen.n < 9000\n GROUP BY gen.n;\n```\n\n```\nANALYZE TABLE employees;\n```\n\nNotes:\n\n- The new primary key includes by the `SUBSIDIARY_ID`; that is, the `EMPLOYEE_ID` remains in the first position.\n- The new records are randomly assigned to the subsidiaries 1 through 29.\n- The table and index are analyzed again to make the optimizer aware of the grown data volume.\n\nThe next script introduces the index on `SUBSIDIARY_ID` to support the query for all employees of one particular subsidiary:\n\n```\nALTER TABLE employees ADD INDEX emp_sub_id (subsidiary_id)\n```\n\nAlthough that gives decent performance, it’s better to use the index that supports the primary key:\n\n```\n-- use tmp index to support the PK\nALTER TABLE employees\n ADD UNIQUE INDEX tmp (employee_id, subsidiary_id);\n```\n\n```\nALTER TABLE employees\n DROP PRIMARY KEY;\n```\n\n```\nALTER TABLE employees\n ADD PRIMARY KEY (subsidiary_id, employee_id);\n```\n\n```\nALTER TABLE employees\n DROP INDEX tmp;\n```\n\n```\nALTER TABLE employees\n DROP INDEX emp_sub_id;\n```\n\n```\nANALYZE TABLE employees;\n```\n\nNotes:\n\n- A new unique index is created and used to substitute the PK.\n- The primary key is dropped and re-created with the new column order.\n- The temporary index is dropped, as well as the index on the subsidiary id that isn’t required anymore.\n\n## Functions\n\nMySQL uses a case-insensitive collation per default. Further, MySQL did not support function-based indexes prior version 5.7. In that case, you don’t need a function-based index, a regular one will do as well:\n\n```\nCREATE INDEX emp_name ON employees (last_name)\n```\n\nStarting with 5.7, computed columns can be indexed in MySQL:\n\nUser-defined functions cannot be used in generated columns—not even when they are deterministic and declared deterministic.\n\n```\nCREATE FUNCTION get_age(date_of_birth DATE)\nRETURNS INTEGER NO SQL\nRETURN TIMESTAMPDIFF(YEAR,date_of_birth,CURDATE());\n```\n\n```\nALTER TABLE employees\n ADD COLUMN last_name_up VARCHAR(255) AS (UPPER(last_name));\n```\n\n```\nCREATE INDEX emp_up_name ON employees (last_name_up);\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 5802, "slov": 827, "odkazu": 67, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:04", "sha256": "d26381424caf5a276512b20e94cbdbb041b70af21a22924e7c867b5f41d885f2", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/oracle", "titulek": "Example Scripts for Oracle", "h1": "Oracle Example Scripts", "popis": "CREATE & INSERT statements to create the Use The Index, Luke Oracle example database.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/oracle", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Oracle", "og:description": "CREATE & INSERT statements to create the Use The Index, Luke Oracle example database.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema"], "osnova": [{"uroven": 1, "text": "Oracle Example Scripts"}, {"uroven": 2, "text": "Contents"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Oracle Example Scripts\n\n---\n\nThe scripts provided in this appendix are ready to run and were tested on the Oracle database release 11gR2. Most of the examples will also work on 10g.\n\n## Contents\n\n1. *[The `where` clause](/sql/example-schema/oracle/where-clause)*\n2. *[Testing and Scalability](/sql/example-schema/oracle/performance-testing-scalability)*\n3. *[The Join Operation](/sql/example-schema/oracle/join)*\n4. *[Clustering Data](/sql/example-schema/oracle/clustering-data)*\n5. *[Sorting and Grouping](/sql/example-schema/oracle/sorting-grouping)*\n6. *[Partial Results](/sql/example-schema/oracle/partial-results)*\n7. *[Insert, Delete and Update](/sql/example-schema/oracle/dml)*\n8. *[3-Minute Test](/sql/example-schema/oracle/3-minute-quiz)*\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1381, "slov": 158, "odkazu": 67, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:05", "sha256": "229dd53d9dde2d94881b9798177ac51bc0afd4c4d26aa88e41b328674c938820", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/oracle/3-minute-quiz", "titulek": "Example Scripts for Oracle - 3-Minuten Test", "h1": "Oracle Example Scripts for “3-Minute Quiz”", "popis": "CREATE & INSERT statements to create the Oracle example database for the 3-Minuten Test", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/oracle/3-minute-quiz", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Oracle - 3-Minuten Test", "og:description": "CREATE & INSERT statements to create the Oracle example database for the 3-Minuten Test", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Oracle"], "osnova": [{"uroven": 1, "text": "Oracle Example Scripts for “3-Minute Quiz”"}, {"uroven": 2, "text": "Question 1 — DATE Anti-Pattern"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 2 — Indexed Top-N"}, {"uroven": 2, "text": "Question 3 — Column Order"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 4 — LIKE"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 5 — Index Only Scan"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Oracle Example Scripts for “3-Minute Quiz”\n\n---\n\nThis section contains the `create`, `insert` and `select` statements for the “[Test your SQL Know-How in 3 Minutes](/3-minute-quiz)” test. You may want to test yourself before reading this page.\n\nThe `create` and `insert` statements are available in the [example schema archive](/use-the-index-luke.tar.gz).\n\nThe execution plans shown are abbreviated for better readability.\n\n## Question 1 — DATE Anti-Pattern\n\n```\nCREATE INDEX tbl_idx ON tbl (date_column);\n```\n\n```\nSELECT COUNT(*)\n FROM tbl\n WHERE EXTRACT(YEAR FROM date_column) = 2025;\n```\n\n```\nSELECT COUNT(*)\n FROM tbl\n WHERE date_column >= DATE'2025-01-01'\n AND date_column < DATE'2026-01-01';\n```\n\nThe first execution plan performs a full table scan (`TABLE ACCESS FULL`). The second execution plan, on the other hand, performs an `INDEX RANGE SCAN`.\n\n```\n-----------------------------------------------------\n| Id | Operation | Name | A-Rows | Buffers |\n-----------------------------------------------------\n| 0 | SELECT STATEMENT | | 1 | 7 |\n| 1 | SORT AGGREGATE | | 1 | 7 |\n|* 2 | TABLE ACCESS FULL| TBL | 271 | 7 |\n-----------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n\n2 - filter(EXTRACT(YEAR FROM DATE_COLUMN)=2017)\n```\n\n```\n-------------------------------------------------------\n| Id | Operation | Name | A-Rows | Buffers |\n-------------------------------------------------------\n| 0 | SELECT STATEMENT | | 1 | 1 |\n| 1 | SORT AGGREGATE | | 1 | 1 |\n|* 2 | INDEX RANGE SCAN| TBL_IDX | 271 | 1 |\n-------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n\n2 - access(DATE_COLUMN>=TO_DATE('2017-01-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss')\n AND DATE_COLUMN< TO_DATE('2018-01-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss'))\n```\n\n#### Learn More\n\n- [Using Functions in the `WHERE` clause](/sql/where-clause/functions)\n- [Common Anti-Patterns: `DATE`](/sql/where-clause/obfuscation/dates)\n- [Reading Oracle explain plan output](/sql/explain-plan/oracle/operations)\n\n## Question 2 — Indexed Top-N\n\n```\nCREATE INDEX tbl_idx ON tbl (a, date_column);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE a = 12\n ORDER BY date_column DESC\n FETCH FIRST 1 ROW ONLY;\n```\n\nThe query uses the index (`INDEX RANGE SCAN`) and fetches in reverse order (`DECENDING`). The text `NOSORT STOPKEY` means that there is no sort operation needed and that the execution is aborted once the condition (predicate 2) is not met anymore.\n\n`--------------------------------------------------------------------\n| Id | Operation | Name | A-Rows | Buffers |\n--------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 1 | 4 |\n|* 1 | VIEW | | 1 | 4 |\n|* 2 | WINDOW **NOSORT STOPKEY** | | 1 | 4 |\n| 3 | TABLE ACCESS BY INDEX ROWID | TBL | 2 | 4 |\n|* 4 | **INDEX RANGE SCAN DESCENDING**| TBL_IDX | 2 | 2 |\n--------------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n\n1 - filter(\"from$_subquery$_002\".\"rowlimit_$$_rownumber\"<=1)\n2 - filter(ROW_NUMBER() OVER ( ORDER BY DATE_COLUMN DESC )<=1)\n4 - access(\"A\"=12)`\n\n## Question 3 — Column Order\n\n```\nCREATE INDEX tbl_idx ON tbl (a, b);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE a = 38\n AND b = 1;\n```\n\n```\nSELECT *\n FROM tbl\n WHERE b = 1;\n```\n\n```\nDROP INDEX tbl_idx ;\n```\n\n```\nCREATE INDEX tbl_idx ON tbl (b, a);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE a = 38\n AND b = 1;\n```\n\n```\nSELECT *\n FROM tbl\n WHERE b = 1;\n```\n\nThe execution plan of the first query is fine with both indexes:\n\n```\n-------------------------------------------------------------------------\n| Id | Operation | Name | A-Rows | Buffers |\n-------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 1 | 3 |\n| 1 | TABLE ACCESS BY INDEX ROWID BATCHED| TBL | 1 | 3 |\n|* 2 | INDEX RANGE SCAN | TBL_IDX | 1 | 2 |\n-------------------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 2 - access(\"A\"=38 AND \"B\"=1)\n```\n\n```\n-------------------------------------------------------------------------\n| Id | Operation | Name | A-Rows | Buffers |\n-------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 1 | 3 |\n| 1 | TABLE ACCESS BY INDEX ROWID BATCHED| TBL | 1 | 3 |\n|* 2 | INDEX RANGE SCAN | TBL_IDX | 1 | 2 |\n-------------------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 2 - access(\"B\"=1 AND \"A\"=38)\n```\n\nBoth indexes can be used with an `INDEX RANGE SCAN` and without any filter predicates.\n\nThe second query performs an INDEX SKIP SCAN. From the efficiency perspective, this is better than an `INDEX FULL SCAN` but still worse than an `INDEX RANGE SCAN`.\n\n```\n-------------------------------------------------------------------------\n| Id | Operation | Name | A-Rows | Buffers |\n-------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 2 | 4 |\n| 1 | TABLE ACCESS BY INDEX ROWID BATCHED| TBL | 2 | 4 |\n|* 2 | INDEX SKIP SCAN | TBL_IDX | 2 | 2 |\n-------------------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 2 - access(\"B\"=1)\n filter(\"B\"=1)\n```\n\nThe second query can use the index on (b, a) with an `INDEX RANGE SCAN`, however.\n\n```\n-------------------------------------------------------------------------\n| Id | Operation | Name | A-Rows | Buffers |\n-------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 2 | 4 |\n| 1 | TABLE ACCESS BY INDEX ROWID BATCHED| TBL | 2 | 4 |\n|* 2 | INDEX RANGE SCAN | TBL_IDX | 2 | 2 |\n-------------------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 2 - access(\"B\"=1)\n```\n\nReversing the column order in the index doesn’t affect the first query, yet it improves the performance of the second query.\n\n#### Learn More\n\n- [The column order in Multi-Column Indexes](/sql/where-clause/the-equals-operator/concatenated-keys)\n\n## Question 4 — LIKE\n\n```\nCREATE INDEX tbl_idx ON tbl (text);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE text LIKE 'TJ%';\n```\n\nThe execution plan clearly states that it is doing an index range scan. Since the only wild card character is at the very end, the full search term `'TJ'` can be used as [index access predicate](/sql/where-clause/searching-for-ranges/greater-less-between-tuning-sql-access-filter-predicates).\n\n```\n-------------------------------------------------------------------------\n| Id | Operation | Name | A-Rows | Buffers |\n-------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 1 | 4 |\n| 1 | TABLE ACCESS BY INDEX ROWID BATCHED| TBL | 1 | 4 |\n|* 2 | INDEX RANGE SCAN | TBL_IDX | 1 | 3 |\n-------------------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 2 - access(\"TEXT\" LIKE 'TJ%')\n filter(\"TEXT\" LIKE 'TJ%')\n```\n\n#### Learn More\n\n- [A visual explanation why LIKE is slow](/sql/where-clause/searching-for-ranges/like-performance-tuning)\n\n## Question 5 — Index Only Scan\n\n```\nCREATE INDEX tbl_idx ON tbl (a, date_column);\n```\n\n```\nSELECT date_column, count(*)\n FROM tbl\n WHERE a = 38\n GROUP BY date_column;\n```\n\n```\nSELECT date_column, count(*)\n FROM tbl\n WHERE a = 38\n AND b = 1\n GROUP BY date_column;\n```\n\nBoth queries use the index, of course. The difference is that the first query doesn’t access the table, so the first query is much faster.\n\n```\n----------------------------------------------------------\n| Id | Operation | Name | A-Rows | Buffers |\n----------------------------------------------------------\n| 0 | SELECT STATEMENT | | 3 | 2 |\n| 1 | SORT GROUP BY NOSORT| | 3 | 2 |\n|* 2 | INDEX RANGE SCAN | TBL_IDX | 3 | 2 |\n----------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 2 - access(\"A\"=38)\n```\n\n```\n------------------------------------------------------------------\n| Id | Operation | Name | A-Rows | Buffers |\n------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 1 | 3 |\n| 1 | SORT GROUP BY NOSORT | | 1 | 3 |\n|* 2 | TABLE ACCESS BY INDEX ROWID| TBL | 1 | 3 |\n|* 3 | INDEX RANGE SCAN | TBL_IDX | 3 | 1 |\n------------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n 2 - filter(\"B\"=1)\n 3 - access(\"A\"=38)\n```\n\nThe database could, theoretically, use a `FAST FULL INDEX SCAN` for the first query, if selecting a large fraction of the table. The second query, using `INDEX RANGE SCAN` and `TABLE ACCESS BY INDEX ROWID` could be faster in that case. However, this case doesn’t apply here because the first query selects a small fraction from the table.\n\nThe other border case, if the first query doesn’t return any rows, means that the second query would be as fast as the first.\n\nBesides these border cases, the second query must be considerable slower because every row needs a table access — also for those that are filtered by the new condition. Even if the index has a low [clustering factor](/sql/clustering/index-filter-predicates#sb-clustering-factor), it is still about twice as many blocks to read.\n\n#### Learn More\n\n- [Chapter 5*Clustering Data: The Second Power of Indexing*](/sql/clustering)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 7413, "slov": 1170, "odkazu": 74, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:06", "sha256": "e665a10143576e71af98bf759df571d2d24d752a3ab7c4a984b8dc32c478fb14", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/oracle/clustering-data", "titulek": "Example Scripts for Oracle - Clustering Data", "h1": "Oracle Example Scripts for “Clustering Data”", "popis": "CREATE & INSERT statements to create the Oracle example database for Chapter 5, Clustering Data", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/oracle/clustering-data", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Oracle - Clustering Data", "og:description": "CREATE & INSERT statements to create the Oracle example database for Chapter 5, Clustering Data", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Oracle"], "osnova": [{"uroven": 1, "text": "Oracle Example Scripts for “Clustering Data”"}, {"uroven": 2, "text": "Index-Organized Table"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Oracle Example Scripts for “Clustering Data”\n\n---\n\nThis section contains the `create` and `insert` statements to run the examples from [Chapter 5*Clustering Data: The Second Power of Indexing*](/sql/clustering) in an Oracle 11gR2 database.\n\n## Index-Organized Table\n\nThe following creates a second sales table as index-organized table. A secondary index on `SALE_DATE` is created.\n\n```\nCREATE TABLE sales_iot (\n sale_id NUMBER NOT NULL,\n employee_id NUMBER NOT NULL,\n subsidiary_id NUMBER NOT NULL,\n sale_date DATE NOT NULL,\n eur_value NUMBER(17,2) NOT NULL,\n junk CHAR(200),\n CONSTRAINT sales_iot_pk \n PRIMARY KEY (sale_id),\n CONSTRAINT sales_iot_emp_fk \n FOREIGN KEY (subsidiary_id, employee_id)\n REFERENCES employees(subsidiary_id, employee_id)\n) ORGANIZATION INDEX;\n\nEXEC DBMS_RANDOM.SEED(0);\n\nINSERT INTO sales_iot (sale_id\n , subsidiary_id, employee_id\n , sale_date, eur_value, junk)\nSELECT rownum, data.*\n FROM (\n SELECT e.subsidiary_id, e.employee_id\n , TRUNC (SYSDATE \n - DBMS_RANDOM.VALUE(0, 3650)) sale_date\n , DBMS_RANDOM.VALUE(10,10000)/100 eur_value\n , 'junk'\n FROM employees e\n , ( SELECT level n\n FROM dual\n CONNECT BY level < 1800\n ) gen\n WHERE MOD(employee_id, 7) = 4\n AND gen.n < employee_id / 5\n ORDER BY sale_date\n ) data;\n\nCREATE INDEX sales_iot_date ON sales_iot (sale_date);\n\nBEGIN\n DBMS_STATS.GATHER_TABLE_STATS(null, 'SALES_IOT', \n METHOD_OPT=>'for all indexed columns', CASCADE => true);\nEND;\n/\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2051, "slov": 261, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:07", "sha256": "f30905c5090c7c2ad6a050479665dad80119d395e598caac73fb29c7d35a59d1", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/oracle/dml", "titulek": "Example Scripts for Oracle - Insert, Delete and Update", "h1": "Oracle Example Scripts for “Insert, Delete and Update”", "popis": "CREATE & INSERT statements to create the Oracle example database for Chapter 8, DML", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/oracle/dml", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Oracle - Insert, Delete and Update", "og:description": "CREATE & INSERT statements to create the Oracle example database for Chapter 8, DML", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Oracle"], "osnova": [{"uroven": 1, "text": "Oracle Example Scripts for “Insert, Delete and Update”"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Oracle Example Scripts for “Insert, Delete and Update”\n\n---\n\nThis section contains the `create` and `insert` statements to run the examples from [Chapter 8*Modifying Data*](/sql/dml) in an Oracle database. There is only one query that reports all figures for the `insert`, `delete` and `update` sections.\n\n```\nCREATE TABLE scale_write_0 AS\n WITH generator AS (\n SELECT --+ materialize\n level n\n FROM DUAL\n CONNECT BY level <= 10000\n) \n SELECT rownum id1\n , CEIL(DBMS_RANDOM.VALUE(1000000,9999999)) id2\n , CEIL(DBMS_RANDOM.VALUE(1000000,9999999)) id3\n , CEIL(DBMS_RANDOM.VALUE(1000000,9999999)) id4\n , CEIL(DBMS_RANDOM.VALUE(1000000,9999999)) id5\n FROM generator, generator\n WHERE rownum <= 10000000;\n\nCREATE TABLE scale_write_1 AS\nSELECT * from scale_write_0;\n\nCREATE TABLE scale_write_2 AS\nSELECT * from scale_write_0;\n\nCREATE TABLE scale_write_3 AS\nSELECT * from scale_write_0;\n\nCREATE TABLE scale_write_4 AS\nSELECT * from scale_write_0;\n\nCREATE TABLE scale_write_5 AS\nSELECT * from scale_write_0;\n\nCREATE INDEX scale_write_1_1 on scale_write_1(id1);\n\nCREATE INDEX scale_write_2_1 on scale_write_2(id1);\nCREATE INDEX scale_write_2_2 on scale_write_2(id2, id1);\n\nCREATE INDEX scale_write_3_1 on scale_write_3(id1);\nCREATE INDEX scale_write_3_2 on scale_write_3(id2, id1);\nCREATE INDEX scale_write_3_3 on scale_write_3(id3, id2, id1);\n\nCREATE INDEX scale_write_4_1 on scale_write_4(id1);\nCREATE INDEX scale_write_4_2 on scale_write_4(id2, id1);\nCREATE INDEX scale_write_4_3 on scale_write_4(id3, id2, id1);\nCREATE INDEX scale_write_4_4 on scale_write_4(id4, id3, id2\n , id1);\n\nCREATE INDEX scale_write_5_1 on scale_write_5(id1);\nCREATE INDEX scale_write_5_2 on scale_write_5(id2, id1);\nCREATE INDEX scale_write_5_3 on scale_write_5(id3, id2, id1);\nCREATE INDEX scale_write_5_4 on scale_write_5(id4, id3, id2\n , id1);\nCREATE INDEX scale_write_5_5 on scale_write_5(id5, id4, id3\n , id2, id1);\n\nbegin\n DBMS_STATS.GATHER_TABLE_STATS(user\n , 'SCALE_WRITE_0', cascade=>true);\n DBMS_STATS.GATHER_TABLE_STATS(user\n , 'SCALE_WRITE_1', cascade=>true);\n DBMS_STATS.GATHER_TABLE_STATS(user\n , 'SCALE_WRITE_2', cascade=>true);\n DBMS_STATS.GATHER_TABLE_STATS(user\n , 'SCALE_WRITE_3', cascade=>true);\n DBMS_STATS.GATHER_TABLE_STATS(user\n , 'SCALE_WRITE_4', cascade=>true);\n DBMS_STATS.GATHER_TABLE_STATS(user\n , 'SCALE_WRITE_5', cascade=>true);\nend;\n/\n```\n\n```\ncreate or replace\nPACKAGE test_write_scalability IS\n TYPE piped_output IS\n RECORD ( idxes NUMBER\n , cmnd VARCHAR2(255)\n , seconds NUMBER\n , id1 NUMBER);\n TYPE piped_output_table IS TABLE OF piped_output;\n\n FUNCTION run(n IN number)\n RETURN test_write_scalability.piped_output_table PIPELINED;\nEND;\n\ncreate or replace\nPACKAGE BODY test_write_scalability\nIS\n TYPE tmp IS TABLE OF piped_output INDEX BY PLS_INTEGER;\n\nFUNCTION run_insert(tbl IN NUMBER, d1 IN NUMBER)\n RETURN VARCHAR2\nAS\n r2 NUMBER := CEIL(DBMS_RANDOM.VALUE(1000000,9999999));\n r3 NUMBER := CEIL(DBMS_RANDOM.VALUE(1000000,9999999));\n r4 NUMBER := CEIL(DBMS_RANDOM.VALUE(1000000,9999999));\n r5 NUMBER := CEIL(DBMS_RANDOM.VALUE(1000000,9999999));\nBEGIN\n CASE tbl\n WHEN 0 THEN \n INSERT INTO scale_write_0 (id1, id2, id3, id4, id5)\n VALUES ( d1, r2, r3, r4, r5);\n WHEN 1 THEN \n INSERT INTO scale_write_1 (id1, id2, id3, id4, id5)\n VALUES ( d1, r2, r3, r4, r5);\n WHEN 2 THEN \n INSERT INTO scale_write_2 (id1, id2, id3, id4, id5)\n VALUES ( d1, r2, r3, r4, r5);\n WHEN 3 THEN \n INSERT INTO scale_write_3 (id1, id2, id3, id4, id5)\n VALUES ( d1, r2, r3, r4, r5);\n WHEN 4 THEN \n INSERT INTO scale_write_4 (id1, id2, id3, id4, id5)\n VALUES ( d1, r2, r3, r4, r5);\n WHEN 5 THEN \n INSERT INTO scale_write_5 (id1, id2, id3, id4, id5)\n VALUES ( d1, r2, r3, r4, r5);\n END CASE;\n RETURN 'insert';\nEND;\n\nFUNCTION run_delete(tbl IN NUMBER, d1 IN NUMBER)\nRETURN VARCHAR2\nAS\nBEGIN\n CASE tbl\n WHEN 1 THEN \n DELETE FROM scale_write_1 WHERE id1 = d1;\n WHEN 2 THEN \n DELETE FROM scale_write_2 WHERE id1 = d1;\n WHEN 3 THEN \n DELETE FROM scale_write_3 WHERE id1 = d1;\n WHEN 4 THEN \n DELETE FROM scale_write_4 WHERE id1 = d1;\n WHEN 5 THEN \n DELETE FROM scale_write_5 WHERE id1 = d1;\n ELSE NULL;\n END CASE;\n IF SQL%ROWCOUNT > 0 THEN RETURN 'delete';\n ELSE RETURN NULL; END IF;\nEND;\n\nFUNCTION run_update_all(tbl IN NUMBER, d1 IN NUMBER)\nRETURN VARCHAR2\nAS \n r2 NUMBER := CEIL(DBMS_RANDOM.VALUE(1000000,9999999));\n r3 NUMBER := CEIL(DBMS_RANDOM.VALUE(1000000,9999999));\n r4 NUMBER := CEIL(DBMS_RANDOM.VALUE(1000000,9999999));\n r5 NUMBER := CEIL(DBMS_RANDOM.VALUE(1000000,9999999));\nBEGIN\n CASE tbl\n WHEN 1 THEN \n UPDATE scale_write_1\n SET id2 = r2, id3=r3, id4=r4, id5=r5 WHERE id1=d1;\n WHEN 2 THEN \n UPDATE scale_write_2\n SET id2 = r2, id3=r3, id4=r4, id5=r5 WHERE id1=d1;\n WHEN 3 THEN \n UPDATE scale_write_3\n SET id2 = r2, id3=r3, id4=r4, id5=r5 WHERE id1=d1;\n WHEN 4 THEN \n UPDATE scale_write_4\n SET id2 = r2, id3=r3, id4=r4, id5=r5 WHERE id1=d1;\n WHEN 5 THEN \n UPDATE scale_write_5\n SET id2 = r2, id3=r3, id4=r4, id5=r5 WHERE id1=d1;\n ELSE NULL;\n END CASE; \n IF SQL%ROWCOUNT > 0 THEN RETURN 'update all';\n ELSE RETURN NULL; END IF;\nEND;\n\nFUNCTION run_update_one(tbl IN NUMBER, d1 IN NUMBER)\nRETURN VARCHAR2\nAS\n r NUMBER := CEIL(DBMS_RANDOM.VALUE(1000000,9999999));\nBEGIN\n CASE tbl\n WHEN 1 THEN -- no index updated\n UPDATE scale_write_1 SET id2 = r WHERE id1=d1;\n WHEN 2 THEN -- one index updated\n UPDATE scale_write_2 SET id2 = r WHERE id1=d1;\n WHEN 3 THEN -- one index updated\n UPDATE scale_write_3 SET id3 = r WHERE id1=d1;\n WHEN 4 THEN -- one index updated\n UPDATE scale_write_4 SET id4 = r WHERE id1=d1;\n WHEN 5 THEN -- one index updated\n UPDATE scale_write_5 SET id5 = r WHERE id1=d1;\n ELSE NULL;\n END CASE; \n IF SQL%ROWCOUNT > 0 THEN RETURN 'update one';\n ELSE RETURN NULL; END IF;\nEND;\n\nFUNCTION run(n IN NUMBER)\n RETURN test_write_scalability.piped_output_table PIPELINED\nIS\n PRAGMA AUTONOMOUS_TRANSACTION;\n rec test_write_scalability.piped_output;\n\n id1 NUMBER;\n tbl NUMBER;\n strt TIMESTAMP(9);\n cmnd NUMBER;\n d1 NUMBER;\n q NUMBER;\n begn NUMBER;\n iter NUMBER;\n r NUMBER;\n tmp DATE;\n\nBEGIN\n SELECT CEIL((max(id1)-min(id1))/4) into q FROM scale_write_1;\n\n iter := n;\n WHILE iter > 0 LOOP\n FOR cmd IN 0 .. 3 LOOP\n r := TRUNC(DBMS_RANDOM.VALUE(0, q));\n FOR tbl IN 0 .. 5 LOOP\n strt := systimestamp;\n rec.cmnd := \n CASE cmd\n WHEN 0 THEN run_update_all(tbl, r + cmd*q)\n WHEN 1 THEN run_insert (tbl, r + cmd*q)\n WHEN 2 THEN run_update_one(tbl, r + cmd*q)\n WHEN 3 THEN run_delete (tbl, r + cmd*q)\n END;\n IF rec.cmnd IS NOT NULL THEN\n COMMIT;\n -- magic: convert INTERVAL DAYS TO SECONDS\n -- to NUMERIC (seconds)\n tmp := sysdate;\n rec.seconds := tmp \n + (systimestamp - strt)*86400\n - tmp; \n rec.idxes := tbl;\n rec.id1 := r + cmd*q;\n PIPE ROW(rec);\n END IF;\n END LOOP;\n END LOOP;\n iter := iter - 1;\n END LOOP;\n COMMIT;\n RETURN;\nEND run;\nEND test_write_scalability;\n```\n\n```\nSELECT *\n FROM (SELECT idxes, cmnd, seconds\n FROM TABLE (test_write_scalability.run(1000)\n )\n PIVOT (AVG(seconds)\n FOR cmnd\n IN ('insert', 'delete', 'update all', 'update one')\n );\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 7491, "slov": 1013, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:08", "sha256": "b9138f3bf0bb85e409649cbf20f67169a9bc0c51e0b9ff72cf263dc25d11ad32", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/oracle/join", "titulek": "Example Scripts for Oracle - The Join Operation", "h1": "Oracle Example Scripts for “The Join Operation”", "popis": "CREATE & INSERT statements to create the Oracle example database for Chapter 4, The Join Operation", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/oracle/join", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Oracle - The Join Operation", "og:description": "CREATE & INSERT statements to create the Oracle example database for Chapter 4, The Join Operation", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Oracle"], "osnova": [{"uroven": 1, "text": "Oracle Example Scripts for “The Join Operation”"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Oracle Example Scripts for “The Join Operation”\n\n---\n\nThis section contains the `create`, `insert` and PL/SQL code to run the examples from [Chapter 4*The Join Operation*](/sql/join) in an Oracle 11gR2 database.\n\n```\nCREATE TABLE sales (\n sale_id NUMBER NOT NULL,\n employee_id NUMBER NOT NULL,\n subsidiary_id NUMBER NOT NULL,\n sale_date DATE NOT NULL,\n eur_value NUMBER(17,2) NOT NULL,\n product_id NUMBER NOT NULL,\n quantity number NOT NULL,\n junk CHAR(200),\n CONSTRAINT sales_pk \n PRIMARY KEY (sale_id),\n CONSTRAINT sales_emp_fk \n FOREIGN KEY (subsidiary_id, employee_id)\n REFERENCES employees(subsidiary_id, employee_id)\n);\n\nEXEC DBMS_RANDOM.SEED(0);\n\nINSERT INTO sales (sale_id\n , subsidiary_id, employee_id\n , sale_date, eur_value\n , product_id, quantity\n , junk)\nSELECT rownum, data.*\n FROM (\n SELECT e.subsidiary_id, e.employee_id\n , TRUNC(SYSDATE\n - DBMS_RANDOM.VALUE(0, 3650)) sale_date\n , DBMS_RANDOM.VALUE(10,10000)/100 eur_value\n , TRUNC(DBMS_RANDOM.VALUE(1,25)) product_id\n , TRUNC(DBMS_RANDOM.VALUE(1,5)) quantity\n , 'junk'\n FROM employees e\n , ( SELECT level n\n FROM dual\n CONNECT BY level < 1800\n ) gen\n WHERE MOD(employee_id, 7) = 4\n AND gen.n < employee_id / 5\n ORDER BY sale_date\n ) data\n WHERE TO_CHAR(sale_date, 'D') \n != TO_CHAR(TO_DATE('2012-01-01', 'YYYY-MM-DD'), 'D');\n\nBEGIN\n DBMS_STATS.GATHER_TABLE_STATS(null, 'SALES', \n METHOD_OPT=>'for all indexed columns', CASCADE => true);\nEND;\n/\n```\n\nNotes:\n\n- The rows are inserted chronologically to reflect a natural table growth.\n- Only a small fraction of employees have sales at all.\n- No sales on Sundays. This is, however, hard to accomplish because [Oracle’s `TO_CHAR` is sensitive to `NLS_TERRITORY`](https://renenyffenegger.ch/notes/development/databases/Oracle/SQL/functions/type-conversion/to/char/index) settings. Using `TO_CHAR` on both sides cancels that effect—so, it is implemented by a comparison of the weekday for a known Sunday (1st Jan 2012).\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2555, "slov": 325, "odkazu": 67, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:09", "sha256": "1d90dfeabcb3992a9d6a846209978fb3b7a7f92eba13f1cadaf9c02bfbc18e34", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://renenyffenegger.ch/notes/development/databases/Oracle/SQL/functions/type-conversion/to/char/index", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/oracle/partial-results", "titulek": "Example Scripts for Oracle - Partial Results", "h1": "Oracle Example Scripts for “Partial Results”", "popis": "CREATE & INSERT statements to create the Oracle example database for Chapter 7, Partial Results", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/oracle/partial-results", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Oracle - Partial Results", "og:description": "CREATE & INSERT statements to create the Oracle example database for Chapter 7, Partial Results", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Oracle"], "osnova": [{"uroven": 1, "text": "Oracle Example Scripts for “Partial Results”"}, {"uroven": 2, "text": "Querying Top-N Rows"}, {"uroven": 2, "text": "Paging Through Results"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Oracle Example Scripts for “Partial Results”\n\n---\n\nThis section contains the `create` and `insert` statements to run the examples from [Chapter 7*Partial Results*](/sql/partial-results) in an Oracle database.\n\nThe test approach for the scalability of Top-N queries is the same as used in the “[Testing and Scalability](/sql/example-schema/oracle/performance-testing-scalability)” chapter.\n\n## Querying Top-N Rows\n\nFirst, using a pipelined Top-N with an index covering the `order by` clause:\n\n```\nCREATE INDEX scale_slow ON scale_data (section, id1, id2);\n\nSELECT *\n FROM TABLE(test_scalability.run(\n 'SELECT * FROM (SELECT id2, id1 '\n || 'FROM scale_data '\n || 'WHERE section=:1 '\n || 'ORDER BY id2, id1) '\n || ' WHERE rownum <= 100', 10));\n```\n\nThen, using an index for the `where` clause only:\n\n```\n DROP INDEX scale_slow;\nCREATE INDEX scale_fast ON scale_data (SECTION, id2, id1);\n\nSELECT *\n FROM TABLE(test_scalability.run(\n 'SELECT * FROM (SELECT id2, id1 '\n || 'FROM scale_data '\n || 'WHERE section=:1 '\n || 'ORDER BY id2, id1) '\n || ' WHERE rownum <= 100', 10));\n```\n\n## Paging Through Results\n\nThe following function uses both methods to fetch the result page-wise. The select statement in the end prepares the statistics on screen.\n\n```\nCREATE OR REPLACE\nPACKAGE test_topn_scalability IS\n TYPE piped_output IS\n RECORD ( section NUMBER\n , mde NUMBER\n , page NUMBER\n , seconds INTERVAL DAY TO SECOND);\n TYPE piped_output_table IS TABLE OF piped_output;\n\n FUNCTION run(n IN number)\n RETURN test_topn_scalability.piped_output_table PIPELINED;\nEND;\n/\n\nCREATE OR REPLACE\nPACKAGE BODY test_topn_scalability\nIS\n TYPE tmp IS TABLE OF piped_output INDEX BY PLS_INTEGER;\n\nFUNCTION run(n IN NUMBER)\n RETURN test_topn_scalability.piped_output_table PIPELINED\nIS\n TYPE last_fetched IS RECORD (id2 NUMBER, id1 NUMBER);\n last last_fetched;\n rec test_topn_scalability.piped_output;\n TYPE sec_array IS TABLE OF last_fetched INDEX BY PLS_INTEGER;\n\n iter NUMBER;\n sec NUMBER;\n strt TIMESTAMP(9);\n mde NUMBER;\n page NUMBER;\n cont sec_array;\n\n CURSOR s_restart (sec IN NUMBER, page IN NUMBER) \n IS SELECT id2, id1\n FROM (SELECT id2, id1, rownum rn\n FROM scale_data\n WHERE section = sec\n ORDER BY id2, id1)\n WHERE rownum <= 100\n AND rn > page*100; \n\n CURSOR s_continue (sec IN NUMBER, c IN last_fetched)\n IS SELECT *\n FROM (SELECT id2, id1\n FROM scale_data\n WHERE section = sec\n AND id2 >= c.id2\n AND ( \n (id2 = c.id2 AND id1 > c.id1)\n OR \n (id2 > c.id2)\n )\n ORDER BY id2, id1)\n WHERE rownum <= 100;\nBEGIN\n iter := 0;\n WHILE iter <= n LOOP\n FOR mde IN 0 .. 1 LOOP\n FOR page IN 0 .. 100 LOOP\n FOR sec IN 0 .. 300 LOOP\n strt := systimestamp;\n IF (mde = 0 OR page = 0) THEN\n FOR r IN s_restart (sec, page) LOOP\n last := r;\n END LOOP;\n ELSE\n FOR r IN s_continue (sec, cont(sec)) LOOP\n last := r;\n END LOOP;\n END IF;\n \n rec.seconds := (systimestamp - strt);\n rec.section := sec;\n rec.page := page;\n rec.mde := mde;\n PIPE ROW(rec);\n\n cont(sec) := last;\n\n END LOOP;\n END LOOP;\n END LOOP;\n iter := iter +1;\n END LOOP;\n RETURN;\nEND run;\nEND test_topn_scalability;\n/\n\nSELECT section, mde, page, sum(extract(second from seconds))\n FROM TABLE(test_topn_scalability.run(10))\n WHERE section = 10\n GROUP BY section, mde, page\n ORDER BY section, mde, page;\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3794, "slov": 561, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:10", "sha256": "97b798ff8237ecc3516f34316874e5ddb250a847b9a73c9009afbee5362d5a3a", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/oracle/performance-testing-scalability", "titulek": "Example Scripts for Oracle - Testing and Scalability", "h1": "Oracle Example Scripts for “Testing and Scalability”", "popis": "CREATE & INSERT statements to create the Oracle example database for Chapter 3, Testing and Scalability", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/oracle/performance-testing-scalability", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Oracle - Testing and Scalability", "og:description": "CREATE & INSERT statements to create the Oracle example database for Chapter 3, Testing and Scalability", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Oracle"], "osnova": [{"uroven": 1, "text": "Oracle Example Scripts for “Testing and Scalability”"}, {"uroven": 4, "text": "Warning"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Oracle Example Scripts for “Testing and Scalability”\n\n---\n\nThis section contains the `create`, `insert` and PL/SQL code to run the scalability test from [Chapter 3*Performance and Scalability*](/sql/testing-scalability) in an Oracle 11gR2 database.\n\n#### Warning\n\nThese scripts will create large objects in the database and produce a huge amount of redo logs.\n\n```\nCREATE TABLE scale_data (\n section NUMBER NOT NULL,\n id1 NUMBER NOT NULL,\n id2 NUMBER NOT NULL\n);\n```\n\nNote:\n\n- There is no primary key (to keep the data generation simple)\n- There is no index (yet). That’s done after filling the table\n- There is no “junk” column because the table is actually not accessed during testing\n\n```\nINSERT INTO scale_data\nSELECT sections.n, gen.x, CEIL(DBMS_RANDOM.VALUE(0, 100)) \n FROM (\n SELECT level - 1 n\n FROM DUAL\n CONNECT BY level < 300) sections\n , (\n SELECT level x\n FROM DUAL\n CONNECT BY level < 900000) gen\n WHERE gen.x <= sections.n * 3000;\n```\n\nNote:\n\n- This code generates 300 sections, you may need to adjust the number for your environment. If you increase the number of sections, you must also increase the second generator. It must generate at least `3000 x ` records.\n- The table will need some gigabytes\n\n```\nCREATE INDEX scale_slow ON scale_data (section, id1, id2);\n\nBEGIN\n DBMS_STATS.GATHER_TABLE_STATS(null, 'SCALE_DATA' \n , CASCADE => true);\nEND;\n/\n```\n\nNote:\n\n- The index will also need some gigabytes\n\n```\nCREATE OR REPLACE PACKAGE test_scalability IS\n TYPE piped_output IS RECORD ( section NUMBER\n , seconds NUMBER\n , cnt_rows NUMBER);\n TYPE piped_output_table IS TABLE OF piped_output;\n\n FUNCTION run(sql_txt IN varchar2, n IN number)\n RETURN test_scalability.piped_output_table PIPELINED;\nEND;\n/\n\nCREATE OR REPLACE PACKAGE BODY test_scalability\nIS\n TYPE tmp IS TABLE OF piped_output INDEX BY PLS_INTEGER;\n\n FUNCTION run(sql_txt IN VARCHAR2, n IN NUMBER)\n RETURN test_scalability.piped_output_table PIPELINED\n IS\n rec test_scalability.tmp;\n r test_scalability.piped_output;\n iter NUMBER;\n sec NUMBER;\n strt NUMBER;\n exec_txt VARCHAR2(4000);\n cnt NUMBER;\n BEGIN\n exec_txt := 'select count(*) from (' || sql_txt || ')';\n iter := 0;\n WHILE iter <= n LOOP\n sec := 0;\n WHILE sec < 300 LOOP\n IF iter = 0 THEN\n rec(sec).seconds := 0;\n rec(sec).section := sec;\n rec(sec).cnt_rows := 0;\n END IF;\n strt := DBMS_UTILITY.GET_TIME;\n EXECUTE IMMEDIATE exec_txt INTO cnt USING sec;\n rec(sec).seconds := rec(sec).seconds \n + (DBMS_UTILITY.GET_TIME - strt)/100;\n rec(sec).cnt_rows:= rec(sec).cnt_rows + cnt;\n IF iter = n THEN\n PIPE ROW(rec(sec));\n END IF;\n sec := sec +1;\n END LOOP;\n iter := iter +1;\n END LOOP;\n RETURN;\n END;\nEND test_scalability;\n/\n```\n\nNote:\n\n- The `TEST_SCALABILITY.RUN` function returns a table\n- It’s hardcoded to run the test for 300 sections (highlighted).\n- The number of iterations is configurable\n\nThe following `select` calls the function and passes the query as string:\n\n```\nSELECT *\n FROM TABLE(test_scalability.run(\n 'SELECT * ' \n || 'FROM scale_data '\n ||'WHERE section=:1 '\n || 'AND id2=CEIL(DBMS_RANDOM.value(1,100))', 10));\n```\n\nThe counter test, with a better index, can be done like that:\n\n```\nDROP INDEX scale_slow;\nCREATE INDEX scale_fast ON scale_data (section, id2, id1);\n\nBEGIN\n DBMS_STATS.GATHER_TABLE_STATS(null, 'SCALE_DATA' \n , CASCADE => true);\nEND;\n/\n\nSELECT *\n FROM TABLE(test_scalability.run(\n 'SELECT * ' \n || 'FROM scale_data '\n ||'WHERE section=:1 '\n || 'AND id2=CEIL(DBMS_RANDOM.value(1,10))', 10));\n```\n\nNote:\n\n- The `SCALE_SLOW` index is dropped to prevent “ORA-01408: such column list already indexed”.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 4121, "slov": 574, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:11", "sha256": "3a1d941ebd1640389c5e35ec45105778f22069dec0131db561f33ad9728cf29b", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/oracle/sorting-grouping", "titulek": "Example Scripts for Oracle - Sorting and Grouping", "h1": "Oracle Example Scripts for “Sorting and Grouping”", "popis": "CREATE & INSERT statements to create the Oracle example database for Chapter 5, Sorting and Grouping", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/oracle/sorting-grouping", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Oracle - Sorting and Grouping", "og:description": "CREATE & INSERT statements to create the Oracle example database for Chapter 5, Sorting and Grouping", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Oracle"], "osnova": [{"uroven": 1, "text": "Oracle Example Scripts for “Sorting and Grouping”"}, {"uroven": 2, "text": "Indexed Order By"}, {"uroven": 2, "text": "Indexed Group By"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Oracle Example Scripts for “Sorting and Grouping”\n\n---\n\nThis section contains the `create`, `insert` and PL/SQL code to run the examples from [Chapter 6*Sorting and Grouping*](/sql/sorting-grouping) in an Oracle 11gR2 database.\n\n## Indexed Order By\n\n```\nSELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= TRUNC(sysdate) - INTERVAL '1' DAY\n ORDER BY product_id\n```\n\nGathering new statistics is good practice after changing indexes:\n\n```\nBEGIN\n DBMS_STATS.GATHER_TABLE_STATS(null, 'SALES', \n METHOD_OPT=>'for all indexed columns', CASCADE => true);\nEND;\n/\n```\n\n## Indexed Group By\n\nThere is one particular problem in the Oracle database (at least 11g-19c) that appears when ordering the grouped result in reverse index order:\n\n```\nSELECT product_id, sum(eur_value)\n FROM sales\n WHERE sale_date = TRUNC(sysdate) - INTERVAL '1' DAY\n GROUP BY product_id\n ORDER BY product_id DESC;\n```\n\nAlthough it can use the index when ordering in index order:\n\n```\nSELECT product_id, sum(eur_value)\n FROM sales\n WHERE sale_date = TRUNC(sysdate) - INTERVAL '1' DAY\n GROUP BY product_id\n ORDER BY product_id ASC;\n```\n\nThere is no known workaround for this problem.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1770, "slov": 238, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:12", "sha256": "8d1586099c10709045166f005367d0ad55528489bcdbfccc821b6a5d4616cbf3", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/oracle/where-clause", "titulek": "Example Scripts for Oracle - The WHERE Clause", "h1": "Oracle Example Scripts for “The Where Clause”", "popis": "CREATE & INSERT statements to create the Use The Index, Luke Oracle example database for Chapter 2, The Where Clause", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/oracle/where-clause", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Oracle - The WHERE Clause", "og:description": "CREATE & INSERT statements to create the Use The Index, Luke Oracle example database for Chapter 2, The Where Clause", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Oracle"], "osnova": [{"uroven": 1, "text": "Oracle Example Scripts for “The Where Clause”"}, {"uroven": 2, "text": "The Equals Operator"}, {"uroven": 3, "text": "Surrogate Keys"}, {"uroven": 3, "text": "Concatenated Keys"}, {"uroven": 3, "text": "Slow Indexes, Part II"}, {"uroven": 2, "text": "Functions"}, {"uroven": 3, "text": "Case-Insensitive Search"}, {"uroven": 3, "text": "User-Defined Functions"}, {"uroven": 2, "text": "Searching for Ranges"}, {"uroven": 2, "text": "Indexing NULL"}, {"uroven": 2, "text": "Emulating Partial Indexes"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Oracle Example Scripts for “The Where Clause”\n\n---\n\n## The Equals Operator\n\n### Surrogate Keys\n\nThe following script creates the `EMPLOYEES` table with 1000 entries.\n\n```\nCREATE TABLE employees (\n employee_id NUMBER NOT NULL,\n first_name VARCHAR2(1000) NOT NULL,\n last_name VARCHAR2(1000) NOT NULL,\n date_of_birth DATE NOT NULL,\n phone_number VARCHAR2(1000) NOT NULL,\n junk CHAR(1000) DEFAULT 'JUNK',\n CONSTRAINT employees_pk PRIMARY KEY (employee_id)\n);\n```\n\n```\nINSERT INTO employees (employee_id, first_name,\n last_name, date_of_birth, \n phone_number)\nSELECT level, \n DBMS_RANDOM.STRING('u', 1) || \n DBMS_RANDOM.STRING('l', DBMS_RANDOM.value(2,10)),\n DBMS_RANDOM.STRING('u', 1) || \n DBMS_RANDOM.STRING('l', DBMS_RANDOM.value(2,10)),\n SYSDATE - (DBMS_RANDOM.normal() * 365 * 10) - 40 * 365,\n TRUNC(DBMS_RANDOM.VALUE(1000,10000))\n FROM DUAL \n CONNECT BY level <= 1000;\n```\n\n```\nUPDATE employees \n SET first_name='MARKUS', \n last_name='WINAND'\n WHERE employee_id=123;\n```\n\n```\nBEGIN\n DBMS_STATS.GATHER_TABLE_STATS(null, 'EMPLOYEES', \n METHOD_OPT=>'for all indexed columns', CASCADE => true);\nEND;\n```\n\nNotes:\n\n- The `JUNK` column is used to have a realistic row length. Because it’s data type is `CHAR`, as opposed to `VARCHAR2`, it always needs the 1000 bytes it can hold. Without this column the table would become unrealistically small and many demonstrations would not work.\n- Random data is filled into the table, with exception to my entry, that is updated after the insert.\n- Table and index [statistics](/sql/where-clause/the-equals-operator/slow-indexes-part-ii#sb-statistics) are gathered so that the [optimizer](/sql/where-clause/the-equals-operator/slow-indexes-part-ii#sb-optimizer) knows a little bit about the table’s content.\n\n### Concatenated Keys\n\nThis script changes the `EMPLOYEES` table so that it reflects the situation after the merger with Very Big Company:\n\n`-- add subsidiary_id and update existing records\nALTER TABLE employees ADD subsidiary_id NUMBER;``UPDATE employees SET subsidiary_id = 30;``ALTER TABLE employees MODIFY subsidiary_id NOT NULL;``-- change the PK\nALTER TABLE employees DROP PRIMARY KEY;``ALTER TABLE employees ADD CONSTRAINT employees_pk \n PRIMARY KEY (employee_id, subsidiary_id);``-- generate more records (Very Big Company)\nINSERT INTO employees (employee_id, first_name, \n last_name, date_of_birth, \n phone_number, subsidiary_id)\nSELECT level, \n DBMS_RANDOM.STRING('u', 1) || \n DBMS_RANDOM.STRING('l', DBMS_RANDOM.value(2,10)),\n DBMS_RANDOM.STRING('u', 1) || \n DBMS_RANDOM.STRING('l', DBMS_RANDOM.value(2,10)),\n SYSDATE - (DBMS_RANDOM.normal() * 365 * 10) - 40 * 365,\n TRUNC(DBMS_RANDOM.VALUE(1000,10000)), \n TRUNC(DBMS_RANDOM.VALUE(1,level/9000*29))\nFROM DUAL CONNECT BY level <= 9000;``BEGIN\n DBMS_STATS.GATHER_TABLE_STATS(null, 'EMPLOYEES', \n METHOD_OPT=>'for all indexed columns', CASCADE => true);\nEND;`\n\nNotes:\n\n- The new primary key just extended by the `SUBSIDIARY_ID`; that is, the `EMPLOYEE_ID` remains in the first position.\n- The new records are randomly assigned to the subsidiaries 1 through 29.\n- The table and index are analyzed again to make the optimizer aware of the grown data volume.\n\nThe next script introduces the index on `SUBSIDIARY_ID` to support the query for all employees of one particular subsidiary:\n\n```\nCREATE INDEX emp_sub_id ON employees (subsidiary_id);\n```\n\n```\nBEGIN\n DBMS_STATS.GATHER_TABLE_STATS(null, 'EMPLOYEES', \n METHOD_OPT=>'for all indexed columns', CASCADE => true);\nEND;\n```\n\nNotes:\n\n- The table and all indexes are analyzed again. In that particular case it would be sufficient to analyse only the new index.\n\nAlthough that gives decent performance, it’s better to use the index that supports the primary key:\n\nOracle 11g\n\n`-- use tmp index to support the PK\nCREATE INDEX employee_pk_tmp \n ON employees (subsidiary_id, employee_id, 1);``ALTER TABLE employees \n MODIFY CONSTRAINT employees_pk \n USING INDEX employee_pk_tmp;``-- recreate the pk index as needed (automatically done)\n--DROP INDEX employee_pk;``CREATE UNIQUE INDEX employee_pk \n ON employees (subsidiary_id, employee_id);``-- change the constraint to use the new index\nALTER TABLE employees \n MODIFY CONSTRAINT employees_pk \n USING INDEX employee_pk;``-- drop old indexes\nDROP INDEX employee_pk_tmp;``DROP INDEX emp_sub_id;``BEGIN\n DBMS_STATS.GATHER_TABLE_STATS(null, 'EMPLOYEES', \n METHOD_OPT=>'for all indexed columns', CASCADE => true);\nEND;`\n\nOracle 12c\n\n`CREATE UNIQUE INDEX employee_pk_new \n ON employees (subsidiary_id, employee_id);``ALTER TABLE employees \n MODIFY CONSTRAINT employees_pk \n USING INDEX employee_pk_new;``-- drop old indexes\nDROP INDEX emp_sub_id;``-- note: employee_pk is automatically dropped\n\n-- rename new PK index\nALTER INDEX employee_pk_new RENAME TO employee_pk;``BEGIN\n DBMS_STATS.GATHER_TABLE_STATS(null, 'EMPLOYEES', \n METHOD_OPT=>'for all indexed columns', CASCADE => true);\nEND;`\n\nNotes:\n\n- In versions prior 12c, we create a new index with a dummy column and use it to temporarily support the PK. This is required because the Oracle database till 11g doesn’t allow two indexes that include the same columns.\n- Once the old PK index isn’t used by the constraint anymore, it can be dropped and recreated with its new column order.\n- The constraint is changed again to use the new PK index and the temporary index can be dropped—as well as the index on the subsidiary id that isn’t required anymore.\n\n### Slow Indexes, Part II\n\nThe following statement removes some statistics to make my example work.\n\n```\nBEGIN\n DBMS_STATS.DELETE_COLUMN_STATS\n (null, 'EMPLOYEES', 'SUBSIDIARY_ID');\nEND\n```\n\nTo re-create them, use the same procedure as before:\n\n```\nBEGIN\n DBMS_STATS.GATHER_TABLE_STATS(null, 'EMPLOYEES', \n METHOD_OPT=>'for all indexed columns', CASCADE => true);\nEND\n```\n\nThe final statement to create, and analyze, the index on the `LAST_NAME` column:\n\n```\nCREATE INDEX emp_name ON employees (last_name)\n```\n\n```\nBEGIN\n DBMS_STATS.GATHER_TABLE_STATS(null, 'EMPLOYEES', \n METHOD_OPT=>'for all indexed columns', CASCADE => true);\nEND\n```\n\n## Functions\n\n### Case-Insensitive Search\n\nThe randomized names were already created in correct case, just update “my” record:\n\n```\nUPDATE employees \n SET first_name = 'Markus'\n , last_name = 'Winand'\n WHERE employee_id = 123\n AND subsidiary_id = 30;;\n```\n\nThe statement to create the function-based index:\n\n```\nCREATE INDEX emp_up_name ON employees (UPPER(last_name));;\nDROP INDEX emp_name;;\n```\n\nNotes:\n\n- I intentionally break my own best practice to re-analyze the table and all indexes. Just the new index is analyzed (automatically as of 10g).\n\nThe next statement will, as of release 11g, automatically collect the extended statistics for the function-based index.\n\n```\nBEGIN\n DBMS_STATS.GATHER_TABLE_STATS(null, 'EMPLOYEES', \n METHOD_OPT=>'for all indexed columns', CASCADE => true);\nEND;\n/\n```\n\n### User-Defined Functions\n\nDefine a PL/SQL function that calculates the age and attempts to use it in an index:\n\n```\nCREATE FUNCTION get_age(date_of_birth DATE) \nRETURN NUMBER\nAS\nBEGIN\n RETURN TRUNC(MONTHS_BETWEEN(SYSDATE, DATE_OF_BIRTH)/12);\nEND;\n/\n\nCREATE INDEX invalid ON EMPLOYEES (get_age(date_of_birth));\n```\n\nYou should get the error “ORA-30553: The function is not deterministic”.\n\n## Searching for Ranges\n\nCreating the `EMP_TEST` index:\n\n```\nCREATE INDEX emp_test\n ON employees (date_of_birth, subsidiary_id);;\n```\n\nAnd the reverse column order:\n\n```\nCREATE INDEX emp_test\n ON employees (subsidiary_id, date_of_birth);;\n```\n\n## Indexing NULL\n\nThe following re-creates the standard indexes after you have run the examples from the book:\n\n```\n-- for demo purpose we drop the NOT NULL constraint\nALTER TABLE employees MODIFY date_of_birth NULL;;\nCREATE INDEX emp_dob ON employees (date_of_birth);;\n```\n\n```\nDROP INDEX emp_dob_upname;;\n```\n\n```\nCREATE INDEX emp_dob ON employees (date_of_birth, '1');;\n```\n\n## Emulating Partial Indexes\n\n```\nCREATE TABLE messages AS\nSELECT level id\n , CASE WHEN DBMS_RANDOM.NORMAL() < 0.09 THEN 'N' ELSE 'Y' END processed\n , trunc(DBMS_RANDOM.VALUE(0,100)) receiver\n , RPAD('junk', 200) message\n FROM dual \nCONNECT BY level < 999999;;\n```\n\nYou have to update the statistics after creating the function-based index. No statistics, no CBO, no FBI.\n\n```\nbegin\n DBMS_STATS.GATHER_TABLE_STATS( user\n ,'MESSAGES'\n , cascade=>true);\nend;\n/\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 8674, "slov": 1127, "odkazu": 68, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:13", "sha256": "e280c4e58b5ece59255c8b14bf7419206041086e423fc2524a2acaf30fdf6a9e", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/postgresql", "titulek": "Example Scripts for PostgreSQL", "h1": "PostgreSQL Example Scripts", "popis": "CREATE & INSERT statements to create the Use The Index, Luke PostgreSQL example database.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/postgresql", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for PostgreSQL", "og:description": "CREATE & INSERT statements to create the Use The Index, Luke PostgreSQL example database.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema"], "osnova": [{"uroven": 1, "text": "PostgreSQL Example Scripts"}, {"uroven": 2, "text": "Contents"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# PostgreSQL Example Scripts\n\n---\n\nThe scripts provided in this appendix are ready to run and were tested on the PostgreSQL database release 9.0.3. Most of the examples will also work on earlier releases.\n\n## Contents\n\n1. *[The `where` clause](/sql/example-schema/postgresql/where-clause)*\n2. *[Testing and Scalability](/sql/example-schema/postgresql/performance-testing-scalability)*\n3. *[The Join Operation](/sql/example-schema/postgresql/join)*\n4. *[Sorting and Grouping](/sql/example-schema/postgresql/sorting-grouping)*\n5. *[Partial Results](/sql/example-schema/postgresql/partial-results)*\n6. *[Insert, Delete and Update](/sql/example-schema/postgresql/dml)*\n7. *[3-Minute Test](/sql/example-schema/postgresql/3-minute-quiz)*\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1364, "slov": 154, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:14", "sha256": "bb38cab62909caa8960240272aaa872b07bbc09ac4473601f8b3cc5a657c81b8", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/postgresql/3-minute-quiz", "titulek": "Example Scripts for PostgreSQL - 3-Minute Quiz", "h1": "PostgreSQL Example Scripts for “3-Minute Quiz”", "popis": "CREATE & INSERT statements to create the PostgreSQL example database for The 3-Minute Quiz", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/postgresql/3-minute-quiz", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for PostgreSQL - 3-Minute Quiz", "og:description": "CREATE & INSERT statements to create the PostgreSQL example database for The 3-Minute Quiz", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "PostgreSQL"], "osnova": [{"uroven": 1, "text": "PostgreSQL Example Scripts for “3-Minute Quiz”"}, {"uroven": 2, "text": "Question 1 — DATE Anti-Pattern"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 2 — Indexed Top-N"}, {"uroven": 2, "text": "Question 3 — Column Order"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 4 — LIKE"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 5 — Index Only Scan"}, {"uroven": 4, "text": "Tip"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# PostgreSQL Example Scripts for “3-Minute Quiz”\n\n---\n\nThis section contains the `create`, `insert` and `select` statements for the “[Test your SQL Know-How in 3 Minutes](/3-minute-quiz)” test. You may want to test yourself before reading this page.\n\nThe `create` and `insert` statements are available in the [example schema archive](/use-the-index-luke.tar.gz).\n\nThe execution plans shown are abbreviated for better readability.\n\n## Question 1 — DATE Anti-Pattern\n\n```\nCREATE INDEX tbl_idx ON tbl (date_column);\n```\n\n```\nSELECT COUNT(*)\n FROM tbl\n WHERE EXTRACT(YEAR FROM date_column) = 2025;\n```\n\n```\nSELECT COUNT(*)\n FROM tbl\n WHERE date_column >= DATE'2025-01-01'\n AND date_column < DATE'2026-01-01';\n```\n\nThe first execution plan performs a full table scan (`Seq Scan`). The second execution plan, on the other hand, uses the index.\n\n```\n QUERY PLAN\n----------------------------------------------------\nAggregate (actual rows=1 loops=1)\nBuffers: shared hit=3\n-> Seq Scan on tbl (actual rows=271 loops=1)\n Filter: (date_part('year', date_column) = '2017')\n Rows Removed by Filter: 29\n Buffers: shared hit=3\n```\n\n```\n QUERY PLAN\n------------------------------------------------\nAggregate (actual rows=1 loops=1)\nBuffers: shared hit=3\n-> Seq Scan on tbl (actual rows=271 loops=1)\n Filter: ((date_column >= '2017-01-01'::date)\n AND (date_column < '2018-01-01'::date))\n Rows Removed by Filter: 29\n Buffers: shared hit=3\n```\n\n#### Learn More\n\n- [Using Functions in the `WHERE` clause](/sql/where-clause/functions)\n- [Common Anti-Patterns: `DATE`](/sql/where-clause/obfuscation/dates)\n- [Reading PostgreSQL explain plan output](/sql/explain-plan/postgresql/operations)\n\n## Question 2 — Indexed Top-N\n\n```\nCREATE INDEX tbl_idx ON tbl (a, date_column);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE a = 12\n ORDER BY date_column DESC\n FETCH FIRST 1 ROW ONLY;\n```\n\nThe query uses the index (`Index Scan`) and fetches in reverse order (`Backward`). Note that there is no sort operation.\n\n```\n QUERY PLAN\n-------------------------------------------------------------------\nLimit (actual rows=1 loops=1)\nBuffers: shared hit=3\n-> Index Scan Backward using tbl_idx on tbl (actual rows=1 loops=1)\n Index Cond: (a = '12'::numeric)\n Buffers: shared hit=3\n```\n\n## Question 3 — Column Order\n\n```\nCREATE INDEX tbl_idx ON tbl (a, b);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE a = 38\n AND b = 1;\n```\n\n```\nSELECT *\n FROM tbl\n WHERE b = 1;\n```\n\n```\nDROP INDEX tbl_idx ;\n```\n\n```\nCREATE INDEX tbl_idx ON tbl (b, a);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE a = 38\n AND b = 1;\n```\n\n```\nSELECT *\n FROM tbl\n WHERE b = 1;\n```\n\nThe first query can use both indexes efficiently:\n\n```\n QUERY PLAN\n--------------------------------------------------------\nIndex Scan using tbl_idx on tbl (actual rows=1 loops=1)\nIndex Cond: ((a = '38'::numeric) AND (b = '1'::numeric))\nBuffers: shared hit=3\n```\n\n```\n QUERY PLAN\n--------------------------------------------------------\nIndex Scan using tbl_idx on tbl (actual rows=1 loops=1)\nIndex Cond: ((b = '1'::numeric) AND (a = '38'::numeric))\nBuffers: shared hit=3\n```\n\nThe second query reads the entire table (`Seq Scan`). Changing the column order in the index allows both queries to use a `(Bitmap) Index Scan`.\n\n```\n QUERY PLAN\n---------------------------------------\nSeq Scan on tbl (actual rows=2 loops=1)\nFilter: (b = '1'::numeric)\nRows Removed by Filter: 298\nBuffers: shared hit=11\n```\n\n```\n QUERY PLAN\n-------------------------------------------------------\nIndex Scan using tbl_idx on tbl (actual rows=2 loops=1)\nIndex Cond: (b = '1'::numeric)\nBuffers: shared hit=4\n```\n\n#### Learn More\n\n- [The column order in Multi-Column Indexes](/sql/where-clause/the-equals-operator/concatenated-keys)\n- [PostgreSQL operations Index Scan and Bitmap Index Scan](/sql/explain-plan/postgresql/operations)\n\n## Question 4 — LIKE\n\n```\nCREATE INDEX tbl_idx ON tbl (text varchar_pattern_ops);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE text LIKE 'TJ%';\n```\n\nThe execution plan states that it is doing an *Index Scan*. Since there is only wild card character at the very end, the full search text `'TJ'` can be used as [index access predicate](/sql/where-clause/searching-for-ranges/greater-less-between-tuning-sql-access-filter-predicates).\n\nThe [PostgreSQL execution plan does not immediately reveal whether the index access is a full index scan or an index range scan](/sql/explain-plan/postgresql/filter-predicates). To be safe, you can increase the table size (like 100-fold) and check the number of processed blocks for this query (`explain (analyse, buffers)`).\n\n```\n QUERY PLAN\n-------------------------------------------------------\nIndex Scan using tbl_idx on tbl (actual rows=1 loops=1)\nIndex Cond: (((text)::text ~>=~ 'TJ'::text)\n AND ((text)::text ~<~ 'TK'::text))\nFilter: ((text)::text ~~ 'TJ%'::text)\nBuffers: shared hit=3\n```\n\n#### Learn More\n\n- [A visual explanation why LIKE is slow](/sql/where-clause/searching-for-ranges/like-performance-tuning)\n- [PostgreSQL 9.1 Trigram Indexes for anywhere LIKE](https://www.postgresql.org/docs/current/pgtrgm.html)\n\n## Question 5 — Index Only Scan\n\n```\nCREATE INDEX tbl_idx ON tbl (a, date_column);\n```\n\n```\nSELECT date_column, count(*)\n FROM tbl\n WHERE a = 38\n GROUP BY date_column;\n```\n\n```\nSELECT date_column, count(*)\n FROM tbl\n WHERE a = 38\n AND b = 1\n GROUP BY date_column;\n```\n\nAlthough the index is used efficiently in both queries, the first query does perform an [*Index Only Scan*](/sql/clustering/index-only-scan-covering-index). That means the second query performs less efficient as the first.\n\n```\n QUERY PLAN\n---------------------------------------------------------------\nGroupAggregate (actual rows=3 loops=1)\nGroup Key: date_column\nBuffers: shared hit=3\n-> Index Only Scan using tbl_idx on tbl (actual rows=3 loops=1)\n Index Cond: (a = '12'::numeric)\n Heap Fetches: 0\n Buffers: shared hit=3\n```\n\n```\n QUERY PLAN\n-------------------------------------------------------------\nGroupAggregate (actual rows=1 loops=1)\nGroup Key: date_column\nBuffers: shared hit=5\n-> Sort (actual rows=1 loops=1)\n Sort Key: date_column\n Sort Method: quicksort Memory: 25kB\n Buffers: shared hit=5\n -> Bitmap Heap Scan on tbl (actual rows=1 loops=1)\n Recheck Cond: (a = '38'::numeric)\n Filter: (b = '1'::numeric)\n Rows Removed by Filter: 2\n Heap Blocks: exact=3\n Buffers: shared hit=5\n -> Bitmap Index Scan on tbl_idx (actual rows=3 loops=1)\n Index Cond: (a = '38'::numeric)\n Buffers: shared hit=2\n```\n\n#### Tip\n\n- [Chapter 5*Clustering Data: The Second Power of Indexing*](/sql/clustering)\n- [Reading MySQL explain plan output](/sql/explain-plan/mysql/operations)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 6452, "slov": 938, "odkazu": 76, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:15", "sha256": "b2efd6d7956aea27ab95069ab2d2c97813105d000d0587ce4c3bec1f9c6e514a", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://www.postgresql.org/docs/current/pgtrgm.html", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/postgresql/dml", "titulek": "Example Scripts for PostgreSQL - Insert, Delete and Update", "h1": "PostgreSQL Example Scripts for “Insert, Delete and Update”", "popis": "CREATE & INSERT statements to create the PostgreSQL example database for Chapter 8, DML", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/postgresql/dml", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for PostgreSQL - Insert, Delete and Update", "og:description": "CREATE & INSERT statements to create the PostgreSQL example database for Chapter 8, DML", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "PostgreSQL"], "osnova": [{"uroven": 1, "text": "PostgreSQL Example Scripts for “Insert, Delete and Update”"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# PostgreSQL Example Scripts for “Insert, Delete and Update”\n\n---\n\nThis section contains the `create` and `insert` statements to run the examples from [Chapter 8*Modifying Data*](/sql/dml) in an PostgreSQL database. There is only one query that reports all figures for the `insert`, `delete` and `update` sections.\n\n```\nCREATE TABLE scale_write_0 AS (\nSELECT GENERATE_SERIES::numeric id1\n , (random() * 9000000)::numeric + 10000000 id2\n , (random() * 9000000)::numeric + 10000000 id3\n , (random() * 9000000)::numeric + 10000000 id4\n , (random() * 9000000)::numeric + 10000000 id5\n FROM GENERATE_SERIES(10000000, 19999999)\n);\n\nCREATE TABLE scale_write_1\nAS (SELECT * from scale_write_0);\n\nCREATE TABLE scale_write_2\nAS (SELECT * from scale_write_0);\n\nCREATE TABLE scale_write_3\nAS (SELECT * from scale_write_0);\n\nCREATE TABLE scale_write_4\nAS (SELECT * from scale_write_0);\n\nCREATE TABLE scale_write_5\nAS SELECT * from scale_write_0;\n\nCREATE INDEX scale_write_1_1 on scale_write_1(id1);\n\nCREATE INDEX scale_write_2_1 on scale_write_2(id1);\nCREATE INDEX scale_write_2_2 on scale_write_2(id2, id1);\n\nCREATE INDEX scale_write_3_1 on scale_write_3(id1);\nCREATE INDEX scale_write_3_2 on scale_write_3(id2, id1);\nCREATE INDEX scale_write_3_3 on scale_write_3(id3, id2, id1);\n\nCREATE INDEX scale_write_4_1 on scale_write_4(id1);\nCREATE INDEX scale_write_4_2 on scale_write_4(id2, id1);\nCREATE INDEX scale_write_4_3 on scale_write_4(id3, id2, id1);\nCREATE INDEX scale_write_4_4 on scale_write_4(id4, id3, id2\n ,id1);\n\nCREATE INDEX scale_write_5_1 on scale_write_5(id1);\nCREATE INDEX scale_write_5_2 on scale_write_5(id2, id1);\nCREATE INDEX scale_write_5_3 on scale_write_5(id3, id2, id1);\nCREATE INDEX scale_write_5_4 on scale_write_5(id4, id3, id2\n ,id1);\nCREATE INDEX scale_write_5_5 on scale_write_5(id5, id4, id3\n ,id2, id1);\n```\n\n```\nCREATE OR REPLACE\nFUNCTION run_insert(idxes INT, lb INT, ub INT, n INT)\n RETURNS VARCHAR AS\n$$\nDECLARE\n rows_affected INT;\n r2 INT;\n r3 INT;\n r4 INT;\n r5 INT;\n d1 INT;\nBEGIN\n WHILE n > 0 LOOP\n d1 := (random() * (ub-lb))::INT + lb;\n r2 := (random() * 9000000)::INT;\n r3 := (random() * 9000000)::INT;\n r4 := (random() * 9000000)::INT;\n r5 := (random() * 9000000)::INT;\n CASE idxes\n WHEN 0 THEN \n INSERT INTO scale_write_0 (id1, id2, id3, id4, id5)\n VALUES ( d1, r2, r3, r4, r5);\n WHEN 1 THEN \n INSERT INTO scale_write_1 (id1, id2, id3, id4, id5)\n VALUES ( d1, r2, r3, r4, r5);\n WHEN 2 THEN \n INSERT INTO scale_write_2 (id1, id2, id3, id4, id5)\n VALUES ( d1, r2, r3, r4, r5);\n WHEN 3 THEN \n INSERT INTO scale_write_3 (id1, id2, id3, id4, id5)\n VALUES ( d1, r2, r3, r4, r5);\n WHEN 4 THEN \n INSERT INTO scale_write_4 (id1, id2, id3, id4, id5)\n VALUES ( d1, r2, r3, r4, r5);\n WHEN 5 THEN \n INSERT INTO scale_write_5 (id1, id2, id3, id4, id5)\n VALUES ( d1, r2, r3, r4, r5);\n END CASE;\n n := n - 1;\n END LOOP;\n RETURN 'insert';\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE\nFUNCTION run_delete(tbl INT, lb INT, ub INT, n INT)\n RETURNS VARCHAR AS \n$$\nDECLARE\n rows_affected INT;\n aff INT := 0;\n d1 INT;\n iter INT := n;\nBEGIN\n WHILE iter > 0 LOOP\n d1 := (random() * (ub-lb))::INT + lb;\n CASE tbl\n WHEN 1 THEN \n DELETE FROM scale_write_1 WHERE id1 = d1;\n WHEN 2 THEN \n DELETE FROM scale_write_2 WHERE id1 = d1;\n WHEN 3 THEN \n DELETE FROM scale_write_3 WHERE id1 = d1;\n WHEN 4 THEN \n DELETE FROM scale_write_4 WHERE id1 = d1;\n WHEN 5 THEN \n DELETE FROM scale_write_5 WHERE id1 = d1;\n ELSE NULL;\n END CASE;\n iter := iter - 1;\n GET DIAGNOSTICS rows_affected = ROW_COUNT;\n aff := aff + rows_affected;\n END LOOP;\n RETURN CASE WHEN aff = n THEN 'delete'\n ELSE NULL END;\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE\nFUNCTION run_update_all(tbl INT, lb INT, ub INT, n INT)\nRETURNS VARCHAR AS\n$$\nDECLARE\n rows_affected INT;\n r2 INT;\n r3 INT;\n r4 INT;\n r5 INT;\n d1 INT;\n iter INT := n;\n aff INT := 0;\nBEGIN\n WHILE iter > 0 LOOP\n d1 := (random() * (ub-lb))::INT + lb;\n r2 := (random() * 9000000)::INT;\n r3 := (random() * 9000000)::INT;\n r4 := (random() * 9000000)::INT;\n r5 := (random() * 9000000)::INT;\n CASE tbl\n WHEN 1 THEN \n UPDATE scale_write_1\n SET id2 = r2, id3=r3, id4=r4, id5=r5 WHERE id1=d1;\n WHEN 2 THEN\n UPDATE scale_write_2\n SET id2 = r2, id3=r3, id4=r4, id5=r5 WHERE id1=d1;\n WHEN 3 THEN \n UPDATE scale_write_3\n SET id2 = r2, id3=r3, id4=r4, id5=r5 WHERE id1=d1; \n WHEN 4 THEN \n UPDATE scale_write_4\n SET id2 = r2, id3=r3, id4=r4, id5=r5 WHERE id1=d1; \n WHEN 5 THEN \n UPDATE scale_write_5\n SET id2 = r2, id3=r3, id4=r4, id5=r5 WHERE id1=d1;\n ELSE NULL;\n END CASE; \n iter := iter - 1;\n GET DIAGNOSTICS rows_affected = ROW_COUNT;\n aff := aff + rows_affected;\n END LOOP;\n RETURN CASE WHEN aff = n THEN 'update all'\n ELSE NULL END;\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE\nFUNCTION run_update_one(tbl INT, lb INT, ub INT, n INT)\nRETURNS VARCHAR AS\n$$\nDECLARE\n rows_affected INT;\n r INT;\n d1 INT;\n aff INT := 0;\n iter INT := n;\nBEGIN\n WHILE iter > 0 LOOP\n d1 := (random() * (ub-lb))::INT + lb;\n r := (random() * 9000000)::INT;\n CASE tbl\n WHEN 1 THEN -- no index updated\n UPDATE scale_write_1 SET id2 = r WHERE id1=d1;\n WHEN 2 THEN -- one index updated\n UPDATE scale_write_2 SET id2 = r WHERE id1=d1;\n WHEN 3 THEN -- one index updated\n UPDATE scale_write_3 SET id3 = r WHERE id1=d1;\n WHEN 4 THEN -- one index updated\n UPDATE scale_write_4 SET id4 = r WHERE id1=d1;\n WHEN 5 THEN -- one index updated\n UPDATE scale_write_5 SET id5 = r WHERE id1=d1;\n ELSE NULL;\n END CASE;\n iter := iter - 1;\n GET DIAGNOSTICS rows_affected = ROW_COUNT;\n aff := aff + rows_affected;\n END LOOP;\n RETURN CASE WHEN aff = n THEN 'update one'\n ELSE NULL END;\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE\nFUNCTION test_write_scalability (n INT)\n RETURNS SETOF RECORD AS\n$$\nDECLARE\n rec RECORD;\n strt TIMESTAMP;\n mode VARCHAR;\n cmnd INT;\n q INT;\n lb INT;\n alb INT;\n iter INT;\n idxs INT;\nBEGIN\n SELECT ((max(id1)-min(id1))/4)::INT, min(id1)::INT\n INTO q, alb\n FROM scale_write_1;\n\n FOR iter IN 1 .. n LOOP\n FOR cmnd IN 0 .. 3 LOOP\n FOR idxs IN 0 .. 5 LOOP\n lb := alb + cmnd*q;\n strt := CLOCK_TIMESTAMP();\n mode := \n CASE cmnd\n WHEN 0 THEN run_insert (idxs, lb, lb+q, 1)\n WHEN 1 THEN run_update_one(idxs, lb, lb+q, 1)\n WHEN 2 THEN run_delete (idxs, lb, lb+q, 1)\n WHEN 3 THEN run_update_all(idxs, lb, lb+q, 1)\n END;\n\n IF mode IS NOT NULL THEN\n SELECT INTO rec\n idxs, mode, (CLOCK_TIMESTAMP() - strt);\n RETURN NEXT rec;\n END IF;\n END LOOP;\n END LOOP;\n END LOOP;\n RETURN;\nEND;\n$$ LANGUAGE plpgsql;\n```\n\n```\nSELECT indxes\n , mode\n , AVG(seconds) seconds \n , TO_CHAR (STDDEV(EXTRACT(epoch FROM seconds))\n / AVG(EXTRACT(epoch FROM seconds))\n * 100\n , '999.9') std_dev_prc\n FROM test_write_scalability(10) \n AS (indxes INT, mode VARCHAR, seconds INTERVAL)\n GROUP BY indxes, mode\n ORDER BY mode, indxes;\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 7215, "slov": 1101, "odkazu": 65, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:16", "sha256": "06f2000f46119434c5e96b468d61286ee5a3627d3d23453f7ac779af122f1dd2", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/postgresql/join", "titulek": "Example Scripts for PostgreSQL -The Join Operation", "h1": "PostgreSQL Example Scripts for “The Join Operation”", "popis": "CREATE & INSERT statements to create the PostgreSQL example database for Chapter 4, The Join Operation", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/postgresql/join", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for PostgreSQL -The Join Operation", "og:description": "CREATE & INSERT statements to create the PostgreSQL example database for Chapter 4, The Join Operation", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "PostgreSQL"], "osnova": [{"uroven": 1, "text": "PostgreSQL Example Scripts for “The Join Operation”"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# PostgreSQL Example Scripts for “The Join Operation”\n\n---\n\nThis section contains the `CREATE` and `INSERT` code to run the examples from “[The Join Operator](/sql/join)” in a PostgreSQL database.\n\n```\nCREATE TABLE sales (\n sale_id NUMERIC NOT NULL,\n employee_id NUMERIC NOT NULL,\n subsidiary_id NUMERIC NOT NULL,\n sale_date DATE NOT NULL,\n eur_value NUMERIC(17,2) NOT NULL,\n product_id BIGINT NOT NULL,\n quantity INTEGER NOT NULL,\n junk CHAR(200),\n CONSTRAINT sales_pk \n PRIMARY KEY (sale_id),\n CONSTRAINT sales_emp_fk \n FOREIGN KEY (subsidiary_id, employee_id)\n REFERENCES employees(subsidiary_id, employee_id)\n);\n\nSELECT SETSEED(0);\n\nINSERT INTO sales (sale_id\n , subsidiary_id, employee_id\n , sale_date, eur_value\n , product_id, quantity\n , junk)\nSELECT row_number() OVER (), data.*\n FROM (\n SELECT e.subsidiary_id, e.employee_id\n , (CURRENT_DATE - CAST(RANDOM()*3650 AS NUMERIC) * INTERVAL '1 DAY') sale_date\n , CAST(RANDOM()*100000 AS NUMERIC)/100 eur_value\n , CAST(RANDOM()*25 AS NUMERIC) + 1 product_id\n , CAST(RANDOM()*5 AS NUMERIC) + 1 quantity\n , 'junk'\n FROM employees e\n , GENERATE_SERIES(1, 1800) gen\n WHERE MOD(employee_id, 7) = 4\n AND gen < employee_id / 5\n ORDER BY sale_date\n ) data\n WHERE TO_CHAR(sale_date, 'D') <> '1';\n\nVACUUM ANALYZE sales;\n```\n\nNotes:\n\n- The rows are inserted chronologically to reflect a natural table growth.\n- Only a small fraction of employees have sales at all.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2031, "slov": 269, "odkazu": 65, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:17", "sha256": "c9d048f9f83d4aece1fd3c06b5fe628ba52111cd023c07cfbe9983ba19049d1d", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/postgresql/partial-results", "titulek": "Example Scripts for PostgreSQL - Partial Results", "h1": "PostgreSQL Example Scripts for “Partial Results”", "popis": "CREATE & INSERT statements to create the PostgreSQL example database for Chapter 7, Partial Results", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/postgresql/partial-results", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for PostgreSQL - Partial Results", "og:description": "CREATE & INSERT statements to create the PostgreSQL example database for Chapter 7, Partial Results", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "PostgreSQL"], "osnova": [{"uroven": 1, "text": "PostgreSQL Example Scripts for “Partial Results”"}, {"uroven": 2, "text": "Querying Top-N Rows"}, {"uroven": 2, "text": "Paging Through Results"}, {"uroven": 2, "text": "Window-Functions"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# PostgreSQL Example Scripts for “Partial Results”\n\n---\n\nThis section contains the `create` and `insert` statements to run the examples from [Chapter 7*Partial Results*](/sql/partial-results) in a PostgreSQL database.\n\nThe test approach for the scalability of Top-N queries is the same as used in the “[Testing and Scalability](/sql/example-schema/postgresql/performance-testing-scalability)” chapter.\n\n## Querying Top-N Rows\n\nFirst, using an index for the `where` clause only:\n\n```\nDROP INDEX scale_fast;\nCREATE INDEX scale_slow ON scale_data (SECTION, ID1, ID2);\nALTER TABLE scale_data CLUSTER ON scale_slow;\nCLUSTER scale_data;\n\nSELECT *\n FROM test_scalability('SELECT * '\n || 'FROM scale_data '\n || 'WHERE section=$1 '\n || 'ORDER BY id2, id1 '\n || 'FETCH FIRST 100 ROWS ONLY', 10)\n AS (sec INT, seconds INTERVAL, cnt_rows INT);\n```\n\nThen, using a pipelined Top-N with an index covering the `order by` clause:\n\n```\nCREATE INDEX scale_fast ON scale_data (SECTION, ID2, ID1);\nALTER TABLE scale_data CLUSTER ON scale_fast;\nCLUSTER scale_data;\n\nSELECT *\n FROM test_scalability('SELECT * '\n || 'FROM scale_data '\n || 'WHERE section=$1 '\n || 'ORDER BY id2, id1 '\n || 'FETCH FIRST 100 ROWS ONLY', 10)\n AS (sec INT, seconds INTERVAL, cnt_rows INT);\n```\n\n## Paging Through Results\n\nThe following function uses both methods to fetch the result page-wise. The select statement in the end prepares the statistics on screen.\n\n```\nCREATE OR REPLACE\nFUNCTION test_topn_scalability (n INT)\n RETURNS SETOF RECORD AS\n$$\nDECLARE\n strt TIMESTAMP;\n dur INTERVAL;\n v_rec RECORD;\n mode INT; iter INT; sec INT;\n lf RECORD;\n c1 INT[300]; c2 INT[300];\n\n sql_restart CURSOR (sec int, page int)\n IS SELECT id2, id1 \n FROM scale_data\n WHERE section = sec\n ORDER BY id2,id1\n OFFSET 100*page\n FETCH NEXT 100 ROWS ONLY;\n\n sql_continue CURSOR (sec int, c2 int, c1 int) \n IS SELECT id2, id1\n FROM scale_data\n WHERE section = sec\n -- AND (id2, id1) > (c2, c1)\n AND id2 >= c2\n AND (\n (id2 = c2 AND id1 > c1)\n OR\n (id2 > c2)\n )\n ORDER BY id2,id1\n FETCH NEXT 100 ROWS ONLY;\nBEGIN\n FOR iter IN 1..n LOOP\n FOR mode IN 0..1 LOOP\n FOR page IN 0..100 LOOP\n FOR sec IN 0..300 LOOP\n strt := CLOCK_TIMESTAMP();\n\n IF mode = 0 or page = 0 THEN\n FOR lf IN sql_restart(sec, page) LOOP\n c1[sec] := lf.id1; c2[sec] := lf.id2;\n END LOOP;\n ELSE\n FOR lf IN sql_continue(sec, c2[sec], c1[sec]) LOOP\n c1[sec] := lf.id1; c2[sec] := lf.id2;\n END LOOP;\n END IF;\n\n dur := (CLOCK_TIMESTAMP() - strt);\n\n SELECT INTO v_rec mode, sec, page, dur;\n RETURN NEXT v_rec;\n END LOOP;\n END LOOP;\n END LOOP;\n END LOOP;\n RETURN;\nEND;\n$$ LANGUAGE plpgsql;\n\nSELECT sec, mode, page, sum(seconds)\n FROM test_topn_scalability(10) \n AS (mode INT, sec INT, page int, seconds INTERVAL)\n WHERE sec=10\n GROUP BY sec, mode, page\n ORDER BY sec, mode, page;\n```\n\n## Window-Functions\n\nPostgreSQL supports window-Functions, but does, as of release 9.1, not use indexes for the best benefits.\n\n```\nSELECT *\n FROM ( SELECT sales.*\n , ROW_NUMBER() OVER (ORDER BY sale_date DESC\n , sale_id DESC) rn\n FROM sales\n ) tmp\n WHERE rn between 11 and 20\n ORDER BY sale_date DESC, sale_id DESC\n```\n\n`QUERY PLAN \n---------------------------------------------------------------\nSubquery Scan on tmp (cost=606750.08..649178.30 rows=6061)\n Filter: ((tmp.rn >= 11) AND (tmp.rn <= 20))\n -> WindowAgg (cost=606750.08..630994.78 rows=1212235)\n -> **Sort** (cost=606750.08..609780.67 rows=1212235)\n Sort Key: sales.sale_date, sales.sale_id\n -> **Seq Scan on sales** (cost=0.00..55417.35 rows=1212235)`\n\nThe database reads the entire table (`Seq Scan`) and sorts it (`Sort`). There is no `Limit` operation that would indicate awareness of the statements purpose.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 4121, "slov": 613, "odkazu": 65, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:18", "sha256": "dfab4ec77e22bb03c668d0a486f0da2e1469ca6812b41bc4ecc3e6d8243f0b43", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/postgresql/performance-testing-scalability", "titulek": "Example Scripts for PostgreSQL - Testing and Scalability", "h1": "PostgreSQL Example Scripts for “Testing and Scalability”", "popis": "CREATE & INSERT statements to create the PostgreSQL example database for Chapter 3, Testing and Scalability", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/postgresql/performance-testing-scalability", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for PostgreSQL - Testing and Scalability", "og:description": "CREATE & INSERT statements to create the PostgreSQL example database for Chapter 3, Testing and Scalability", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "PostgreSQL"], "osnova": [{"uroven": 1, "text": "PostgreSQL Example Scripts for “Testing and Scalability”"}, {"uroven": 4, "text": "Warning"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# PostgreSQL Example Scripts for “Testing and Scalability”\n\n---\n\nThis section contains the `CREATE`, `INSERT` and PL/pgSQL code to run the scalability test from the [Testing and Scalability Chapter](/sql/testing-scalability) in a PostgreSQL database.\n\n#### Warning\n\nThese scripts will create large objects in the database and produce a huge amount of transaction logs.\n\nIt’s required to run the test against a very large data set to make sure caching does not affect the measurement. Depending on your environment, you might need to create even larger tables to reproduce a linear result as shown in the book.\n\n```\nCREATE TABLE scale_data (\n section NUMERIC NOT NULL,\n id1 NUMERIC NOT NULL,\n id2 NUMERIC NOT NULL\n);\n```\n\nNote:\n\n- There is no primary key (to keep the data generation simple).\n- There is no index (yet). That’s done after filling the table.\n- There is no “junk” column to keep the table small.\n\n```\nINSERT INTO scale_data\nSELECT sections.*, gen.*\n , CEIL(RANDOM()*100) \n FROM GENERATE_SERIES(1, 300) sections,\n GENERATE_SERIES(1, 900000) gen\n WHERE gen <= sections * 3000;\n```\n\nNote:\n\n- This code generates 300 sections, you may need to adjust the number for your environment. If you increase the number of sections, you might also need to increase second `GENERATE_SERIES` call. It must generate at least `3000 x ` records.\n- The table will need some gigabytes.\n\n```\nCREATE INDEX scale_slow ON scale_data (section, id1, id2);\n\nALTER TABLE scale_data CLUSTER ON scale_slow;\nCLUSTER scale_data;\n```\n\nNote:\n\n- The index will also need some gigabytes.\n- PostgreSQL doesn’t support covering indexes as of release 9.0.3. That means, it’s not possible to select from an index only, without the corresponding table access. We will therefore cluster the table according to the index, to keep the impact at a minimum.\n- That might take ages.\n\n```\nCREATE OR REPLACE FUNCTION test_scalability\n (sql_txt VARCHAR(2000), n INT)\n RETURNS SETOF RECORD AS\n$$\nDECLARE\n tim INTERVAL[300];\n rec INT[300];\n strt TIMESTAMP;\n v_rec RECORD;\n iter INT;\n sec INT;\n cnt INT;\n rnd INT;\nBEGIN\n FOR iter IN 0..n LOOP\n FOR sec IN 0..300 LOOP\n IF iter = 0 THEN\n tim[sec] := 0;\n rec[sec] := 0;\n END IF;\n rnd := CEIL(RANDOM() * 100);\n strt := CLOCK_TIMESTAMP();\n\n EXECUTE 'select count(*) from (' || sql_txt || ') tbl'\n INTO cnt\n USING sec, rnd;\n\n tim[sec] := tim[sec] + CLOCK_TIMESTAMP() - strt;\n rec[sec] := rec[sec] + cnt;\n\n IF iter = n THEN\n SELECT INTO v_rec sec, tim[sec], rec[sec];\n RETURN NEXT v_rec;\n END IF;\n END LOOP;\n END LOOP;\n\n RETURN;\nEND;\n$$ LANGUAGE plpgsql;\n```\n\nNote:\n\n- The `TEST_SCALABILITY` function returns a table.\n- It’s hardcoded to run the test 300 sections\n- The number of iterations is configurable\n\n```\nSELECT *\n FROM test_scalability('SELECT * '\n || 'FROM scale_data '\n || 'WHERE section=$1 '\n || 'AND id2=$2', 10)\n AS (sec INT, seconds INTERVAL, cnt_rows INT);\n```\n\nThe counter test, with a better index, can be done like that:\n\n```\nCREATE INDEX scale_fast ON scale_data (section, id2, id1);\n\nALTER TABLE scale_data CLUSTER ON scale_fast;\nCLUSTER scale_data;\n\nSELECT *\n FROM test_scalability('SELECT * '\n || 'FROM scale_data '\n || 'WHERE section=$1 '\n || 'AND id2=$2', 10)\n AS (sec INT, seconds INTERVAL, cnt_rows INT);\n```\n\nNote:\n\n- It’s required to cluster the table on the new index. That might take ages.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3874, "slov": 580, "odkazu": 65, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:19", "sha256": "d7731a44e15d9a549df43ce20c75336b4f2e82c6090ec3dd090f82c04607ec9a", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/postgresql/sorting-grouping", "titulek": "Example Scripts for PostgreSQL - Sorting and Grouping", "h1": "PostgreSQL Example Scripts for “Sorting and Grouping”", "popis": "CREATE & INSERT statements to create the PostgreSQL example database for Chapter 5, Sorting and Grouping", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/postgresql/sorting-grouping", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for PostgreSQL - Sorting and Grouping", "og:description": "CREATE & INSERT statements to create the PostgreSQL example database for Chapter 5, Sorting and Grouping", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "PostgreSQL"], "osnova": [{"uroven": 1, "text": "PostgreSQL Example Scripts for “Sorting and Grouping”"}, {"uroven": 2, "text": "Indexed Order By"}, {"uroven": 2, "text": "Indexing ASC, DESC and NULLS FIRST/LAST"}, {"uroven": 2, "text": "Indexed Group By"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# PostgreSQL Example Scripts for “Sorting and Grouping”\n\n---\n\nThis section contains the code and execution plans for [Chapter 6*Sorting and Grouping*](/sql/sorting-grouping) in a PostgreSQL database.\n\n## Indexed Order By\n\n```\n DROP INDEX sales_date;\nCREATE INDEX sales_dt_pr ON sales (sale_date, product_id);\n\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date = now() - INTERVAL '1' DAY\n ORDER BY sale_date, product_id;\n```\n\nThe execution does not perform a sort operation:\n\n`QUERY PLAN\n-----------------------------------------------------------\nIndex Scan using sales_dt_pr (cost=0.01..680.86 rows=376)\n Index Cond: (sale_date = (now() - '1 day'::interval day))`\n\nPostgreSQL uses the same execution plan, when sorting by `PRODUCT_ID` only.\n\n```\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date = now() - INTERVAL '1' DAY\n ORDER BY product_id;\n```\n\nUsing an greater or equals condition requires an Sort operation:\n\n```\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= now() - INTERVAL '1' DAY\n ORDER BY product_id;\n```\n\nAlthough the row estimate got lower, causing the cost also to be lower:\n\n`QUERY PLAN\n--------------------------------------------------------------\nSort (cost=8.50..8.50 rows=1 width=32)\n Sort Key: product_id\n -> Index Scan using sales_dt_pr (cost=0.00..8.49 rows=1)\n Index Cond: (sale_date >= (now() - '1 day'::interval day))`\n\n## Indexing ASC, DESC and NULLS FIRST/LAST\n\nScanning an index backwards:\n\n```\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= now() - INTERVAL '1' DAY\n ORDER BY sale_date DESC, product_id DESC;\n```\n\nMixing `ASC` and `DESC` causes an explicit sort:\n\n```\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= now() - INTERVAL '1' DAY\n ORDER BY sale_date ASC, product_id DESC;\n```\n\nOrdering the index with mixed `ASC`/`DESC` modifiers:\n\n```\n DROP INDEX sales_dt_pr;\n\nCREATE INDEX sales_dt_pr\n ON sales (sale_date ASC, product_id DESC);\n\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= now() - INTERVAL '1' DAY\n ORDER BY sale_date ASC, product_id DESC;\n```\n\nPostgreSQL orders `NULLS LAST` per default. However, the `DESC` modifier puts them to the front, so that `DESC NULLS LAST` must sort explicitly:\n\n```\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= now() - INTERVAL '1' DAY\n ORDER BY sale_date ASC, product_id DESC NULLS LAST;\n```\n\nPostgreSQL allows explicit `NULLS LAST` indexing as well, so it becomes a pipelined `order by` again:\n\n```\n DROP INDEX sales_dt_pr;\n\nCREATE INDEX sales_dt_pr\n ON sales (sale_date ASC, product_id DESC NULLS LAST);\n\nEXPLAIN\n SELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= now() - INTERVAL '1' DAY\n ORDER BY sale_date ASC, product_id DESC NULLS LAST;\n```\n\n## Indexed Group By\n\nThe PostgreSQL (at least 9.0-13) database seems to have a little glitch, that makes the following not work as pipelined `order by`, when the index has `NULLS LAST`, as created above:\n\n```\nEXPLAIN\n SELECT product_id, SUM(eur_value)\n FROM sales\n WHERE sale_date = now() - INTERVAL '1' DAY\n GROUP BY product_id;\n```\n\n```\n QUERY PLAN\n------------------------------------------------------------------------------------\n HashAggregate (cost=574.21..574.53 rows=26 width=40)\n Group Key: product_id\n -> Index Scan using sales_dt_pr on sales (cost=0.43..572.62 rows=318 width=14)\n Index Cond: (sale_date = (now() - '1 day'::interval day))\n```\n\nRemoving the `NULLS LAST` clause from the index reveals something interesting:\n\n```\n DROP INDEX sales_dt_pr;\n\nCREATE INDEX sales_dt_pr\n ON sales (sale_date ASC, product_id DESC);\n\nEXPLAIN\n SELECT product_id, SUM(eur_value)\n FROM sales\n WHERE sale_date = now() - INTERVAL '1' DAY\n GROUP BY product_id;\n```\n\n```\n QUERY PLAN\n---------------------------------------------------------------------------------------------\n GroupAggregate (cost=0.43..574.53 rows=26 width=40)\n Group Key: product_id\n -> Index Scan Backward using sales_dt_pr on sales (cost=0.43..572.62 rows=318 width=14)\n Index Cond: (sale_date = (now() - '1 day'::interval day))\n```\n\nThe index is read backwards, although the SQL statement does not require it. It seems like PostgreSQL uses an `GROUP BY PRODUCT_ID` internally, to fetch the pre-sorted result. The next case adds an `order by` clause in opposite order.\n\n```\nEXPLAIN\n SELECT product_id, SUM(eur_value)\n FROM sales\n WHERE sale_date = now() - INTERVAL '1' DAY\n GROUP BY product_id\n ORDER BY product_id DESC;\n```\n\n```\n QUERY PLAN\n------------------------------------------------------------------------------------\n GroupAggregate (cost=0.43..574.53 rows=26 width=40)\n Group Key: product_id\n -> Index Scan using sales_dt_pr on sales (cost=0.43..572.62 rows=318 width=14)\n Index Cond: (sale_date = (now() - '1 day'::interval day))\n```\n\nSo, it seems that the implicit `order by` is not hardcoded. Our next test show that PostgreSQL can actually use such an index, but only if an explicit `order by` clause asks for the same order:\n\n```\n DROP INDEX sales_dt_pr;\n\nCREATE INDEX sales_dt_pr\n ON sales (sale_date ASC, product_id DESC NULLS LAST);\n\nEXPLAIN\n SELECT product_id, SUM(eur_value)\n FROM sales\n WHERE sale_date = now() - INTERVAL '1' DAY\n GROUP BY product_id\n ORDER BY product_id DESC NULLS LAST;\n```\n\n```\n QUERY PLAN\n------------------------------------------------------------------------------------\n GroupAggregate (cost=0.43..574.53 rows=26 width=40)\n Group Key: product_id\n -> Index Scan using sales_dt_pr on sales (cost=0.43..572.62 rows=318 width=14)\n Index Cond: (sale_date = (now() - '1 day'::interval day))\n```\n\nIt does a pipelined `group by`, even when the index is defined `NULLS LAST` when the order by clause explicitly sorts the same way. Otherwise, it uses an internal order by clause that disregards the indexes `NULLS` specification.\n\nFurther testing shows that the problem exists for `ASC` indexes with `NULLS FIRST`:\n\n```\n DROP INDEX sales_dt_pr;\n\nCREATE INDEX sales_dt_pr\n ON sales (sale_date ASC, product_id ASC NULLS FIRST);\n\nEXPLAIN\n SELECT product_id, SUM(eur_value)\n FROM sales\n WHERE sale_date = now() - INTERVAL '1' DAY\n GROUP BY product_id\n ORDER BY product_id ASC NULLS FIRST;\n```\n\n```\n QUERY PLAN\n------------------------------------------------------------------------------------\n GroupAggregate (cost=0.43..574.53 rows=26 width=40)\n Group Key: product_id\n -> Index Scan using sales_dt_pr on sales (cost=0.43..572.62 rows=318 width=14)\n Index Cond: (sale_date = (now() - '1 day'::interval day))\n```\n\nBut skipping `order b`y clause:\n\n```\nEXPLAIN\n SELECT product_id, SUM(eur_value)\n FROM sales\n WHERE sale_date = now() - INTERVAL '1' DAY\n GROUP BY product_id;\n```\n\n```\n QUERY PLAN\n------------------------------------------------------------------------------------\n HashAggregate (cost=574.21..574.53 rows=26 width=40)\n Group Key: product_id\n -> Index Scan using sales_dt_pr on sales (cost=0.43..572.62 rows=318 width=14)\n Index Cond: (sale_date = (now() - '1 day'::interval day))\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 6840, "slov": 940, "odkazu": 65, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:20", "sha256": "d4bbf160d79a754512a1d3368c7c8c2fae234032463d9ffae859953931e24632", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/postgresql/where-clause", "titulek": "Example Scripts for PostgreSQL - The WHERE Clause", "h1": "PostgreSQL Example Scripts for “The Where Clause”", "popis": "CREATE & INSERT statements to create the PostgreSQL example database for Chapter 2, The Where Clause", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/postgresql/where-clause", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for PostgreSQL - The WHERE Clause", "og:description": "CREATE & INSERT statements to create the PostgreSQL example database for Chapter 2, The Where Clause", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "PostgreSQL"], "osnova": [{"uroven": 1, "text": "PostgreSQL Example Scripts for “The Where Clause”"}, {"uroven": 2, "text": "The Equals Operator"}, {"uroven": 3, "text": "Surrogate Keys"}, {"uroven": 3, "text": "Concatenated Keys"}, {"uroven": 2, "text": "Functions"}, {"uroven": 3, "text": "Case-Insensitive Search"}, {"uroven": 3, "text": "User-Defined Functions"}, {"uroven": 2, "text": "Partial Indexes"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# PostgreSQL Example Scripts for “The Where Clause”\n\n---\n\nThe scripts provided in this appendix are ready to run and were tested on the PostgreSQL 9. Most of the examples will also work earlier releases.\n\n## The Equals Operator\n\n### Surrogate Keys\n\nThe following script creates the `EMPLOYEES` table with 1000 entries.\n\n```\nCREATE TABLE employees (\n employee_id NUMERIC NOT NULL,\n first_name VARCHAR(1000) NOT NULL,\n last_name VARCHAR(1000) NOT NULL,\n date_of_birth DATE ,\n phone_number VARCHAR(1000) NOT NULL,\n junk CHAR(1000) ,\n CONSTRAINT employees_pk PRIMARY KEY (employee_id)\n);\n```\n\n```\nCREATE FUNCTION random_string(minlen NUMERIC, maxlen NUMERIC)\nRETURNS VARCHAR(1000)\nAS\n$$\nDECLARE\n rv VARCHAR(1000) := '';\n i INTEGER := 0;\n len INTEGER := 0;\nBEGIN\n IF maxlen < 1 OR minlen < 1 OR maxlen < minlen THEN\n RETURN rv;\n END IF;\n\n len := floor(random()*(maxlen-minlen)) + minlen;\n\n FOR i IN 1..floor(len) LOOP\n rv := rv || chr(97+CAST(random() * 25 AS INTEGER));\n END LOOP;\n RETURN rv;\nEND;\n$$ LANGUAGE plpgsql;\n```\n\n```\nINSERT INTO employees (employee_id, first_name,\n last_name, date_of_birth, \n phone_number, junk)\nSELECT GENERATE_SERIES\n , initcap(lower(random_string(2, 8)))\n , initcap(lower(random_string(2, 8)))\n , CURRENT_DATE - CAST(floor(random() * 365 * 10 + 40 * 365) AS NUMERIC) * INTERVAL '1 DAY'\n , CAST(floor(random() * 9000 + 1000) AS NUMERIC)\n , 'junk'\n FROM GENERATE_SERIES(1, 1000);\n```\n\n```\nUPDATE employees \n SET first_name='MARKUS', \n last_name='WINAND'\n WHERE employee_id=123;\n```\n\n```\nVACUUM ANALYZE employees;\n```\n\nNotes:\n\n- The `JUNK` column is used to have a realistic row length. Because it’s data type is `CHAR`, as opposed to `VARCHAR`, it always needs the 1000 bytes it can hold. Without this column the table would become unrealistically small and many demonstrations would not work.\n- Random data is filled into the table, with exception to my entry, that is updated after the insert.\n- Table [statistics](/sql/where-clause/the-equals-operator/slow-indexes-part-ii#sb-statistics) are gathered so that the [optimizer](/sql/where-clause/the-equals-operator/slow-indexes-part-ii#sb-optimizer) knows a little bit about the table’s content.\n\n### Concatenated Keys\n\nThis script changes the `EMPLOYEES` table so that it reflects the situation after the merger with Very Big Company:\n\n```\n-- add subsidiary_id and update existing records\nALTER TABLE employees ADD subsidiary_id NUMERIC;\nUPDATE employees SET subsidiary_id = 30;\nALTER TABLE employees ALTER COLUMN subsidiary_id SET NOT NULL;\n\n-- change the PK\nALTER TABLE employees DROP CONSTRAINT employees_pk;\nALTER TABLE employees ADD CONSTRAINT employees_pk\n PRIMARY KEY (employee_id, subsidiary_id);\n\n-- generate more records (Very Big Company)\nINSERT INTO employees (employee_id, first_name,\n last_name, date_of_birth, \n phone_number, subsidiary_id, junk)\nSELECT GENERATE_SERIES\n , initcap(lower(random_string(2, 8)))\n , initcap(lower(random_string(2, 8)))\n , CURRENT_DATE - CAST(floor(random() * 365 * 10 + 40 * 365) AS NUMERIC) * INTERVAL '1 DAY'\n , CAST(floor(random() * 9000 + 1000) AS NUMERIC)\n , CAST(floor(random() * (generate_series)/9000*29) AS NUMERIC)\n , 'junk'\n FROM GENERATE_SERIES(1, 9000);\n\nVACUUM ANALYZE employees;\n```\n\nNotes:\n\n- The new primary key just extended by the `SUBSIDIARY_ID`; that is, the `EMPLOYEE_ID` remains in the first position.\n- The new records are randomly assigned to the subsidiaries 1 through 29.\n- The table and index are analyzed again to make the optimizer aware of the grown data volume.\n\nThe next script introduces the index on `SUBSIDIARY_ID` to support the query for all employees of one particular subsidiary:\n\n```\nCREATE INDEX emp_sub_id ON employees (subsidiary_id);\n```\n\nAlthough that gives decent performance, it’s better to use the index that supports the primary key:\n\n```\n-- use tmp index to support the PK\nCREATE UNIQUE INDEX employee_pk_tmp \n ON employees (subsidiary_id, employee_id);\n\n ALTER TABLE employees \n ADD CONSTRAINT employees_pk_tmp\nUNIQUE (subsidiary_id, employee_id);\n\nALTER TABLE employees\n DROP CONSTRAINT employees_pk;\n\nALTER TABLE employees\n ADD CONSTRAINT employees_pk\n PRIMARY KEY (subsidiary_id, employee_id);\n\nALTER TABLE employees\n DROP CONSTRAINT employees_pk_tmp;\n\n-- drop old indexes\nDROP INDEX employee_pk_tmp;\nDROP INDEX emp_sub_id;\n```\n\nNotes:\n\n- A new index is created and used to support the PK.\n- Once the old PK index isn’t used by the constraint anymore, it can be dropped and recreated with its new column order.\n- The constraint is changed again to use the new PK index and the temporary index can be dropped—as well as the index on the subsidiary id that isn’t required anymore.\n\n## Functions\n\n### Case-Insensitive Search\n\nThe randomized names were already created in correct case, just update “my” record:\n\n```\nUPDATE employees \n SET first_name = 'Markus'\n , last_name = 'Winand'\n WHERE employee_id = 123\n AND subsidiary_id = 30;\n```\n\nThe statement to create the function-based index:\n\n```\nCREATE INDEX emp_up_name\n ON employees (UPPER(last_name) varchar_pattern_ops);;\nDROP INDEX emp_name;;\n```\n\n```\nVACUUM ANALYZE employees;;\n```\n\n### User-Defined Functions\n\nDefine a PL/SQL function that calculates the age and attempts to use it in an index:\n\n```\nCREATE FUNCTION get_age(date_of_birth DATE) \nRETURNS NUMERIC\nAS\n$$\nBEGIN\n RETURN DATE_PART('year', AGE(date_of_birth));\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE INDEX invalid ON EMPLOYEES (get_age(date_of_birth));\n```\n\nYou should get the error “functions in index expression must be marked IMMUTABLE”.\n\n## Partial Indexes\n\n```\nCREATE TABLE messages AS (\nSELECT GENERATE_SERIES::numeric id\n , CASE WHEN random() < 0.01 THEN 'N' ELSE 'Y' END processed\n , CAST(trunc(random() * 100) AS NUMERIC) receiver\n , 'junk' message\n FROM GENERATE_SERIES(0, 999999)\n);\n\nCREATE INDEX messages_todo\n ON messages (receiver, processed);\n```\n\n```\nPREPARE stmt(int) AS\n SELECT message\n FROM messages\n WHERE processed = 'N'\n AND receiver = $1;\n\nEXPLAIN EXECUTE stmt(1);\n```\n\n```\nCREATE INDEX messages_only_todo\n ON messages (receiver)\n WHERE processed = 'N';\n\nPREPARE stmt(int) AS\n SELECT message\n FROM messages\n WHERE processed = 'N'\n AND receiver = $1;\n\nEXPLAIN EXECUTE stmt(1);\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 6637, "slov": 909, "odkazu": 67, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:21", "sha256": "b1a41965b82f7f0603e26883395975776ad9730710858fc00613f1c64932045f", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sql-server", "titulek": "Example Scripts for SQL Server", "h1": "SQL Server Example Scripts", "popis": "CREATE & INSERT statements to create the Use The Index, Luke SQL Server example database.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sql-server", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for SQL Server", "og:description": "CREATE & INSERT statements to create the Use The Index, Luke SQL Server example database.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema"], "osnova": [{"uroven": 1, "text": "SQL Server Example Scripts"}, {"uroven": 2, "text": "Contents"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# SQL Server Example Scripts\n\n---\n\nThe scripts provided in this appendix are ready to run and were tested on the SQL Server database release 2008R2. Most of the examples will also work on earlier releases.\n\n## Contents\n\n1. *[The `where` clause](/sql/example-schema/sql-server/where-clause)*\n2. *[Testing and Scalability](/sql/example-schema/sql-server/performance-testing-scalability)*\n3. *[The Join Operation](/sql/example-schema/sql-server/join)*\n4. *[Clustering Data](/sql/example-schema/sql-server/clustering-data)*\n5. *[Sorting and Grouping](/sql/example-schema/sql-server/sorting-grouping)*\n6. *[Partial Results](/sql/example-schema/sql-server/partial-results)*\n7. *[Insert, Delete and Update](/sql/example-schema/sql-server/dml)*\n8. *[3-Minute Test](/sql/example-schema/sql-server/3-minute-quiz)*\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1435, "slov": 169, "odkazu": 67, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:22", "sha256": "d65776cb87f7cf4848ce6ef17176eb5d194aa17b5e63501fa56714fa3e38a7d9", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sql-server/3-minute-quiz", "titulek": "Example Scripts for SQL Server - 3-Minuten Test", "h1": "SQL Server Scripts for “3-Minute Quiz”", "popis": "CREATE & INSERT statements to create the SQL Server example database for the 3-Minuten Test", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sql-server/3-minute-quiz", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for SQL Server - 3-Minuten Test", "og:description": "CREATE & INSERT statements to create the SQL Server example database for the 3-Minuten Test", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "SQL Server"], "osnova": [{"uroven": 1, "text": "SQL Server Scripts for “3-Minute Quiz”"}, {"uroven": 2, "text": "Question 1 — DATE Anti-Pattern"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 2 — Indexed Top-N"}, {"uroven": 2, "text": "Question 3 — Column Order"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 4 — LIKE"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 5 — Index Only Scan"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# SQL Server Scripts for “3-Minute Quiz”\n\n---\n\nThis section contains the `create`, `insert` and `select` statements for the “[Test your SQL Know-How in 3 Minutes](/3-minute-quiz)” test. You may want to test yourself before reading this page.\n\nThe `create` and `insert` statements are available in the [example schema archive](/use-the-index-luke.tar.gz).\n\n## Question 1 — DATE Anti-Pattern\n\n```\nCREATE INDEX tbl_idx ON tbl (date_column);\n```\n\n```\nSELECT COUNT(*)\n FROM tbl\n WHERE DATEPART(YEAR, date_column) = 2025;\n```\n\n```\nSELECT COUNT(*)\n FROM tbl\n WHERE date_column >= {d'2025-01-01'}\n AND date_column < {d'2026-01-01'};\n```\n\n```\n|--Compute Scalar(DEFINE:([Expr1003]=CONVERT_IMPLICIT(int,[Expr1005],0)))\n |--Stream Aggregate(DEFINE:([Expr1005]=Count(*)))\n |--Index Scan(OBJECT:(tbl.tbl_idx),\n WHERE:(datepart(year,tbl.date_column)=(2017)))\n```\n\n```\n|--Compute Scalar(DEFINE:([Expr1003]=CONVERT_IMPLICIT(int,[Expr1013],0)))\n |--Stream Aggregate(DEFINE:([Expr1013]=Count(*)))\n |--Nested Loops(Inner Join)\n |--Merge Interval\n | |--Concatenation\n | |--Compute Scalar(DEFINE:(([Expr1005],[Expr1006],[Expr1004])=...))\n | | |--Constant Scan\n | |--Compute Scalar(DEFINE:(([Expr1008],[Expr1009],[Expr1007])=...))\n | |--Constant Scan\n |--Index Seek(OBJECT:(tbl.tbl_idx),\n SEEK:(tbl.date_column > [Expr1010]\n AND tbl.date_column < [Expr1011])\n ORDERED FORWARD)\n```\n\n#### Learn More\n\n- [Using Functions in the `WHERE` clause](/sql/where-clause/functions)\n- [Common Anti-Patterns: `DATE`](/sql/where-clause/obfuscation/dates)\n- [Explain plan operations `Index Scan` and `Index Seek`](/sql/explain-plan/sql-server/operations)\n\n## Question 2 — Indexed Top-N\n\n```\nCREATE INDEX tbl_idx ON tbl (a, date_column);\n```\n\n```\nSELECT TOP 1*\n FROM tbl\n WHERE a = 12\n ORDER BY date_column DESC\n ;\n```\n\nThe `Index Seek` returns the result `BACKWARD` to reflect the `ORDER BY DESC`. Note that there is no `SORT` operation.\n\n```\n|--Top(TOP EXPRESSION:(1))\n |--Nested Loops(Inner Join)\n |--Index Seek(OBJECT:(tbl.tbl_idx),\n | SEEK:(a=12.)\n | ORDERED BACKWARD)\n |--Clustered Index Seek(OBJECT:(tbl.PK__tbl__3213E83F20C1E124),\n SEEK:(tbl.id=tbl.id)\n LOOKUP ORDERED FORWARD)\n```\n\n## Question 3 — Column Order\n\n```\nCREATE INDEX tbl_idx ON tbl (a, b);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE a = 38\n AND b = 1;\n```\n\n```\nSELECT *\n FROM tbl\n WHERE b = 1;\n```\n\n```\nDROP INDEX tbl_idx ON tbl;\n```\n\n```\nCREATE INDEX tbl_idx ON tbl (b, a);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE a = 38\n AND b = 1;\n```\n\n```\nSELECT *\n FROM tbl\n WHERE b = 1;\n```\n\nThe first query can use both index very efficiently (`Index Seek` with only `SEEK` predicates):\n\n```\n|--Nested Loops(Inner Join)\n |--Index Seek(OBJECT:(tbl.tbl_idx), \n | SEEK:(tbl.a=38. AND tbl.b=1.)\n | ORDERED FORWARD)\n |--Clustered Index Seek(OBJECT:(tbl.PK__tbl__3213E83F20C1E124),\n SEEK:(tbl.id=tbl.id)\n LOOKUP ORDERED FORWARD)\n```\n\n```\n|--Nested Loops(Inner Join)\n |--Index Seek(OBJECT:(tbl.tbl_idx), \n | SEEK:(tbl.b=1. AND tbl.a=38.)\n | ORDERED FORWARD)\n |--Clustered Index Seek(OBJECT:(tbl.PK__tbl__3213E83F20C1E124),\n SEEK:(tbl.id=tbl.id)\n LOOKUP ORDERED FORWARD)\n```\n\nThe second query cannot perform an `Index Seek`, so it makes an `Index Scan`—reading the entire index.\n\n```\n|--Nested Loops(Inner Join)\n |--Index Scan(OBJECT:(tbl.tbl_idx),\n | WHERE:(tbl.b=1.))\n |--Clustered Index Seek(OBJECT:(tbl.PK__tbl__3213E83F20C1E124),\n SEEK:(tbl.id=tbl.id)\n LOOKUP ORDERED FORWARD)\n```\n\nWith the reversed index column order, the second query can use the index efficiently:\n\n```\n|--Nested Loops(Inner Join)\n |--Index Seek(OBJECT:(tbl.tbl_idx), \n | SEEK:(tbl.b=1.)\n | ORDERED FORWARD)\n |--Clustered Index Seek(OBJECT:(tbl.PK__tbl__3213E83F20C1E124],\n SEEK:(tbl.id=tbl.id)\n LOOKUP ORDERED FORWARD)\n```\n\n#### Learn More\n\n- [The column order in Multi-Column Indexes](/sql/where-clause/the-equals-operator/concatenated-keys)\n- [Explain plan operations `Index Scan` and `Index Seek`](/sql/explain-plan/sql-server/operations)\n\n## Question 4 — LIKE\n\n```\nCREATE INDEX tbl_idx ON tbl (text);\n```\n\n```\nSELECT *\n FROM tbl\n WHERE text LIKE 'TJ%';\n```\n\nThe execution plan states that it is doing an *Index Seek*. Since there is only wild card character at the very end, the full search text `'TERM'` can be used as [index access predicate](/sql/where-clause/searching-for-ranges/greater-less-between-tuning-sql-access-filter-predicates).\n\n```\n|--Nested Loops(Inner Join, OUTER REFERENCES:(tbl.id))\n |--Index Seek(OBJECT:(tbl.tbl_idx)\n | , SEEK:(tbl.text >= 'TÏþ'\n | AND tbl.text < 'TK')\n | , WHERE:(tbl.text like 'TJ%')\n | ORDERED FORWARD\n | )\n |--Clustered Index Seek(OBJECT:(tbl.tbl_pk)\n , SEEK:(tbl.id=tbl.id)\n LOOKUP ORDERED FORWARD\n )\n```\n\n#### Learn More\n\n- [A visual explanation why LIKE is slow](/sql/where-clause/searching-for-ranges/like-performance-tuning)\n- [Explain plan operations `Index Scan` and `Index Seek`](/sql/explain-plan/sql-server/operations)\n\n## Question 5 — Index Only Scan\n\n```\nCREATE INDEX tbl_idx ON tbl (a, date_column);\n```\n\n```\nSELECT date_column, count(*)\n FROM tbl\n WHERE a = 38\n GROUP BY date_column;\n```\n\n```\nSELECT date_column, count(*)\n FROM tbl\n WHERE a = 38\n AND b = 1\n GROUP BY date_column;\n```\n\nThe first query uses one index to search based on column `A` but can also retrieve the `DATE_COLUMN` from the very same index. The second query must run a key lookup on the clustered index (or `RID Lookup (HEAP)`) to apply the filter on the `B` column.\n\n```\n|--Compute Scalar(DEFINE:([Expr1003]=CONVERT_IMPLICIT(int,[Expr1006],0)))\n |--Stream Aggregate(GROUP BY:(tbl.date_column)\n | DEFINE:([Expr1006]=Count(*)))\n |--Index Seek(OBJECT:(tbl.tbl_idx),\n SEEK:(tbl.a=38.)\n ORDERED FORWARD)\n```\n\n```\n|--Compute Scalar(DEFINE:([Expr1003]=CONVERT_IMPLICIT(int,[Expr1006],0)))\n |--Stream Aggregate(GROUP BY:(tbl.date_column)\n | DEFINE:([Expr1006]=Count(*)))\n |--Nested Loops(Inner Join)\n |--Index Seek(OBJECT:(tbl.tbl_idx),\n | SEEK:(tbl.a=38.)\n | ORDERED FORWARD)\n |--Clustered Index Seek(OBJECT:(tbl.PK__tbl__3213E83F20C1E124),\n SEEK:(tbl.id=tbl.id),\n WHERE:(tbl.b=1.)\n LOOKUP ORDERED FORWARD)\n```\n\n#### Learn More\n\n- [Chapter 5*Clustering Data: The Second Power of Indexing*](/sql/clustering)\n- [Reading SQL Server explain plan output](/sql/explain-plan/sql-server/operations)\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 6438, "slov": 760, "odkazu": 73, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:22", "sha256": "190e61c1c14dd8f470adcb07d719e615935a4870729cf0b42b52c8ccd1bb00b4", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sql-server/clustering-data", "titulek": "Example Scripts for SQL Server - Clustering Data", "h1": "SQL Server Scripts for “Clustering Data”", "popis": "CREATE & INSERT statements to create the SQL Server example database for Chapter 5, Clustering Data", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sql-server/clustering-data", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for SQL Server - Clustering Data", "og:description": "CREATE & INSERT statements to create the SQL Server example database for Chapter 5, Clustering Data", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "SQL Server"], "osnova": [{"uroven": 1, "text": "SQL Server Scripts for “Clustering Data”"}, {"uroven": 2, "text": "Index-Organized Table (Clustered Index)"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# SQL Server Scripts for “Clustering Data”\n\n---\n\nThis section contains the `create`, `insert` and T-SQL code to run the examples from [Chapter 5*Clustering Data: The Second Power of Indexing*](/sql/clustering) in a SQL Server database. It requires the helper functions `RANDOM_DATE` and `RANDOM_INT` from the [where clause examples](/sql/example-schema/sql-server/where-clause).\n\n## Index-Organized Table (Clustered Index)\n\nThe following creates a second sales table with a clustered index and a secondary index on `SALE_DATE`.\n\n```\nCREATE TABLE sales_clst (\n sale_id NUMERIC NOT NULL,\n employee_id NUMERIC NOT NULL,\n subsidiary_id NUMERIC NOT NULL,\n sale_date DATE NOT NULL,\n eur_value NUMERIC(17,2) NOT NULL,\n junk CHAR(200),\n CONSTRAINT sales_pk \n PRIMARY KEY (sale_id),\n CONSTRAINT sales_emp_fk \n FOREIGN KEY (subsidiary_id, employee_id)\n REFERENCES employees(subsidiary_id, employee_id)\n);\nGO\n\nSELECT RAND(0);\nGO\n\nWITH generator (n)\n AS (\n SELECT 1\n UNION ALL\n SELECT n + 1\n FROM generator\n WHERE N < 1800\n )\nINSERT INTO sales_clst (sale_id\n , subsidiary_id, employee_id\n , sale_date, eur_value, junk)\nSELECT row_number() OVER (ORDER BY sale_date), data.*\n FROM (\n SELECT e.subsidiary_id, e.employee_id\n , [dbo].random_date(0, 3650) sale_date\n , [dbo].random_int(1, 100000)/100 eur_value\n , 'junk' junk\n FROM employees e\n , generator gen\n WHERE employee_id % 7 = 4\n AND gen.n < employee_id / 5\n ) data\n ORDER BY sale_date\nOPTION(MAXRECURSION 2000);\nGO\n\nEXEC sp_updatestats;\nGO\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2111, "slov": 283, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:23", "sha256": "8951a805d475d04d2a202843a0382e82675e8fc201d59ce5a60721ac131a2345", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sql-server/dml", "titulek": "Example Scripts for SQL Server - Insert, Delete and Update", "h1": "SQL Server Scripts for “Insert, Delete and Update”", "popis": "CREATE & INSERT statements to create the SQL Server example database for Chapter 8, Insert, Delete and Update", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sql-server/dml", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for SQL Server - Insert, Delete and Update", "og:description": "CREATE & INSERT statements to create the SQL Server example database for Chapter 8, Insert, Delete and Update", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "SQL Server"], "osnova": [{"uroven": 1, "text": "SQL Server Scripts for “Insert, Delete and Update”"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# SQL Server Scripts for “Insert, Delete and Update”\n\n---\n\nThis section contains the `create` and `insert` statements to run the examples from [Chapter 8*Modifying Data*](/sql/dml) in an SQL Server database. There is only one query that reports all figures for the `insert`, `delete` and `update` sections.\n\n```\nWITH generate_series_1k(n) AS (\n SELECT 0\n UNION ALL\n SELECT n + 1\n FROM generate_series_1k\n WHERE N + 1 < 10000\n), generate_series(n, n1, n2) AS (\n SELECT gs2.n * 1000 + gs1.n, gs1.n, gs2.n\n FROM generate_series_1k gs1, \n generate_series_1k gs2\n WHERE gs1.n < 1000\n)\nSELECT n id1\n , CAST(CEILING(ABS(CAST(NEWID() AS BINARY(6)) % 900000))\n + 100000 AS numeric) id2\n , CAST(CEILING(ABS(CAST(NEWID() AS BINARY(6)) % 900000))\n + 100000 AS numeric) id3\n , CAST(CEILING(ABS(CAST(NEWID() AS BINARY(6)) % 900000))\n + 100000 AS numeric) id4\n , CAST(CEILING(ABS(CAST(NEWID() AS BINARY(6)) % 900000))\n + 100000 AS numeric) id5\n INTO scale_write_0\n FROM generate_series\nOPTION(MAXRECURSION 32767);\nGO\n\nSELECT *\n INTO scale_write_1\n FROM scale_write_0;\nGO\n\nSELECT *\n INTO scale_write_2\n FROM scale_write_0;\nGO\n\nSELECT *\n INTO scale_write_3\n FROM scale_write_0;\nGO\n\nSELECT *\n INTO scale_write_4\n FROM scale_write_0;\nGO\n\nSELECT *\n INTO scale_write_5\n FROM scale_write_0;\nGO\n\nCREATE INDEX scale_write_1_1 on scale_write_1(id1);\nGO\n\nCREATE INDEX scale_write_2_1 on scale_write_2(id1);\nGO\nCREATE INDEX scale_write_2_2 on scale_write_2(id2, id1);\nGO\n\nCREATE INDEX scale_write_3_1 on scale_write_3(id1);\nGO\nCREATE INDEX scale_write_3_2 on scale_write_3(id2, id1);\nGO\nCREATE INDEX scale_write_3_3 on scale_write_3(id3, id2, id1);\nGO\n\nCREATE INDEX scale_write_4_1 on scale_write_4(id1);\nGO\nCREATE INDEX scale_write_4_2 on scale_write_4(id2, id1);\nGO\nCREATE INDEX scale_write_4_3 on scale_write_4(id3, id2, id1);\nGO\nCREATE INDEX scale_write_4_4 on scale_write_4(id4, id3, id2\n ,id1);\nGO\n\nCREATE INDEX scale_write_5_1 on scale_write_5(id1);\nGO\nCREATE INDEX scale_write_5_2 on scale_write_5(id2, id1);\nGO\nCREATE INDEX scale_write_5_3 on scale_write_5(id3, id2, id1);\nGO\nCREATE INDEX scale_write_5_4 on scale_write_5(id4, id3, id2\n ,id1);\nGO\nCREATE INDEX scale_write_5_5 on scale_write_5(id5, id4, id3\n ,id2, id1);\nGO\n```\n\n```\nCREATE PROCEDURE \nrun_insert(@idxes INT, @q INT, @n INT, @mode VARCHAR(64) OUT)\nAS BEGIN\nDECLARE @r2 INT = CEILING(rand() * 9000000)+1000000;\nDECLARE @r3 INT = CEILING(rand() * 9000000)+1000000;\nDECLARE @r4 INT = CEILING(rand() * 9000000)+1000000;\nDECLARE @r5 INT = CEILING(rand() * 9000000)+1000000;\nDECLARE @d1 INT;\n WHILE (@n > 0) BEGIN\n SET @d1 = CEILING(rand() * @q);\n IF @idxes = 0 \n INSERT INTO scale_write_0 (id1, id2, id3, id4, id5)\n VALUES (@d1, @r2, @r3, @r4, @r5);\n ELSE IF @idxes = 1\n INSERT INTO scale_write_1 (id1, id2, id3, id4, id5)\n VALUES (@d1, @r2, @r3, @r4, @r5);\n ELSE IF @idxes = 2 \n INSERT INTO scale_write_2 (id1, id2, id3, id4, id5)\n VALUES (@d1, @r2, @r3, @r4, @r5);\n ELSE IF @idxes = 3\n INSERT INTO scale_write_3 (id1, id2, id3, id4, id5)\n VALUES (@d1, @r2, @r3, @r4, @r5);\n ELSE IF @idxes = 4\n INSERT INTO scale_write_4 (id1, id2, id3, id4, id5)\n VALUES (@d1, @r2, @r3, @r4, @r5);\n ELSE IF @idxes = 5 \n INSERT INTO scale_write_5 (id1, id2, id3, id4, id5)\n VALUES (@d1, @r2, @r3, @r4, @r5);\n SET @n = @n - 1;\n END;\n SET @mode = 'insert';\nEND;\ngo\n\nCREATE PROCEDURE\nrun_delete(@idxes INT, @q INT, @n INT, @mode VARCHAR(64) OUT)\nAS BEGIN\nDECLARE @cnt INT = @n;\nDECLARE @aff INT = 0;\nDECLARE @d1 INT;\n WHILE (@cnt >0) BEGIN\n SET @d1 = CEILING(rand() * @q) + @q;\n IF @idxes = 1 \n DELETE FROM scale_write_1 WHERE id1 = @d1;\n ELSE IF @idxes = 2 \n DELETE FROM scale_write_2 WHERE id1 = @d1;\n ELSE IF @idxes = 3 \n DELETE FROM scale_write_3 WHERE id1 = @d1;\n ELSE IF @idxes = 4 \n DELETE FROM scale_write_4 WHERE id1 = @d1;\n ELSE IF @idxes = 5 \n DELETE FROM scale_write_5 WHERE id1 = @d1;\n SET @aff = @aff + @@ROWCOUNT;\n SET @cnt = @cnt - 1;\n END; \n SET @mode = CASE WHEN @aff = @n THEN 'delete' ELSE NULL END;\nEND;\n\ngo\n\nCREATE PROCEDURE\nrun_update_all(@idxes INT, @q INT, @n INT, @mode VARCHAR(64) OUT)\nAS BEGIN\nDECLARE @r2 INT = CEILING(rand() * 9000000)+1000000;\nDECLARE @r3 INT = CEILING(rand() * 9000000)+1000000;\nDECLARE @r4 INT = CEILING(rand() * 9000000)+1000000;\nDECLARE @r5 INT = CEILING(rand() * 9000000)+1000000;\nDECLARE @cnt INT = @n;\nDECLARE @aff INT = 0;\nDECLARE @d1 INT;\n WHILE (@cnt >0) BEGIN\n SET @d1 = CEILING(rand() * @q) + 2 * @q;\n IF @idxes = 1 \n UPDATE scale_write_1\n SET id2=@r2, id3=@r3, id4=@r4, id5=@r5 WHERE id1=@d1;\n ELSE IF @idxes = 2 \n UPDATE scale_write_2\n SET id2=@r2, id3=@r3, id4=@r4, id5=@r5 WHERE id1=@d1;\n ELSE IF @idxes = 3 \n UPDATE scale_write_3\n SET id2=@r2, id3=@r3, id4=@r4, id5=@r5 WHERE id1=@d1;\n ELSE IF @idxes = 4 \n UPDATE scale_write_4\n SET id2=@r2, id3=@r3, id4=@r4, id5=@r5 WHERE id1=@d1;\n ELSE IF @idxes = 5 \n UPDATE scale_write_5\n SET id2=@r2, id3=@r3, id4=@r4, id5=@r5 WHERE id1=@d1;\n\n SET @aff = @aff + @@ROWCOUNT;\n SET @cnt = @cnt - 1;\n END; \n SET @mode = CASE WHEN @aff = @n THEN 'update all'\n ELSE NULL END;\nEND;\ngo\n\nCREATE PROCEDURE\nrun_update_one(@idxes INT, @q INT, @n INT, @mode VARCHAR(64) OUT)\nAS BEGIN\nDECLARE @r2 INT = CEILING(rand() * 9000000)+1000000;\nDECLARE @cnt INT = @n;\nDECLARE @aff INT = 0;\nDECLARE @d1 INT;\n WHILE (@cnt >0) BEGIN\n SET @d1 = CEILING(rand() * @q) + 3 * @q;\n IF @idxes = 1 -- no index updated\n UPDATE scale_write_1 SET id2 = @r2 WHERE id1=@d1;\n ELSE IF @idxes = 2 -- one index updated\n UPDATE scale_write_2 SET id2 = @r2 WHERE id1=@d1; \n ELSE IF @idxes = 3 -- one index updated\n UPDATE scale_write_3 SET id3 = @r2 WHERE id1=@d1;\n ELSE IF @idxes = 4 -- one index updated\n UPDATE scale_write_4 SET id4 = @r2 WHERE id1=@d1; \n ELSE IF @idxes = 5 -- one index updated\n UPDATE scale_write_5 SET id5 = @r2 WHERE id1=@d1;\n ELSE SET @aff = 0;\n SET @mode = CASE WHEN @@ROWCOUNT = 1 THEN 'update one'\n ELSE NULL END;\n SET @aff = @aff + @@ROWCOUNT;\n SET @cnt = @cnt - 1;\n END; \n SET @mode = CASE WHEN @aff = @n THEN 'update one'\n ELSE NULL END;\nEND;\ngo\n\nCREATE PROCEDURE\ntest_write_scalability (@n int, @inner int)\nAS BEGIN\nDECLARE @iter INT;\nDECLARE @indxs INT;\nDECLARE @strt DATETIME2;\nDECLARE @dur NUMERIC;\nDECLARE @cmnd INT;\nDECLARE @q INT;\nDECLARE @c1 VARCHAR(64);\nDECLARE @table TABLE\n( indxes NUMERIC NOT NULL,\n mode VARCHAR(64) NOT NULL,\n seconds NUMERIC NOT NULL,\n cnt NUMERIC NOT NULL);\n\n SELECT @q = (max(id1) - min(id1))/4 FROM scale_write_1;\n SET @iter = 0;\n WHILE (@iter < @n) BEGIN\n SET @cmnd = 0;\n WHILE (@cmnd <= 3) BEGIN\n SET @indxs = 0;\n WHILE (@indxs <= 5) BEGIN\n SET @strt = SYSDATETIME();\n IF (@cmnd = 0)\n exec [dbo].run_insert @indxs, @q, @inner\n , @mode=@c1 OUTPUT;\n ELSE IF (@cmnd = 1) \n exec [dbo].run_update_all @indxs, @q, @inner\n , @mode=@c1 OUTPUT;\n ELSE IF (@cmnd = 2) \n exec [dbo].run_update_one @indxs, @q, @inner\n , @mode=@c1 OUTPUT;\n ELSE IF (@cmnd = 3) BEGIN\n exec [dbo].run_delete @indxs, @q, @inner\n , @mode=@c1 OUTPUT;\n END;\n\n SET @dur = datediff(microsecond, @strt, SYSDATETIME());\n IF @c1 IS NOT NULL\n BEGIN\n INSERT INTO @table\n VALUES (@indxs, @c1, @dur, 1);\n END;\n SET @indxs = @indxs +1;\n END;\n SET @cmnd = @cmnd +1;\n END;\n SET @iter = @iter + 1;\n END;\n SELECT indxes, mode, seconds, cnt from @table;\nEND;\n```\n\n```\nSET NOCOUNT ON;\n\nCREATE TABLE #res (\n indxes NUMERIC NOT NULL,\n mode VARCHAR(64) NOT NULL,\n seconds NUMERIC NOT NULL,\n cnt NUMERIC NOT NULL); \nGO\n\nINSERT INTO #res\nEXEC test_write_scalability 1000;\ngo\n\nSELECT indxes, [insert], [delete], [update all], [update one]\n FROM (SELECT indxes, mode, seconds/1000000 seconds\n FROM #res\n ) x\n PIVOT (AVG(seconds)\n FOR mode\n IN ([insert],[delete],[update all],[update one]))\n AS AvgExecTime\n ORDER BY indxes;\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 8148, "slov": 1241, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:24", "sha256": "846e6a22f4e2dadafc7e31b735c99af809e2c5fd5d7659941a9e7010e15de481", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sql-server/join", "titulek": "Example Scripts for SQL Server - The Join Operation", "h1": "SQL Server Scripts for “The Join Operation”", "popis": "CREATE & INSERT statements to create the SQL Server example database for Chapter 4, The Join Operation", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sql-server/join", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for SQL Server - The Join Operation", "og:description": "CREATE & INSERT statements to create the SQL Server example database for Chapter 4, The Join Operation", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "SQL Server"], "osnova": [{"uroven": 1, "text": "SQL Server Scripts for “The Join Operation”"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# SQL Server Scripts for “The Join Operation”\n\n---\n\nThis section contains the `create`, `insert` and T-SQL code to run the examples from [Chapter 4*The Join Operation*](/sql/join) in a SQL Server database. It requires the helper functions `RANDOM_DATE` and `RANDOM_INT` from the [where clause examples](/sql/example-schema/sql-server/where-clause).\n\n```\nCREATE TABLE sales (\n sale_id NUMERIC NOT NULL,\n employee_id NUMERIC NOT NULL,\n subsidiary_id NUMERIC NOT NULL,\n sale_date DATE NOT NULL,\n eur_value NUMERIC(17,2) NOT NULL,\n product_id NUMERIC NOT NULL,\n quantity NUMERIC NOT NULL,\n junk CHAR(200),\n CONSTRAINT sales_pk \n PRIMARY KEY NONCLUSTERED (sale_id),\n CONSTRAINT sales_emp_fk \n FOREIGN KEY (subsidiary_id, employee_id)\n REFERENCES employees(subsidiary_id, employee_id)\n);\nGO\n\nSELECT RAND(0);\nGO\n\nWITH generator (n)\n AS (\n SELECT 1\n UNION ALL\n SELECT n + 1\n FROM generator\n WHERE N < 1800\n )\nINSERT INTO sales (sale_id\n , subsidiary_id, employee_id\n , sale_date, eur_value\n , product_id, quantity\n , junk)\nSELECT row_number() OVER (ORDER BY sale_date), data.*\n FROM (\n SELECT e.subsidiary_id, e.employee_id\n , [dbo].random_date(0, 3650) sale_date\n , [dbo].random_int(1, 100000)/100 eur_value\n , [dbo].random_int(1, 25) product_id\n , [dbo].random_int(1, 5) quantity\n , 'junk' junk\n FROM employees e\n , generator gen\n WHERE employee_id % 7 = 4\n AND gen.n < employee_id / 5\n ) data\n WHERE DATEPART(weekday, sale_date)\n <> DATEPART(weekday, '2012-01-01')\n ORDER BY sale_date\nOPTION(MAXRECURSION 2000);\nGO\n\nEXEC sp_updatestats;\nGO\n```\n\nNotes:\n\n- The rows are inserted chronologically to reflect a natural table growth.\n- Only a small fraction of employees have sales at all.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 2304, "slov": 308, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:25", "sha256": "bb20db6a3c4b454229d415f6864d091a81fc4ad811b3a7cfc947a6cea6f8b1e9", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sql-server/partial-results", "titulek": "Example Scripts for SQL Server - Partial Results", "h1": "SQL Server Scripts for “Partial Results”", "popis": "CREATE & INSERT statements to create the SQL Server example database for Chapter 7, Partial Results", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sql-server/partial-results", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for SQL Server - Partial Results", "og:description": "CREATE & INSERT statements to create the SQL Server example database for Chapter 7, Partial Results", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "SQL Server"], "osnova": [{"uroven": 1, "text": "SQL Server Scripts for “Partial Results”"}, {"uroven": 2, "text": "Querying Top-N Rows"}, {"uroven": 2, "text": "Paging Through Results"}, {"uroven": 2, "text": "Window-Functions"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# SQL Server Scripts for “Partial Results”\n\n---\n\nThis section contains the `create` and `insert` statements to run the examples from [Chapter 7*Partial Results*](/sql/partial-results) in an SQL Server database.\n\n## Querying Top-N Rows\n\nThe test approach for the scalability of Top-N queries is the same as used in the “[Testing and Scalability](/sql/example-schema/sql-server/performance-testing-scalability)” chapter.\n\n```\nCREATE FUNCTION [dbo].test_top_n_scalability (@n int)\n RETURNS @table TABLE\n( section NUMERIC NOT NULL PRIMARY KEY,\n duration NUMERIC NOT NULL,\n rows NUMERIC NOT NULL)\nAS BEGIN\n DECLARE @strt DATETIME2\n DECLARE @iter INT\n DECLARE @xsec INT\n DECLARE @xcnt INT\n DECLARE @xrnd INT\n\n SET @iter = 0\n WHILE (@iter < @n) BEGIN\n SET @xsec = 0\n WHILE (@xsec < 300) BEGIN\n SET @strt = SYSDATETIME()\n\n SELECT @xcnt = COUNT(*)\n FROM (SELECT TOP 100 *\n FROM scale_data\n WHERE section=@xsec\n ORDER BY id2) tlb; \n\n IF @iter = 0 BEGIN\n INSERT INTO @table\n VALUES ( @xsec\n , datediff(microsecond, @strt, SYSDATETIME())\n , @xcnt);\n END; ELSE BEGIN\n UPDATE @table\n SET duration = duration \n + datediff(microsecond, @strt, SYSDATETIME())\n , rows = rows + @xcnt\n WHERE section = @xsec\n END;\n SET @xsec = @xsec + 1\n END;\n SET @iter = @iter + 1\n END;\n\n RETURN;\nEND;\n\nGO\n```\n\nFirst, using a pipelined Top-N with an index covering the `order by` clause:\n\n```\nCREATE INDEX scale_fast ON scale_data(section, id2, id1);\nGO\n\nSELECT * FROM [dbo].[test_top_n_scalability] (10);\nGO\n```\n\nThen, using an index for the `where` clause only. However, SQL Server refuses to use the index unless it includes the ID2 column. So, it is not exactly the same test case as for the other databases, but it still shows the scalability.\n\n```\nDROP INDEX scale_fast ON scale_data;\nGO\n\nCREATE INDEX scale_slow ON scale_data(section, id1, id2);\nGO\n\nSELECT * FROM [dbo].[test_top_n_scalability] (10);\nGO\n```\n\n## Paging Through Results\n\n```\nCREATE FUNCTION [dbo].test_topn_scalability (@n int)\n RETURNS @table TABLE\n( section NUMERIC NOT NULL,\n mode NUMERIC NOT NULL,\n page NUMERIC NOT NULL,\n seconds NUMERIC NOT NULL)\nAS BEGIN\n DECLARE @strt DATETIME2\n DECLARE @iter INT\n DECLARE @xmde INT\n DECLARE @page INT\n DECLARE @xsec INT\n DECLARE @c1 INT, @c2 INT;\n DECLARE @cont TABLE (\n section int NOT NULL,\n c1 int NOT NULL, \n c2 int NOT NULL\n );\n\n SET @iter = 0\n WHILE (@iter < @n) BEGIN\n SET @xmde = 0\n WHILE (@xmde <= 1) BEGIN\n SET @page = 0\n WHILE (@page <= 100) BEGIN\n SET @xsec = 5\n WHILE (@xsec < 300) BEGIN\n SET @strt = SYSDATETIME()\n\n IF @xmde = 0 OR @page = 0 BEGIN\n DECLARE sql CURSOR FAST_FORWARD FOR\n SELECT id2, id1\n FROM (SELECT id2, id1\n , ROW_NUMBER() OVER (ORDER BY id2, id1) rn\n FROM scale_data\n WHERE section = @xsec\n ) result\n WHERE rn > 100 * (@page )\n AND rn <= 100 * (@page+1);\n \n END; ELSE BEGIN\n SELECT @c2 = c2, @c1 = c1 FROM @cont WHERE section = @xsec;\n DECLARE sql CURSOR FAST_FORWARD FOR\n SELECT TOP 100 id2, id1\n FROM scale_data\n WHERE section = @xsec\n AND id2 >= @c2\n AND ( \n (id2 = @c2 AND id1 > @c1)\n OR \n (id2 > @c2)\n )\n ORDER BY id2, id1\n END;\n\n OPEN sql; FETCH NEXT FROM sql INTO @c2, @c1;\n WHILE @@FETCH_STATUS = 0 BEGIN\n FETCH NEXT FROM sql INTO @c2, @c1;\n END\n CLOSE sql; DEALLOCATE sql;\n\n INSERT INTO @table\n VALUES ( @xsec\n , @xmde\n , @page\n , datediff(microsecond, @strt, SYSDATETIME())\n );\n UPDATE @cont set c1 = @c1, c2 = @c2\n WHERE section = @xsec;\n IF @@ROWCOUNT = 0\n INSERT INTO @cont VALUES(@xsec, @c1, @c2);\n SET @xsec = @xsec + 1\n END;\n SET @page = @page + 1\n END;\n SET @xmde = @xmde + 1\n END;\n SET @iter = @iter + 1\n END;\n\n RETURN;\nEND;\nGO\n\nSELECT section, mode, page, sum(seconds)\n FROM [dbo].[test_topn_scalability] (10)\n WHERE section=10\n GROUP BY section, mode, page\n ORDER BY section, mode, page;\nGO\n```\n\n## Window-Functions\n\nSQL Server 2008R2 utilizes the index to implement a pipelined Top-N query when using the window-Function `ROW_NUMBER`:\n\n```\nSELECT *\n FROM ( SELECT sales.*\n , ROW_NUMBER() OVER (ORDER BY sale_date DESC\n , sale_id DESC) rn\n FROM sales\n ) tmp\n WHERE rn between 11 and 20\n ORDER BY sale_date DESC, sale_id DESC\n```\n\n`|-**Sort(ORDER BY:([sale_date] DESC, [sale_id] DESC))**\n |-Filter(WHERE:([Expr1004]>=(11) AND [Expr1004]<=(20)))\n |-**Top(TOP EXPRESSION:(20))**\n |-Sequence Project(DEFINE:([Expr1004]=row_number))\n |-Segment\n |-Nested Loops(Inner Join, WITH ORDERED PREFETCH)\n |-Index Scan([sales].[sl_dtid], **ORDERED BACKWARD**)\n |-RID Lookup([sales],\n SEEK:([Bmk1000]=[Bmk1000])\n LOOKUP ORDERED FORWARD)`\n\nSQL Server reads the index backwards, so that it doesn’t need an sort operation for the window function. The Top-Step aborts the operations below it, as soon as 20 rows arrived. The last two steps, shown first in the execution plan, filter the leading 10 rows off and sorts the remaining result. This sort operation will just sort ten rows, so it is not going to be a performance problem.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 5385, "slov": 843, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:26", "sha256": "88718fb0b70c553a0a61b432f2f277f98349107117d118778ea6bb71daa95c0e", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sql-server/performance-testing-scalability", "titulek": "Example Scripts for SQL Server - Testing and Scalability", "h1": "SQL Server Scripts for “Testing and Scalability”", "popis": "CREATE & INSERT statements to create the SQL Server example database for Chapter 3, Testing and Scalability", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sql-server/performance-testing-scalability", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for SQL Server - Testing and Scalability", "og:description": "CREATE & INSERT statements to create the SQL Server example database for Chapter 3, Testing and Scalability", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "SQL Server"], "osnova": [{"uroven": 1, "text": "SQL Server Scripts for “Testing and Scalability”"}, {"uroven": 4, "text": "Warning"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# SQL Server Scripts for “Testing and Scalability”\n\n---\n\nThis section contains the `create`, `insert` and T-SQL code to run the scalability test from [Chapter 3*Performance and Scalability*](/sql/testing-scalability) in an SQL Server database.\n\n#### Warning\n\nThese scripts will create large objects in the database and produce a huge amount of transaction logs.\n\nIt’s required to run the test against a very large data set to make sure caching does not affect the measurement. Depending on your environment, you might need to create even larger tables to reproduce a linear result as shown in the book.\n\n```\nCREATE TABLE scale_data (\n section NUMERIC NOT NULL,\n id1 NUMERIC NOT NULL,\n id2 NUMERIC NOT NULL,\n UNIQUE (section, id1)\n);\n```\n\nNote:\n\n- There is no primary key (to keep the data generation simple).\n- There is no index (yet). That’s done after filling the table.\n- There is no “junk” column to keep the table small.\n\n```\nDECLARE @section INT\nSET @section = 300\n\nWHILE (@section >= 0) BEGIN\n\n WITH generate_series (n) AS (\n SELECT 1\n UNION ALL\n SELECT n + 1\n FROM generate_series\n WHERE N < 3000\n ), generate_series2 (n) AS (\n SELECT ROW_NUMBER() OVER(ORDER BY g1.n, g2.n)\n FROM generate_series g1\n CROSS JOIN generate_series g2\n WHERE g2.n <= @section\n )\n INSERT INTO scale_data\n SELECT @section, gen.*\n , CEILING(ABS(CAST(NEWID() AS BINARY(6)) %100))\n FROM generate_series2 gen\n WHERE gen.n <= @section * 3000\n OPTION(MAXRECURSION 32767);\n\n SET @section = @section -1\nEND;\nGO\n```\n\nNote:This code generates 300 sections (highlighted). You may need to adjust the number for your environment.The table will need some gigabytes.\n\n```\nCREATE INDEX scale_slow ON scale_data(section, id1, id2);\nGO\n```\n\nNote:\n\nThe index will also need some gigabytes.That might take ages.\n\n```\nCREATE VIEW rand_helper AS SELECT rnd=RAND();\nGO \n\nCREATE FUNCTION [dbo].test_scalability (@n int)\n RETURNS @table TABLE\n( section NUMERIC NOT NULL PRIMARY KEY,\n duration NUMERIC NOT NULL,\n rows NUMERIC NOT NULL)\nAS BEGIN\n DECLARE @strt DATETIME2\n DECLARE @iter INT\n DECLARE @xsec INT\n DECLARE @xcnt INT\n DECLARE @xrnd INT\n\n SET @iter = 0\n WHILE (@iter < @n) BEGIN\n SET @xsec = 0\n WHILE (@xsec < 300) BEGIN\n SELECT @xrnd=CEILING(rnd * 100) FROM rand_helper;\n SET @strt = SYSDATETIME()\n\n SELECT @xcnt = COUNT(*)\n FROM (SELECT *\n FROM scale_data\n WHERE section=@xsec\n AND id2=@xrnd) tlb; \n\n IF @iter = 0 BEGIN\n INSERT INTO @table\n VALUES ( @xsec\n , datediff(microsecond, @strt, SYSDATETIME())\n , @xcnt);\n END; ELSE BEGIN\n UPDATE @table\n SET duration = duration \n + datediff(microsecond, @strt, SYSDATETIME())\n , rows = rows + @xcnt\n WHERE section = @xsec\n END;\n SET @xsec = @xsec + 1\n END;\n SET @iter = @iter + 1\n END;\n\n RETURN;\nEND;\n\nGO\n```\n\nNote:\n\nThe `SCALABILITY_SCALABILITY` function returns a table.It’s hard-coded to run the test 300 sections (highlighted).The number of iterations is configurableThe `RAND_HELPER` view is required to bypass the use of `RAND()` in a function.\n\n```\nSELECT * FROM [dbo].[test_scalability] (10);\n```\n\nThe counter test, with a better index, can be done like that:\n\n```\nCREATE INDEX scale_fast ON scale_data(section, id2, id1);\nGO\n\nSELECT * FROM [dbo].[test_scalability] (10);\nGO\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3766, "slov": 560, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:27", "sha256": "3c371c1fb5f914d8038d10c3413c5f1257b8243f221a49b3d6473cd1b67cfeb5", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sql-server/sorting-grouping", "titulek": "Example Scripts for SQL Server - Sorting and Grouping", "h1": "SQL Server Scripts for “Sorting and Grouping”", "popis": "CREATE & INSERT statements to create the SQL Server example database for Chapter 6, Sorting and Grouping", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sql-server/sorting-grouping", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for SQL Server - Sorting and Grouping", "og:description": "CREATE & INSERT statements to create the SQL Server example database for Chapter 6, Sorting and Grouping", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "SQL Server"], "osnova": [{"uroven": 1, "text": "SQL Server Scripts for “Sorting and Grouping”"}, {"uroven": 2, "text": "Indexed Order By"}, {"uroven": 2, "text": "Indexing ASC, DESC and NULLS FIRST/LAST"}, {"uroven": 2, "text": "Indexed Group By"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# SQL Server Scripts for “Sorting and Grouping”\n\n---\n\nThis section contains the code and execution plans for [Chapter 6*Sorting and Grouping*](/sql/sorting-grouping) in a SQL Server database.\n\n## Indexed Order By\n\n```\nDROP INDEX sales_date ON sales;\nGO\n\nCREATE INDEX sales_dt_pr ON sales (sale_date, product_id);\nGO\n\nEXEC sp_updatestats;\nGO\n\nSET STATISTICS PROFILE ON;\n\nSELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date = DATEADD(day, -1, GETDATE())\n ORDER BY sale_date, product_id;\n```\n\nThe execution does not perform a sort operation:\n\n`Nested Loops(Inner Join, OUTER REFERENCES:[Bmk1000])\n |--Index Seek(OBJECT:([sales].[sales_dt_pr]),\n | SEEK:[sales].[sale_date]=dateadd(day,(-1),getdate())\n | **ORDERED FORWARD**)\n |--RID Lookup(OBJECT:([sales]),\n SEEK:[Bmk1000]=[Bmk1000]) LOOKUP ORDERED FORWARD`\n\nSQL Server uses the same execution plan, when sorting by `PRODUCT_ID` only.\n\n```\nSELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date = DATEADD(day, -1, GETDATE())\n ORDER BY product_id;\n```\n\nUsing an greater or equals condition requires an Sort operation:\n\n```\nSELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= DATEADD(day, -1, GETDATE())\n ORDER BY product_id;\n```\n\nAlthough the row estimate got lower, causing the cost also to be lower:\n\n`**Sort(ORDER BY:([test].[dbo].[sales].[product_id] ASC))**\n |--Nested Loops(Inner Join, OPTIMIZED WITH UNORDERED PREFETCH)\n |--Compute Scalar(DEFINE:([Expr1009]=BmkToPage([Bmk1000])))\n | |--Nested Loops(Inner Join)\n | |--Compute Scalar([...])\n | | |--Constant Scan\n | |--Index Seek(OBJECT:([sales].[sales_dt_pr]),\n | SEEK:([sales].[sale_date] > [Expr1007]\n | AND [sales].[sale_date] < NULL) ORDERED FORWARD)\n |--RID Lookup(OBJECT:([sales]),\n SEEK:([Bmk1000]=[Bmk1000]) LOOKUP ORDERED FORWARD)`\n\n## Indexing ASC, DESC and NULLS FIRST/LAST\n\nScanning an index backwards:\n\n```\nSELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= DATEADD(day, -1, GETDATE())\n ORDER BY sale_date DESC, product_id DESC;\n```\n\nMixing `ASC` and `DESC` causes an explicit sort:\n\n```\nSELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= DATEADD(day, -1, GETDATE())\n ORDER BY sale_date ASC, product_id DESC;\n```\n\nOrdering the index with mixed `ASC`/`DESC` modifiers:\n\n```\nDROP INDEX sales_dt_pr ON sales;\nGO\n\nCREATE INDEX sales_dt_pr\n ON sales (sale_date ASC, product_id DESC);\nGO\n\nSELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= DATEADD(day, -1, GETDATE())\n ORDER BY sale_date ASC, product_id DESC;\n```\n\nSQL Server 2008R2 does not implement the `order by` `NULLS` extension.\n\n```\nSELECT sale_date, product_id, quantity\n FROM sales\n WHERE sale_date >= DATEADD(day, -1, GETDATE())\n ORDER BY sale_date ASC, product_id DESC NULLS LAST;\n```\n\n## Indexed Group By\n\nPipelined `group by` execution:\n\n```\nSELECT product_id, SUM(eur_value)\n FROM sales\n WHERE sale_date = DATEADD(day, -1, GETDATE())\n GROUP BY product_id;\n```\n\nExplicit Sort/Group when retrieving the stats for two days (parallelism disable for plan readability):\n\n```\nSELECT product_id, SUM(eur_value)\n FROM sales\n WHERE sale_date >= DATEADD(day, -1, GETDATE())\n GROUP BY product_id\nOPTION (MAXDOP 1);\n```\n\nThe Hash-Algorithm is used when aggregating a larger set:\n\n```\nSELECT product_id, SUM(eur_value)\n FROM sales\n WHERE sale_date >= DATEADD(day, -100, GETDATE())\n GROUP BY product_id\nOPTION (MAXDOP 1);\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3877, "slov": 480, "odkazu": 66, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:28", "sha256": "acefab6779681b08bf328cb033183a7cdb3f8065e643f77cd88e0f5dd758387b", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sql-server/where-clause", "titulek": "Example Scripts for SQL Server - The WHERE Clause", "h1": "SQL Server Scripts for “The Where Clause”", "popis": "CREATE & INSERT statements to create the SQL Server example database for Chapter 2, The Where Clause", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sql-server/where-clause", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for SQL Server - The WHERE Clause", "og:description": "CREATE & INSERT statements to create the SQL Server example database for Chapter 2, The Where Clause", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "SQL Server"], "osnova": [{"uroven": 1, "text": "SQL Server Scripts for “The Where Clause”"}, {"uroven": 2, "text": "The Equals Operator"}, {"uroven": 3, "text": "Surrogate Keys"}, {"uroven": 3, "text": "Concatenated Keys"}, {"uroven": 2, "text": "Functions"}, {"uroven": 2, "text": "Filtered (Partial) Indexes"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# SQL Server Scripts for “The Where Clause”\n\n---\n\n## The Equals Operator\n\n### Surrogate Keys\n\nThe following script creates the `EMPLOYEES` table with 1000 entries.\n\nTo generate random data, a view/function pair is used to bypass the “all user-defined functions are deterministic” feature of SQL Server.\n\n```\nCREATE TABLE employees (\n employee_id NUMERIC NOT NULL,\n first_name VARCHAR(1000) NOT NULL,\n last_name VARCHAR(900) NOT NULL,\n date_of_birth DATE ,\n phone_number VARCHAR(1000) NOT NULL,\n junk CHAR(1000) ,\n CONSTRAINT employees_pk\n PRIMARY KEY NONCLUSTERED (employee_id)\n);\nGO\n```\n\n```\nIF OBJECT_ID('rand_helper') IS NOT NULL\n DROP VIEW rand_helper;\nGO\n\nCREATE VIEW rand_helper AS SELECT RND=RAND();\nGO\n```\n\n```\nIF OBJECT_ID('random_string') IS NOT NULL\n DROP FUNCTION random_string;\nGO\n\nCREATE FUNCTION random_string (@maxlen int)\n RETURNS VARCHAR(255)\nAS BEGIN\n DECLARE @rv VARCHAR(255)\n DECLARE @loop int\n DECLARE @len int\n\n SET @len = (SELECT CAST(rnd * (@maxlen-3) AS INT) + 3\n FROM rand_helper)\n SET @rv = ''\n SET @loop = 0\n\n WHILE @loop < @len BEGIN\n SET @rv = @rv \n + CHAR(CAST((SELECT rnd * 26\n FROM rand_helper) AS INT )+97)\n IF @loop = 0 BEGIN\n SET @rv = UPPER(@rv)\n END\n SET @loop = @loop +1;\n END\n\n RETURN @rv\nEND\nGO\n```\n\n```\nIF OBJECT_ID('random_date') IS NOT NULL\n DROP FUNCTION random_date;\nGO\n\nCREATE FUNCTION random_date (@mindays int, @maxdays int) \n RETURNS VARCHAR(255)\nAS BEGIN\n DECLARE @rv date\n SET @rv = (SELECT GetDate() \n - rnd * (@maxdays-@mindays)\n - @mindays\n FROM rand_helper)\n RETURN @rv\nEND\nGO\n```\n\n```\nIF OBJECT_ID('random_int') IS NOT NULL\n DROP FUNCTION random_int;\nGO\n\nCREATE FUNCTION random_int (@min int, @max int)\n RETURNS INT\nAS BEGIN\n DECLARE @rv INT\n SET @rv = (SELECT rnd * (@max) + @min\n FROM rand_helper)\n RETURN @rv\nEND\nGO\n```\n\n```\nWITH generator (n) AS\n( SELECT 1\n UNION ALL\n SELECT n + 1 FROM generator\nWHERE n < 1000\n)\nINSERT INTO employees (employee_id\n , first_name, last_name\n , date_of_birth, phone_number, junk)\nselect n employee_id\n , [dbo].random_string(11) first_name\n , [dbo].random_string(11) last_name \n , [dbo].random_date(20*365, 60*365) dob\n , 'N/A' phone\n , 'junk' junk\n from generator\nOPTION (MAXRECURSION 1000)\nGO\n```\n\n```\nUPDATE employees \n SET first_name='Markus', \n last_name='Winand'\n WHERE employee_id=123;\n\nexec sp_updatestats;\nGO\n```\n\nNotes:\n\n- The `JUNK` column is used to have a realistic row length. Because it’s data type is `CHAR`, as opposed to `VARCHAR2`, it always needs the 1000 bytes it can hold. Without this column the table would become unrealistically small and many demonstrations would not work.\n- Random data is filled into the table, with exception to my entry, that is updated after the insert.\n- Table and index [statistics](/sql/where-clause/the-equals-operator/slow-indexes-part-ii#sb-statistics) are gathered so that the [optimizer](/sql/where-clause/the-equals-operator/slow-indexes-part-ii#sb-optimizer) knows a little bit about the table’s content.\n- SQL Server 2008R2 has a [900 byte index-key constraint](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms191241(v=sql.105)). Hence `LAST_NAME` reduced to 900.\n\n### Concatenated Keys\n\nThis script changes the `EMPLOYEES` table so that it reflects the situation after the merger with Very Big Company:\n\n```\nALTER TABLE employees ADD subsidiary_id NUMERIC;\nGO\nUPDATE employees SET subsidiary_id = 30;\nGO\nALTER TABLE employees ALTER COLUMN subsidiary_id \n NUMERIC NOT NULL;\nGO\n\nALTER TABLE employees DROP CONSTRAINT employees_pk;\nGO\nALTER TABLE employees ADD CONSTRAINT employees_pk \n PRIMARY KEY NONCLUSTERED (employee_id, subsidiary_id);\nGO\n\nWITH generator (n) as\n( select 1\nunion all\nselect n + 1 from generator\nwhere N < 9000\n)\nINSERT INTO employees (employee_id\n , first_name, last_name\n , date_of_birth, phone_number\n , junk, subsidiary_id)\nSELECT n employee_id\n , [dbo].random_string(11) first_name\n , [dbo].random_string(11) last_name \n , [dbo].random_date(20*365, 60*365) dob\n , 'N/A' phone\n , 'junk' junk\n , [dbo].random_int(1, (n*29)/9000) subsidiary_id\n FROM generator\nOPTION (MAXRECURSION 9000)\nGO\n\nCREATE UNIQUE NONCLUSTERED INDEX \n employees_pk_tmp \n on employees (employee_id, subsidiary_id);\nGO\nALTER TABLE employees DROP CONSTRAINT employees_pk;\nGO\nALTER TABLE employees ADD CONSTRAINT employees_pk\n PRIMARY KEY NONCLUSTERED (employee_id, subsidiary_id);\nGO\nDROP INDEX employees_pk_tmp ON employees;\nGO\n\nexec sp_updatestats;\nGO\n```\n\nNotes:\n\n- The new primary key just extended by the `SUBSIDIARY_ID`; that is, the `EMPLOYEE_ID` remains in the first position.\n- The new records are randomly assigned to the subsidiaries 1 through 29.\n- The table and index are analyzed again to make the optimizer aware of the grown data volume.\n\nThe next script introduces the index on `SUBSIDIARY_ID` to support the query for all employees of one particular subsidiary:\n\n```\nCREATE NONCLUSTERED INDEX \n emp_sub_id ON employees (subsidiary_id);\n\nexec sp_updatestats;\n```\n\nNotes:\n\n- The table and all indexes are analyzed again.\n\nAlthough that gives decent performance, it’s better to use the index that supports the primary key:\n\n```\nALTER TABLE employees DROP CONSTRAINT employees_pk;\nGO\nALTER TABLE employees ADD CONSTRAINT employees_pk \n PRIMARY KEY NONCLUSTERED (subsidiary_id, employee_id);\nGO\n\nDROP INDEX emp_sub_id ON employees;\n\nexec sp_updatestats;\n```\n\nNotes:\n\n- The procedure leaves the table without primary key for a while. That means that the procedure is not suitable to run online. However, there is nothing accessing our test schema, therefore no danger.\n- The index on `SUBSIDIARY_ID` is now fully redundant and can be dropped.\n\n## Functions\n\nSQL Server uses a case-insensitive collation per default. In that case, you don’t need a function-based index, a regular one will do as well:\n\n```\nCREATE INDEX emp_name ON employees (last_name);\n```\n\n## Filtered (Partial) Indexes\n\n```\nCREATE TABLE messages (\n id numeric not null,\n processed char(1) not null,\n receiver numeric not null,\n message varchar(255),\n primary key (id)\n);\n\nWITH generator (n) AS\n( SELECT 1\n UNION ALL\n SELECT n + 1 FROM generator\nWHERE n < 1000\n)\nINSERT INTO messages (id, processed, receiver, message)\nselect n id\n , case WHEN n % 5 =0 then 'N' else 'Y' end \n , n/10 receiver\n , 'junk' message\n from generator\nOPTION (MAXRECURSION 1000)\n\n-- regular index\n--CREATE INDEX messages_todo\n-- ON messages (receiver, processed) INCLUDE (message);\n\n-- filtered index\nCREATE INDEX messages_only_todo\n ON messages (receiver) INCLUDE (message)\n WHERE processed = 'N';\n\ndeclare @r numeric\nset @r = 4\n\nSELECT message\n FROM messages\n WHERE processed = 'N'\n AND receiver = @r;\n```\n\nAt [SQL Fiddle](https://sqlfiddle.com/#!6/3a717/2).\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 7177, "slov": 1022, "odkazu": 70, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:29", "sha256": "d3e6d0cd96a5caa9ff80cfb5d04b4ed3b24176819b6100dc00442a7f6ebbfc14", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms191241(v=sql.105)", "https://sqlfiddle.com/", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sqlbase", "titulek": "Gupta SQLBase example scripts for Use The Index, Luke!", "h1": "SQLBase Example Scripts", "popis": "CREATE & INSERT statements to create the Use The Index, Luke Gupta SQLBase example database.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sqlbase", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Gupta SQLBase example scripts for Use The Index, Luke!", "og:description": "CREATE & INSERT statements to create the Use The Index, Luke Gupta SQLBase example database.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema"], "osnova": [{"uroven": 1, "text": "SQLBase Example Scripts"}, {"uroven": 2, "text": "Contents"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# SQLBase Example Scripts\n\n---\n\nThe following scripts were tested with Gupta SQLBase 11.7.\n\n## Contents\n\n1. *[The `where` clause](/sql/example-schema/sqlbase/where-clause)*\n2. *[The Join Operation](/sql/example-schema/sqlbase/join)*\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 831, "slov": 100, "odkazu": 60, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:30", "sha256": "9d124f3fafb987b7459e370604290773f392dcaaa460e54394d8ef79cd58e7cb", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sqlbase/join", "titulek": "Example Scripts for Gupta SQLBase - The JOIN Operation", "h1": "SQLBase Example Scripts for “The Join Operation”", "popis": "CREATE & INSERT statements to create the Gupta SQLBase example database for Chapter 4, The Join Operation", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sqlbase/join", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Gupta SQLBase - The JOIN Operation", "og:description": "CREATE & INSERT statements to create the Gupta SQLBase example database for Chapter 4, The Join Operation", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Gupate SQLBase"], "osnova": [{"uroven": 1, "text": "SQLBase Example Scripts for “The Join Operation”"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# SQLBase Example Scripts for “The Join Operation”\n\n---\n\nThis section contains the `create` and `insert` code to run the examples from [Chapter 4*The Join Operation*](/sql/join) in an Gupta/Unify SQLBase database.\n\n```\nCREATE TABLE sales (\n sale_id INTEGER NOT NULL,\n employee_id INTEGER NOT NULL,\n subsidiary_id INTEGER NOT NULL,\n sale_date DATE NOT NULL,\n eur_value DECIMAL(13,2) NOT NULL,\n product_id INTEGER NOT NULL,\n quantity INTEGER NOT NULL,\n junk CHAR(200),\n PRIMARY KEY (sale_id),\n FOREIGN KEY (subsidiary_id, employee_id)\n REFERENCES employees\n);\n\nCREATE UNIQUE INDEX sales_pk ON sales (sale_id);\n\nINSERT INTO sales (sale_id\n , subsidiary_id, employee_id\n , sale_date, eur_value\n , product_id, quantity\n , junk)\n SELECT gen.n *2000*30 + e.employee_id * 30 + e.subsidiary_id AS sale_id\n , e.subsidiary_id, e.employee_id\n , SYSDATE - @mod(n+@MICROSECOND(@NOW), 10*365) AS sale_date\n , (@MOD(@MICROSECOND(@NOW)+n, 9000) + 1000)/100 AS eur_value\n , @MOD(@SECOND(@NOW)+n/9000*29,29) AS product_id\n , @MOD(@SECOND(@NOW)+n/9000*26,5) AS quantity\n , 'junk'\n FROM employees e\n , generator_4k gen\n WHERE @MOD(employee_id, 7) = 4\n AND gen.n < 1800\n AND gen.n < employee_id / 5 ;\n```\n\nNotes:\n\n- The rows are NOT inserted chronologically\n- Only a small fraction of employees have sales at all.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 1879, "slov": 252, "odkazu": 59, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:31", "sha256": "f9bd7e5e8b6ba05a6bee055cace4f6ad98c69e4fc6a61c220e4018bd23608145", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sqlbase/where-clause", "titulek": "Example Scripts for Gupta SQLBase - The WHERE Clause", "h1": "SQLBase Example Scripts for “The Where Clause”", "popis": "CREATE & INSERT statements to create the Gupta SQLBase example database for Chapter 2, The Where Clause", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sqlbase/where-clause", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for Gupta SQLBase - The WHERE Clause", "og:description": "CREATE & INSERT statements to create the Gupta SQLBase example database for Chapter 2, The Where Clause", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "Gupate SQLBase"], "osnova": [{"uroven": 1, "text": "SQLBase Example Scripts for “The Where Clause”"}, {"uroven": 2, "text": "The Equals Operator"}, {"uroven": 3, "text": "Surrogate Keys"}, {"uroven": 3, "text": "Concatenated Keys"}, {"uroven": 2, "text": "Functions"}, {"uroven": 2, "text": "About the Author"}], "markdown": "# SQLBase Example Scripts for “The Where Clause”\n\n---\n\n## The Equals Operator\n\n### Surrogate Keys\n\nCreating the `EMPLOYEES` table with 1000 rows.\n\n```\nCREATE TABLE employees (\n employee_id INTEGER NOT NULL,\n first_name VARCHAR(200) NOT NULL,\n last_name VARCHAR(200) NOT NULL,\n date_of_birth DATE ,\n phone_number VARCHAR(200) NOT NULL,\n junk CHAR(254) ,\n PRIMARY KEY (employee_id)\n);\n\nCREATE UNIQUE INDEX employees_pk ON employees(employee_id);\n\nCREATE TABLE generator_16 (\n n NUMBER NOT NULL,\n PRIMARY KEY (n)\n);\n\nCREATE UNIQUE INDEX generator_16_pk ON generator_16 (n);\n\nINSERT INTO generator_16 VALUES (0);\nINSERT INTO generator_16 VALUES (1);\nINSERT INTO generator_16 VALUES (2);\nINSERT INTO generator_16 VALUES (3);\nINSERT INTO generator_16 VALUES (4);\nINSERT INTO generator_16 VALUES (5);\nINSERT INTO generator_16 VALUES (6);\nINSERT INTO generator_16 VALUES (7);\nINSERT INTO generator_16 VALUES (8);\nINSERT INTO generator_16 VALUES (9);\nINSERT INTO generator_16 VALUES (10);\nINSERT INTO generator_16 VALUES (11);\nINSERT INTO generator_16 VALUES (12);\nINSERT INTO generator_16 VALUES (13);\nINSERT INTO generator_16 VALUES (14);\nINSERT INTO generator_16 VALUES (15);\n\nCREATE VIEW generator_256 (n)\nAS SELECT ( ( hi.n * 16 ) + lo.n ) AS n\n FROM generator_16 lo, generator_16 hi;\n\nCREATE VIEW generator_4k (n)\nAS SELECT ( ( hi.n * 256 ) + lo.n ) AS n\n FROM generator_256 lo, generator_16 hi;\n\nCREATE VIEW generator_64k (n)\nAS SELECT ( ( hi.n * 256 ) + lo.n ) AS n\n FROM generator_256 lo, generator_256 hi;\n\nINSERT INTO employees (employee_id, first_name,\n last_name, date_of_birth, \n phone_number, junk)\nSELECT n +1,\n @CHAR(@mod(n, 26)+65) || @CHAR(@mod(@microsecond(@NOW), 26)+97) || @CHAR(@mod(@minute(@NOW)+n, 26)+97),\n @CHAR(@mod(13+n, 26)+65) || @CHAR(@mod(@microsecond(@NOW)+7, 26)+97) || @CHAR(@mod(@minute(@NOW)+n+17, 26)+97),\n SYSDATE - @mod(n+@MICROSECOND(@NOW), 40*365) - 3650,\n @MOD(@MICROSECOND(@NOW)+n, 9000) + 1000,\n 'junk'\n FROM generator_4k\nWHERE n < 1000;\n\nUPDATE employees \n SET first_name='MARKUS', \n last_name='WINAND'\n WHERE employee_id=123;\n\nUPDATE STATISTICS ON TABLE employees;\nUPDATE STATISTICS ON INDEX employees_pk;\n```\n\nNote:\n\n- We use 200 characters to be on the safe side regarding SQLBases limit on key lenght (total < 255, including overhead).\n\n### Concatenated Keys\n\n```\n-- add subsidiary_id and update existing records\nALTER TABLE employees ADD subsidiary_id INTEGER;\nUPDATE employees SET subsidiary_id = 30;\nALTER TABLE employees MODIFY subsidiary_id NOT NULL;\n\n-- change the PK\nALTER TABLE employees DROP PRIMARY KEY;\nDROP INDEX employees_pk;\n\nCREATE UNIQUE INDEX employees_pk ON employees (employee_id, subsidiary_id);\nALTER TABLE employees PRIMARY KEY (employee_id, subsidiary_id);\n\n-- generate more records (Very Big Company)\nINSERT INTO employees (employee_id, first_name,\n last_name, date_of_birth, \n phone_number, subsidiary_id, junk)\nSELECT n +1,\n @CHAR(@mod(n, 26)+65) || @CHAR(@mod(@microsecond(@NOW), 26)+97) || @CHAR(@mod(@minute(@NOW)+n, 26)+97),\n @CHAR(@mod(13+n, 26)+65) || @CHAR(@mod(@microsecond(@NOW)+7, 26)+97) || @CHAR(@mod(@minute(@NOW)+n+17, 26)+97),\n SYSDATE - @mod(n+@MICROSECOND(@NOW), 40*365) - 3650,\n @MOD(@MICROSECOND(@NOW)+n, 9000) + 1000,\n @MOD(@SECOND(@NOW)+n/9000*29,29),\n 'junk'\n FROM generator_64k\nWHERE n < 9000;\n\nUPDATE STATISTICS ON TABLE employees;\nUPDATE STATISTICS ON INDEX employees_pk;\n```\n\n```\nCREATE INDEX emp_sub_id ON employees (subsidiary_id);\n```\n\nAlthough that gives decent performance, it’s better to use the index that supports the primary key:\n\n```\n-- use tmp index to support the PK\nALTER TABLE employees DROP PRIMARY KEY;\nDROP INDEX employees_pk;\n\nCREATE UNIQUE INDEX employees_pk ON employees (subsidiary_id, employee_id);\nALTER TABLE employees PRIMARY KEY (subsidiary_id, employee_id);\n\nDROP INDEX emp_sub_id;\n\nUPDATE STATISTICS ON INDEX employees_pk;\n```\n\n## Functions\n\n```\nCREATE INDEX emp_name_up ON employees (@upper(last_name));\n```\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 4430, "slov": 553, "odkazu": 59, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:32", "sha256": "76e31ae29e6a2023a19172a0846d02e4f5718e29989508581680fbbcd7b18e23", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sqlite", "titulek": "Example Scripts for SQLite", "h1": "SQLite", "popis": "CREATE & INSERT statements to create the Use The Index, Luke SQLite example database.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sqlite", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for SQLite", "og:description": "CREATE & INSERT statements to create the Use The Index, Luke SQLite example database.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema"], "osnova": [{"uroven": 1, "text": "SQLite"}, {"uroven": 2, "text": "Contents"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# SQLite\n\n---\n\n## Contents\n\n1. *[The `where` clause](/sql/example-schema/sqlite/where-clause)*\n2. *[The Join Operation](/sql/example-schema/sqlite/join)*\n3. *[3-Minute Test](/sql/example-schema/sqlite/3-minute-quiz)*\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 854, "slov": 99, "odkazu": 62, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:33", "sha256": "23734cce0224e9b400e9616990ddda5814268c65acd57c078e04d45a57c051f6", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/example-schema/sqlite/3-minute-quiz", "titulek": "Example Scripts for SQLite - 3-Minute Quiz", "h1": "SQLite Example Scripts for “3-Minute Quiz”", "popis": "CREATE & INSERT statements to create the SQLite example database for The 3-Minute Quiz", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/example-schema/sqlite/3-minute-quiz", "jazyk": "en", "robots_meta": "", "og": {"og:title": "Example Scripts for SQLite - 3-Minute Quiz", "og:description": "CREATE & INSERT statements to create the SQLite example database for The 3-Minute Quiz", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Example Schema", "SQLite"], "osnova": [{"uroven": 1, "text": "SQLite Example Scripts for “3-Minute Quiz”"}, {"uroven": 2, "text": "Question 1 — DATE Anti-Pattern"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 2 — Indexed Top-N"}, {"uroven": 2, "text": "Question 3 — Column Order"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 4 — LIKE"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "Question 5 — Index Only Scan"}, {"uroven": 4, "text": "Learn More"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# SQLite Example Scripts for “3-Minute Quiz”\n\n---\n\nThis section contains the `create`, `insert` and `select` statements for the “[Test your SQL Know-How in 3 Minutes](/3-minute-quiz)” test. You may want to [test yourself](/3-minute-quiz) before reading this page.\n\nThe `create` and `insert` statements are available in the [example schema archive](/use-the-index-luke.tar.gz).\n\nThe execution plans are formatted for better readability.\n\n## Question 1 — DATE Anti-Pattern\n\n```\nCREATE INDEX tbl_idx ON tbl (date_column);\n```\n\n```\nSELECT COUNT(*)\n FROM tbl\n WHERE STRFTIME ('%Y', date_column) = 2025;\n```\n\n```\nSELECT COUNT(*)\n FROM tbl\n WHERE date_column >= '2025-01-01'\n AND date_column < '2026-01-01';\n```\n\nThe first execution plan performs a full index scan (`SCAN TABLE`). The second execution plan, on the other hand, uses the index properly (`SEARCH` is the important part here).\n\n```\n0|0|0|SCAN TABLE tbl USING COVERING INDEX tbl_idx\n```\n\n```\n0|0|0|SEARCH TABLE tbl USING COVERING INDEX tbl_idx \n (date_column>? AND date_column? AND text In the early days, IBM researchers named these kinds of search conditions “sargable predicates” because SARG is a contraction for Search ARGument. In later days, Microsoft and Sybase redefined “sargable” to mean “can be looked up via the index.”\n> \n> — [SQL Performance Tuning](https://web.archive.org/web/20241210124531/https://www.informit.com/articles/article.aspx?p=30247)\n\nI find both definitions pretty useless and avoid the term in my books and articles entirely. However, in Db2 execution plans filter predicates are labeled `SARG`—thus we have to make it explicit that IBM Db2 uses the “original” definition as mentioned above. That is, of course, backed by the documentation:\n\n*Index sargable* predicates are not used to bracket a search, but are evaluated from the index if one is chosen, because the columns involved in the predicate are part of the index key. […]*Data sargable* predicates […] require the access of individual rows from a base table. If necessary, DMS will retrieve the columns needed to evaluate the predicate, as well as any others to satisfy the columns in the SELECT list that could not be obtained from the index.\n\n— [Predicate processing for queries, Db2 LUW 11.1 documentation](https://www.ibm.com/docs/en/db2/11.5.x?topic=optimization-predicate-processing-queries)\n\nThat means, in Db2 predicates labeled `SARG` are generally just filter predicates—either on index level or on table level.\n\nThe very nice part about the predicate information shown in Db2 execution plans is that they don’t just label access predicates, but explicitly say which predicates are used as `START` and/or `STOP` conditions.\n\nThe following example shows all types of predicates as shown by the [`last_explained` view](/sql/explain-plan/db2/getting-an-execution-plan#apa-db2-last_explained):\n\n```\nExplain Plan\n--------------------------------------------------------------\nID | Operation | Rows | Cost\n 1 | RETURN | | 23550\n 2 | GRPBY (COMPLETE) | 1 of 96480 ( .00%) | 23550\n 3 | IXSCAN SCALE_SLOW | 96480 of 60299800 ( .16%) | 23544\n\nPredicate Information\n 3 - START (Q1.SECTION = ?)\n STOP (Q1.SECTION = ?)\n SARG (Q1.ID2 = ?)\n\nExplain plan by Markus Winand - NO WARRANTY\nhttp://use-the-index-luke.com/s/last_explained\n```\n\nThe scanned index range can be determined quite easily from this output—it’s only determined by the `START` and `STOP` predicates (which happen to be the same in this case). The third predicate on the `ID2` column is labeled `SARG` and thus just a filter predicate.\n\nWhile `SARG` predicates may appear on other operations too (e.g. `TBSCAN`), `START` and `STOP` are exclusive to `IXSCAN`. The absence of either `START` or `STOP` indicates an search with only upper or lower bound (e.g. `WHERE x > ?`). If neither `START` nor `STOP` appears for an `IXSCAN`, it means that the full index is read.\n\n*You can’t learn everything in one day. Subscribe the newsletter via **[E-Mail](https://winand.at/lists)**, **[Bluesky](https://bsky.app/profile/winand.at)** or **[RSS](/blog/feed)** to gradually catch up. Have a look at [modern-⁠sql.com](https://modern-sql.com) as well.*\n\n## About the Author\n\nMarkus Winand provides insights into SQL and shows how different systems support it at [modern-sql.com](https://modern-sql.com). Previously he made [use-the-index-luke.com](https://use-the-index-luke.com), which is still actively maintained. Markus can be hired as trainer, speaker and consultant via [winand.at](https://winand.at).", "znaku_textu": 3757, "slov": 563, "odkazu": 65, "kodovani": "utf-8", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 05:15:40", "sha256": "c980b52305eb1b4173438e38a3735c46494de435b84fc96a75cda48879f3c1ae", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://winand.at/home", "https://www.informit.com/articles/article.aspx?p=30247", "https://www.ibm.com/docs/en/db2/11.5.x?topic=optimization-predicate-processing-queries", "https://winand.at/lists", "https://bsky.app/profile/winand.at", "https://modern-sql.com/", "https://winand.at/", "https://sql-performance-explained.com/", "https://www.amazon.com/gp/product/3950307826/ref=as_li_tl?camp=1789&creative=9325&creativeASIN=3950307826&ie=UTF8&linkCode=as2&linkId=XTDRWIA3YYYIRNO&m=A1PG4MQR22GK8T&tag=sqlperexp-20", "https://at.linkedin.com/in/markuswinand/", "https://www.xing.com/profile/Markus_Winand", "https://mastodon.social/@MarkusWinand"]} {"url": "https://use-the-index-luke.com/sql/explain-plan/db2/getting-an-execution-plan", "titulek": "EXPLAIN PLAN FOR and LAST_EXPLAINED", "h1": "Getting an Execution Plan", "popis": "The Db2 (LUW) database uses EXPLAIN PLAN FOR to generate an execution plan. Our LAST_EXPLAINED view fromats it nicley.", "klicova_slova": "", "kanonicka": "https://use-the-index-luke.com/sql/explain-plan/db2/getting-an-execution-plan", "jazyk": "en", "robots_meta": "", "og": {"og:title": "EXPLAIN PLAN FOR and LAST_EXPLAINED", "og:description": "The Db2 (LUW) database uses EXPLAIN PLAN FOR to generate an execution plan. Our LAST_EXPLAINED view fromats it nicley.", "og:image": "https://use-the-index-luke.com/static/util_squirrel.og.fMeqdSQq.png"}, "jsonld": [], "drobecky": ["Table of Contents", "Execution Plans", "Db2 (LUW)"], "osnova": [{"uroven": 1, "text": "Getting an Execution Plan"}, {"uroven": 2, "text": "Create required tables (once)"}, {"uroven": 2, "text": "Explain the statement"}, {"uroven": 2, "text": "Display the stored execution plan"}, {"uroven": 4, "text": "Warning"}, {"uroven": 4, "text": "Tip"}, {"uroven": 2, "text": "About the Author"}], "markdown": "by [Markus Winand](//winand.at/home).\n\n# Getting an Execution Plan\n\n---\n\nGetting an execution plan from Db2 (LUW) is a three step procedure where the first step is a one-time setup.\n\n## Create required tables (once)\n\nThe recommended way to create the required explain tables is to call this procedure:\n\n```\nCALL SYSPROC.SYSINSTALLOBJECTS('EXPLAIN', 'C', \nCAST (NULL AS VARCHAR(128)), CAST (NULL AS VARCHAR(128)))\n```\n\nThis will install the required tables in the `SYSTOOLS` schema (e.g. `SYSTOOLS.EXPLAIN_STREAM`).\n\nAlternative installation procedures and customizations are explained in the [documentation](https://www.ibm.com/docs/en/db2/11.5.x?topic=sql-explain-tables).\n\n## Explain the statement\n\nPrefix any SQL statement with `explain plan for` to store the execution plan details in the explain tables.\n\nThis step does not yet show the execution plan, it just stores it in the database.\n\n```\nEXPLAIN PLAN FOR SELECT 1 FROM sysibm.sysdummy1\n```\n\n## Display the stored execution plan\n\nIBM provides some [tools to display the data stored in the explain tables](https://www.ibm.com/docs/en/db2/11.5.x?topic=facility-tools-collecting-analyzing-explain-information). However, the output format is not as useful as it could be, so I’m using my own SQL query to display the information I’m usually interested in. The Db2 documentation actually recommends doing this.\n\nBelow you find the definition of the view `last_explained` which returns a formatted explain plan for the last statement that was explained for the current user in this database. Please note that it’s scope is not limited to the current session. The view can be used as simple as that:\n\n```\nSELECT * FROM last_explained\n```\n\nThe result might look like this. The [next section](/sql/explain-plan/db2/operations) has the details how to interpret it.\n\n```\nExplain Plan \n----------------------------------------------\nID | Operation | Rows | Cost \n 1 | RETURN | | 0 \n 2 | TBSCAN GENROW | 1 of 1 (100.00%) | 0 \n \nPredicate Information \n \nExplain plan by Markus Winand - NO WARRANTY \nhttp://use-the-index-luke.com/s/last_explained \n```\n\n#### Warning\n\nThis view is highly experimental. It is provided as is without any warranty. It was extended by Ember Crooks to include ActualRows if available. Read [her article](https://datageek.blog/2014/11/18/db2-explain-output-similar-to-other-rdbmses/) to see how to collect them.\n\nThe view assumes the explain tables in the `SYSTOOLS` schema. If you are using a different schema, you need to adjust the below view manually.\n\nMinimum requirement: Db2 (LUW) 9.7 FixPack 4\n\n#### Tip\n\nThe view is available on [GitHub](https://github.com/fatalmind/DB2-last-explained) ([direct download](https://raw.githubusercontent.com/fatalmind/DB2-last-explained/master/last_explained.sql)).\n\n```\n-- Copyright (c) 2014-2017, Markus Winand - NO WARRANTY\n-- Modifications by Ember Crooks - NO WARRANTY\n-- Info & license: http://use-the-index-luke.com/s/last_explained\n--\n--#SET TERMINATOR ;\n\nCREATE OR REPLACE VIEW last_explained AS\nWITH tree(operator_ID, level, path, explain_time, cycle)\nAS\n(\nSELECT 1 operator_id \n , 0 level\n , CAST('001' AS VARCHAR(1000)) path\n , max(explain_time) explain_time\n , 0\n FROM SYSTOOLS.EXPLAIN_OPERATOR O\n WHERE O.EXPLAIN_REQUESTER = SESSION_USER\n\nUNION ALL\n\nSELECT s.source_id\n , level + 1\n , tree.path || '/' || LPAD(CAST(s.source_id AS VARCHAR(3)), 3, '0') path\n , tree.explain_time\n , POSITION('/' || LPAD(CAST(s.source_id AS VARCHAR(3)), 3, '0') || '/' IN path USING OCTETS)\n FROM tree\n , SYSTOOLS.EXPLAIN_STREAM S\n WHERE s.target_id = tree.operator_id\n AND s.explain_time = tree.explain_time\n AND S.Object_Name IS NULL\n AND S.explain_requester = SESSION_USER\n AND tree.cycle = 0\n AND level < 100\n)\nSELECT * \n FROM (\nSELECT \"Explain Plan\"\n FROM (\nSELECT CAST( LPAD(id, MAX(LENGTH(id)) OVER(), ' ')\n || ' | ' \n || RPAD(operation, MAX(LENGTH(operation)) OVER(), ' ')\n || ' | ' \n || LPAD(rows, MAX(LENGTH(rows)) OVER(), ' ')\n || ' | ' \n -- Don't show ActualRows columns if there are no actuals available at all \n || CASE WHEN COUNT(ActualRows) OVER () > 1 -- the heading 'ActualRows' is always present, so \"1\" means no OTHER values\n THEN LPAD(ActualRows, MAX(LENGTH(ActualRows)) OVER(), ' ') || ' | ' \n ELSE ''\n END\n || LPAD(cost, MAX(LENGTH(cost)) OVER(), ' ')\n AS VARCHAR(100)) \"Explain Plan\"\n , path\n FROM (\nSELECT 'ID' ID\n , 'Operation' Operation\n , 'Rows' Rows\n , 'ActualRows' ActualRows\n , 'Cost' Cost\n , '0' Path\n FROM SYSIBM.SYSDUMMY1\n-- TODO: UNION ALL yields duplicate. where do they come from?\nUNION\nSELECT CAST(tree.operator_id as VARCHAR(254)) ID\n , CAST(LPAD(' ', tree.level, ' ')\n || CASE WHEN tree.cycle = 1\n THEN '(cycle) '\n ELSE ''\n END \n || COALESCE (\n TRIM(O.Operator_Type)\n || COALESCE(' (' || argument || ')', '') \n || ' '\n || COALESCE(S.Object_Name,'')\n , ''\n )\n AS VARCHAR(254)) AS OPERATION\n , COALESCE(CAST(rows AS VARCHAR(254)), '') Rows\n , CAST(ActualRows as VARCHAR(254)) ActualRows -- note: no coalesce\n , COALESCE(CAST(CAST(O.Total_Cost AS BIGINT) AS VARCHAR(254)), '') Cost\n , path\n FROM tree\n LEFT JOIN ( SELECT i.source_id\n , i.target_id\n , CAST(CAST(ROUND(o.stream_count) AS BIGINT) AS VARCHAR(12))\n || ' of '\n || CAST (total_rows AS VARCHAR(12))\n || CASE WHEN total_rows > 0\n AND ROUND(o.stream_count) <= total_rows THEN\n ' ('\n || LPAD(CAST (ROUND(ROUND(o.stream_count)/total_rows*100,2)\n AS NUMERIC(5,2)), 6, ' ')\n || '%)'\n ELSE ''\n END rows\n , CASE WHEN act.actual_value is not null then\n CAST(CAST(ROUND(act.actual_value) AS BIGINT) AS VARCHAR(12))\n || ' of '\n || CAST (total_rows AS VARCHAR(12))\n || CASE WHEN total_rows > 0 THEN\n ' ('\n || LPAD(CAST (ROUND(ROUND(act.actual_value)/total_rows*100,2)\n AS NUMERIC(5,2)), 6, ' ')\n || '%)'\n ELSE NULL\n END END ActualRows\n , i.object_name\n , i.explain_time\n FROM (SELECT MAX(source_id) source_id\n , target_id\n , MIN(CAST(ROUND(stream_count,0) AS BIGINT)) total_rows\n , CAST(LISTAGG(object_name) AS VARCHAR(50)) object_name\n , explain_time\n FROM SYSTOOLS.EXPLAIN_STREAM\n WHERE explain_time = (SELECT MAX(explain_time)\n FROM SYSTOOLS.EXPLAIN_OPERATOR\n WHERE EXPLAIN_REQUESTER = SESSION_USER\n )\n GROUP BY target_id, explain_time\n ) I\n LEFT JOIN SYSTOOLS.EXPLAIN_STREAM O\n ON ( I.target_id=o.source_id\n AND I.explain_time = o.explain_time\n AND O.EXPLAIN_REQUESTER = SESSION_USER\n )\n LEFT JOIN SYSTOOLS.EXPLAIN_ACTUALS act\n ON ( act.operator_id = i.target_id\n AND act.explain_time = i.explain_time\n AND act.explain_requester = SESSION_USER\n AND act.ACTUAL_TYPE like 'CARDINALITY%'\n )\n ) s\n ON ( s.target_id = tree.operator_id\n AND s.explain_time = tree.explain_time\n )\n LEFT JOIN SYSTOOLS.EXPLAIN_OPERATOR O\n ON ( o.operator_id = tree.operator_id\n AND o.explain_time = tree.explain_time\n AND o.explain_requester = SESSION_USER\n ) \n LEFT JOIN (SELECT LISTAGG (CASE argument_type\n WHEN 'UNIQUE' THEN\n CASE WHEN argument_value = 'TRUE'\n THEN 'UNIQUE'\n ELSE NULL\n END\n WHEN 'TRUNCSRT' THEN\n CASE WHEN argument_value = 'TRUE'\n THEN 'TOP-N'\n ELSE NULL\n END \n WHEN 'SCANDIR' THEN\n CASE WHEN argument_value != 'FORWARD'\n THEN argument_value\n ELSE NULL\n END \n ELSE argument_value \n END\n , ' ') argument\n , operator_id\n , explain_time\n FROM SYSTOOLS.EXPLAIN_ARGUMENT EA\n WHERE argument_type IN ('AGGMODE' -- GRPBY\n , 'UNIQUE', 'TRUNCSRT' -- SORT\n , 'SCANDIR' -- IXSCAN, TBSCAN\n , 'OUTERJN' -- JOINs\n )\n AND explain_requester = SESSION_USER\n GROUP BY explain_time, operator_id\n\n ) A\n ON ( a.operator_id = tree.operator_id\n AND a.explain_time = tree.explain_time\n )\n ) O\nUNION ALL\nVALUES ('Explain plan (c) 2014-2017 by Markus Winand - NO WARRANTY - V20171102','Z0')\n , ('Modifications by Ember Crooks - NO WARRANTY','Z1')\n , ('http://use-the-index-luke.com/s/last_explained','Z2')\n , ('', 'A')\n , ('', 'Y')\n , ('Predicate Information', 'AA')\nUNION ALL\nSELECT CAST (LPAD(CASE WHEN operator_id = LAG (operator_id)\n OVER (PARTITION BY operator_id\n ORDER BY pred_order\n )\n THEN ''\n ELSE operator_id || ' - '\n END\n , MAX(LENGTH(operator_id )+4) OVER()\n , ' ')\n || how_applied\n || ' ' \n || predicate_text\n AS VARCHAR(100)) \"Predicate Information\"\n , 'P' || LPAD(id_order, 5, '0') || pred_order path\n FROM (SELECT CAST(operator_id AS VARCHAR(254)) operator_id\n , LPAD(trim(how_applied)\n , MAX (LENGTH(TRIM(how_applied)))\n OVER (PARTITION BY operator_id)\n , ' '\n ) how_applied\n -- next: capped to length 80 to avoid\n -- SQL0445W Value \"...\" has been truncated. SQLSTATE=01004\n -- error when long literal values may appear (space padded!)\n , CAST(substr(predicate_text, 1, 80) AS VARCHAR(80)) predicate_text\n , CASE how_applied WHEN 'START' THEN '1'\n WHEN 'STOP' THEN '2'\n WHEN 'SARG' THEN '3'\n ELSE '9'\n END pred_order\n , operator_id id_order\n FROM systools.explain_predicate p\n WHERE explain_time = (SELECT MAX(explain_time)\n FROM systools.explain_operator)\n )\n)\nORDER BY path\n);\n```\n\nTODO:\n\n- Operator ID is currently giving the physical operator ID as stored in the explain tables. It might be more appropriate to display a line number like the Oracle DBMS_XPLAN does so that it is more easy to find a specific ID.\n- Indicate the presences of predicates with a asterisk next to the operation ID like Oracle’s DBMS_PLAN does it. It might also be good to indicate the presences of filter predicates by using another character (e.g. !). Even more sophisticated features would be possible: *START and STOP predicates are present>A START but no STOP predicate is present