// SQL snippet

Find tables without any index

Every lookup on an unindexed table is a full scan. Small lookup tables get away with it; anything that grows does not. This query lists tables with no index of any kind.

Main statement
MySQL
También cubre
PostgreSQL SQLite

The task

Lookups against one table get slower as rows pile up and you suspect nothing indexes it. Before adding another index somewhere else, find which tables carry no index at all.

The snippet

Written for MySQL. Versions for PostgreSQL and SQLite are under Variations.

MySQL
SELECT t.table_schema, t.table_name,
       t.table_rows AS row_estimate
FROM information_schema.tables t
WHERE t.table_type = 'BASE TABLE'
  AND t.table_schema = 'mydb'
  AND NOT EXISTS (
        SELECT 1 FROM information_schema.statistics s
        WHERE s.table_schema = t.table_schema
          AND s.table_name = t.table_name)
ORDER BY t.table_rows DESC;

Cómo funciona

In MySQL every index, including the primary key, appears in information_schema.statistics, so a table with zero rows there has no index at all. The NOT EXISTS filter keeps only such tables, and the row estimate sorts the largest offenders first. InnoDB still clusters such a table on a hidden 6-byte row ID, but nothing can search on that ID, so every lookup scans the whole table.

Variations

PostgreSQL

PostgreSQL
SELECT n.nspname AS schema_name, c.relname AS table_name,
       c.reltuples::bigint AS row_estimate
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
  AND n.nspname NOT IN ('pg_catalog', 'information_schema')
  AND NOT EXISTS (
        SELECT 1 FROM pg_index i
        WHERE i.indrelid = c.oid)
ORDER BY c.reltuples DESC;

SQLite

SQLite
-- an INTEGER PRIMARY KEY is the rowid and has no entry in
-- index_list, hence the second check
SELECT m.name AS table_name
FROM sqlite_master m
WHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%'
  AND NOT EXISTS (
        SELECT 1 FROM pragma_index_list(m.name) il)
  AND NOT EXISTS (
        SELECT 1 FROM pragma_table_info(m.name) ti WHERE ti.pk > 0);

Questions that come up

Should every table have an index, then?

Not every table, but every table you search. A bridge table with three rows and a monthly truncate can stay index-free; a multi-million-row fact table without any index is a full scan waiting to happen.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.