Database CREATE INDEX and DROP INDEX
What you will learn
- Write
CREATE INDEXandDROP INDEX - Create a unique index
- Use
IF NOT EXISTSandIF EXISTS - See which indexes a table has
- Know which indexes appear automatically
1. The commands
CREATE INDEX index_name ON table_name (column);
CREATE UNIQUE INDEX index_name ON table_name (column);
DROP INDEX index_name;
A common naming habit is idx_<table>_<column>. A unique index is an index that also refuses duplicate values, so it doubles as a rule (lesson 2.6).
2. Try them
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). The indexes you create live in your browser's copy; Reset data removes them. First, which indexes does the table already have?
SELECT type, name FROM sqlite_master WHERE tbl_name = 'customers' ORDER BY type DESC, name;
type name
----- ----------------------------
table customers
index sqlite_autoindex_customers_1
(2 rows)
SELECT type, name FROM sqlite_master WHERE tbl_name = 'branches' ORDER BY type DESC, name;
type name
----- ---------------------------
table branches
index sqlite_autoindex_branches_1
(2 rows)
SELECT type, name FROM sqlite_master WHERE tbl_name = 'students' ORDER BY type DESC, name;
type name
----- ---------------------------
table students
index sqlite_autoindex_students_1
(2 rows)
We created no index, yet one exists: a UNIQUE column made SQLite build an index to enforce it (the name starts with sqlite_autoindex). The INTEGER PRIMARY KEY column made none, because in SQLite it is the row's own id, already used to find rows. Other databases handle this differently: the PostgreSQL documentation says that adding a primary key or a unique constraint automatically creates a unique B-tree index. Check the documentation of the one you use.
Now add our own:
CREATE INDEX idx_customers_city ON customers (city);
CREATE INDEX IF NOT EXISTS idx_customers_city ON customers (city);
CREATE UNIQUE INDEX idx_customers_phone ON customers (phone);
SELECT name, "unique", origin FROM pragma_index_list('customers') ORDER BY name;
SELECT seqno, cid, name FROM pragma_index_info('idx_customers_city');
name unique origin
---------------------------- ------ ------
idx_customers_city 0 c
idx_customers_phone 1 c
sqlite_autoindex_customers_1 1 u
(3 rows)
seqno cid name
----- --- ----
0 5 city
(1 row)
CREATE INDEX idx_customers_city ON customers (city);
CREATE INDEX IF NOT EXISTS idx_customers_city ON customers (city);
CREATE UNIQUE INDEX idx_branches_city ON branches (city);
SELECT name, "unique", origin FROM pragma_index_list('customers') ORDER BY name;
SELECT name, "unique", origin FROM pragma_index_list('branches') ORDER BY name;
SELECT seqno, cid, name FROM pragma_index_info('idx_customers_city');
name unique origin
------------------ ------ ------
idx_customers_city 0 c
(1 row)
name unique origin
--------------------------- ------ ------
idx_branches_city 1 c
sqlite_autoindex_branches_1 1 u
(2 rows)
seqno cid name
----- --- ----
0 3 city
(1 row)
CREATE INDEX idx_courses_department ON courses (department_id);
CREATE INDEX IF NOT EXISTS idx_courses_department ON courses (department_id);
CREATE UNIQUE INDEX idx_courses_title ON courses (title);
SELECT name, "unique", origin FROM pragma_index_list('courses') ORDER BY name;
SELECT seqno, cid, name FROM pragma_index_info('idx_courses_department');
name unique origin
-------------------------- ------ ------
idx_courses_department 0 c
idx_courses_title 1 c
sqlite_autoindex_courses_1 1 u
(3 rows)
seqno cid name
----- --- -------------
0 3 department_id
(1 row)
pragma_index_list shows one row per index: the name, whether it is unique (1) and where it came from (c = created with CREATE INDEX, u = from a UNIQUE constraint). pragma_index_info shows the columns of one index (here a single column). The second CREATE INDEX IF NOT EXISTS with the same name did nothing instead of failing.
The unique index now works as a rule:
INSERT INTO customers (first_name, last_name, email, phone, city, country, joined_on)
SELECT 'Another', 'Person', 'another@example.com', phone, 'Leeds', 'United Kingdom', '2026-01-01'
FROM customers WHERE customer_id = 1;
IntegrityError: UNIQUE constraint failed: customers.phone
INSERT INTO branches (name, city) VALUES ('Second Central', 'Lisbon');
IntegrityError: UNIQUE constraint failed: branches.city
A unique index can only be built if the existing data already obeys it. Customer names repeat in the Bank, so this fails:
CREATE UNIQUE INDEX idx_customers_name ON customers (full_name);
IntegrityError: UNIQUE constraint failed: customers.full_name
INSERT INTO courses (code, title, department_id, credits) VALUES ('NEW101', 'Geometry', 1, 3);
IntegrityError: UNIQUE constraint failed: courses.title
3. Removing an index
DROP INDEX idx_customers_city;
(done)
DROP INDEX idx_customers_city;
OperationalError: no such index: idx_customers_city
DROP INDEX IF EXISTS idx_customers_city;
SELECT name FROM pragma_index_list('customers') ORDER BY name;
name
----------------------------
idx_customers_phone
sqlite_autoindex_customers_1
(2 rows)
DROP INDEX idx_customers_city;
(done)
DROP INDEX idx_customers_city;
OperationalError: no such index: idx_customers_city
DROP INDEX IF EXISTS idx_customers_city;
SELECT name FROM pragma_index_list('customers') ORDER BY name;
name
----
(0 rows)
DROP INDEX idx_courses_department;
(done)
DROP INDEX idx_courses_department;
OperationalError: no such index: idx_courses_department
DROP INDEX IF EXISTS idx_courses_department;
SELECT name FROM pragma_index_list('courses') ORDER BY name;
name
--------------------------
idx_courses_title
sqlite_autoindex_courses_1
(2 rows)
Dropping removes only the index; the table and its rows are untouched. Dropping it twice is an error unless you write IF EXISTS.
Worked example: a library catalogue
A library table books (id, isbn, title, author) should never hold the same ISBN twice, and staff often search by author.
CREATE UNIQUE INDEX idx_books_isbn ON books (isbn); -- a rule and a fast lookup
CREATE INDEX idx_books_author ON books (author); -- fast searches, duplicates allowed
Authors repeat (many books each), so that index is not unique; ISBNs must not, so that one is. The table is made up.
Other databases. The simple forms above are written the same way in the major SQL databases, but each adds its own options and has its own tools for listing indexes (PRAGMA is SQLite's). Check your database's documentation for those.
Common mistakes
- Creating a duplicate index on the same column under another name; it costs space and gives nothing.
- Making an index unique when the data repeats (such as
city): the command fails or later inserts do. - Dropping an index and thinking data is lost. Only the index goes.
- Forgetting that
UNIQUEconstraints already create an index in SQLite.
Key takeaways
CREATE INDEX name ON table (column)builds an index;DROP INDEX nameremoves it.CREATE UNIQUE INDEXalso refuses duplicates.IF NOT EXISTSandIF EXISTSavoid errors when re-running scripts.PRAGMA index_list(table)lists a table's indexes in SQLite.UNIQUEconstraints create an index automatically.
Practice
1. Write the command that creates an index named idx_orders_city on orders (city).
Show answer
CREATE INDEX idx_orders_city ON orders (city);
2. What does the u in the PRAGMA index_list output mean?
Show answer
The index was created by a UNIQUE constraint rather than by CREATE INDEX.
3. Why did the second insert of Rina fail?
Show answer
A unique index on name already held Rina, so a duplicate was refused.
4. Does DROP INDEX delete rows from the table?
Show answer
No. Only the index is removed.
5. How can you make a script safe to run twice?
Show answer
Use CREATE INDEX IF NOT EXISTS and DROP INDEX IF EXISTS.
6. Should email in a users table have a unique index? Why?
Show answer
Usually yes: each person should have a distinct email, and logins look people up by it, so you get the rule and the fast lookup together.