Add More Data and Analyze Sorting
Let's insert more data to make the query plan analysis more meaningful. Insert the following data into the employees table:
INSERT INTO employees (first_name, last_name, email, department) VALUES
('Alice', 'Johnson', 'alice.johnson@example.com', 'HR'),
('Bob', 'Williams', 'bob.williams@example.com', 'Finance'),
('Charlie', 'Brown', 'charlie.brown@example.com', 'IT'),
('David', 'Miller', 'david.miller@example.com', 'Sales'),
('Eve', 'Wilson', 'eve.wilson@example.com', 'Marketing'),
('John', 'Taylor', 'john.taylor@example.com', 'Engineering'),
('Jane', 'Anderson', 'jane.anderson@example.com', 'HR'),
('Robert', 'Thomas', 'robert.thomas@example.com', 'Finance'),
('Emily', 'Jackson', 'emily.jackson@example.com', 'IT'),
('Michael', 'White', 'michael.white@example.com', 'Sales');
Now, let's analyze a more complex query that involves sorting. Suppose you want to find all employees in the 'Sales' department and sort them by last name. You can use the following query:
SELECT * FROM employees WHERE department = 'Sales' ORDER BY last_name;
Analyze the query plan:
EXPLAIN QUERY PLAN SELECT * FROM employees WHERE department = 'Sales' ORDER BY last_name;
The output might look like this:
QUERY PLAN
`--SCAN employees USING INDEX idx_lastname
In this case, SQLite is performing a full table scan and then sorting the results.
Let's create an index on the department column:
CREATE INDEX idx_department ON employees (department);
Now, analyze the query plan again:
EXPLAIN QUERY PLAN SELECT * FROM employees WHERE department = 'Sales' ORDER BY last_name;
The output might change to:
QUERY PLAN
|--SEARCH employees USING INDEX idx_department (department=?)
`--USE TEMP B-TREE FOR ORDER BY
Now SQLite is using the idx_department index to find the employees in the 'Sales' department, but it still needs to sort the results.