Special cases: unique keys with NULL, JSON, maps, and long values
A unique index lets NULLs repeat. A JSON key needs a generated column or a GIN index. Two ranges need a spatial index. A long value needs a prefix or a hash.
More on Indexes: special kinds and practice
Keep learning
Overview
Duplicate NULLs in a UNIQUE index Two rows that look identical are both accepted Partial unique index, NULLS NOT DISTINCT, or a unique index on an expression that replaces NULL. A key inside a JSON document A plain index on the JSON column is never used MySQL: generated column plus index. PostgreSQL: expression index or GIN on jsonb. A value inside a JSON array Containment queries scan the table MySQL: multi-valued index and MEMBER OF. PostgreSQL: GIN. Two ranges, such as longitude and latitude Only the first range narrows the scan A spatial index (GiST with PostGIS, or SPATIAL in MySQL). A long text value The index exceeds the size limit, or entries are fat A prefix index or a hash of the value, and re-check the full value. chapters · indexes Special cases: unique keys with NULL, JSON, maps, and long values A few indexing problems do not fit the left-to-right rule: a unique key that NULL slips past, a key buried in a JSON document, a search on two ranges at once, and a value too long to index. Each has a standard fix. The syntax differs by database, so each fix shows MySQL and PostgreSQL side by side.
1. A unique index and NULL
A NULL is not equal to another NULL, so a unique index does not see two NULLs as a duplicate. A shop wants each customer to have only one open order for a scarce product. The column shipment_id is NULL while the order is open and is filled in when it ships, so the developer adds UNIQUE (customer_id, shipment_id). It does not work: customer 17 can have two open orders, because both rows hold (17, NULL). Does the unique index accept a second (17, NULL)? MySQL (InnoDB) Yes. NULLs never collide. Yes by default. Version 15 added NULLS NOT DISTINCT to change it. SQL Server No. A unique index treats NULLs as equal, so it allows only one. Check your database before relying on either behaviour. There are three ways to get the rule you wanted: 1. Index only the open rows PostgreSQL partial index, SQL Server filtered index. The cleanest, and the index is small. MySQL has no partial index. 2. Tell the index NULLs are equal PostgreSQL 15 and later. Part of the SQL standard, but not yet in MySQL. The third way works everywhere that has expression indexes: replace NULL with a value that cannot occur. The expression hides shipment_id from other queries. A query that filters on shipment_id cannot use this index and needs its own, as the chapter on functions around a column explains. The same warning applies to a plain unique index with nullable columns: always ask what it does with NULL.
2. Keys and arrays inside JSON
Every major database has a JSON type, and indexing it is still awkward. An index on the JSON column itself only finds rows whose whole document is identical, which nobody searches for. To search by a value inside it, you index that value. Pick the index by the question You want to find PostgreSQL (jsonb) One known key, equality Generated column on the key, then a normal index Expression index on the key Any key, or a document that contains something No equivalent. Index the keys you need one by one. One GIN index covers the whole document A value inside an array Multi-valued index (8.0.17+) GIN index on the array
MySQL: a generated column
The optimizer matches the expression in the query to the generated column, so the query does not need to change. You can also index the expression directly with a functional index, but MySQL then needs a cast to a string type with an explicit collation, and the query must match it, so check the plan with EXPLAIN. ! JSON text compares case-sensitively in MySQL Text extracted with ->> carries the utf8mb4_bin collation. Searching for Admin@example.com will not find admin@example.com, unlike a normal VARCHAR column. Lowercase the value when you store it.
Arrays inside JSON
A product that belongs to several categories, stored as a JSON array of category ids: A MySQL multi-valued index holds one type of scalar, for example integers (UNSIGNED ARRAY) or strings (CHAR(n) ARRAY), which is why the example uses category ids instead of names. → If you filter on a key in every request, give it a real column A real column has statistics, constraints, and a plain index. Keep JSON for the keys that vary from row to row and that you rarely filter on.
3. Searching a map: two ranges at once
The equality on type goes first, which helps. After that only the longitude range narrows the scan. Every restaurant in that vertical strip of the map is read, and the latitude is tested on each one. The strip reaches from the north pole to the south, so on a table of the whole country it is a large slice for a small answer. Adding more columns to the index does not fix it, because there is nothing after the first range that can narrow the scan. The real fix is a spatial index. It stores points in a structure that is organised in two dimensions at once, so a box touches only the entries inside it. PostgreSQL (PostGIS) GiST needs the btree_gist extension to include the plain type column. SRID 4326 is the GPS coordinate system. A spatial index covers one column, so type cannot be put in front of it. It is tested on the rows the box finds.
4. Values too long to index
An index entry has a size limit: 3,072 bytes in an InnoDB table with the default row format, and about 2.7 KB in a PostgreSQL B-tree, where one entry must fit well within a page. Past the limit the database refuses to create the index, or refuses an insert with a long value. Even below the limit, fat entries lower the fan-out and the index grows (the height chapter). Two ways to shrink the entry:
A prefix of the value
The index finds every row that starts with the same 20 characters, and the full comparison throws away the false matches after the row is read. Too short a prefix means many false matches. Too long a prefix wastes the space you were saving. Choose the length by counting distinct prefixes against distinct values, as in the covering chapter, which also explains why a prefix index can never cover a query.
A hash of the value
A hash is a short fixed-size stand-in. Collisions are so rare that almost no false rows are read. Store it as binary, not as hex text, which would double the size.
Recap
NULL is not equal to NULL, so a unique index may accept duplicates. Use a partial index, NULLS NOT DISTINCT, or an expression that replaces NULL, and know what your database does by default. Index a value inside JSON by pulling it out: a generated column in MySQL, an expression index or GIN in PostgreSQL. For arrays, use a multi-valued index in MySQL and GIN in PostgreSQL. Text pulled out of JSON in MySQL compares case-sensitively. A box on a map is two ranges, and a normal index can narrow only one. Use a spatial index, and put the low value first in each range. Shrink a long value with a prefix or a hash, and always compare the full value as well.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.