PL/SQL Table Search with and without
Indexing
Step 1: Create Table
CREATE TABLE employees (
emp_id NUMBER PRIMARY KEY,
emp_name VARCHAR2(50),
department VARCHAR2(30),
salary NUMBER
);
Output:
Table EMPLOYEES created.
Step 2: Insert Sample Data
BEGIN
INSERT INTO employees VALUES (101, 'Alice', 'HR', 50000);
INSERT INTO employees VALUES (102, 'Bob', 'IT', 60000);
INSERT INTO employees VALUES (103, 'Charlie', 'Finance', 70000);
INSERT INTO employees VALUES (104, 'David', 'IT', 55000);
INSERT INTO employees VALUES (105, 'Eve', 'HR', 52000);
COMMIT;
END;
/
Output:
PL/SQL procedure successfully completed.
Step 3: Search Operation (Without Index)
Query:
SELECT * FROM employees WHERE department = 'IT';
Query Output:
EMP_ID | EMP_NAME | DEPARTMENT | SALARY
-------+----------+------------+--------
102 | Bob | IT | 60000
104 | David | IT | 55000
Execution Plan (Full Table Scan):
----------------------------------------------------------
| Id | Operation | Name | Rows | Cost (%CPU)|
----------------------------------------------------------
| 0 | SELECT STATEMENT | | 2 | 5 (0)|
|* 1 | TABLE ACCESS FULL| EMPLOYEES | 2 | 5 (0)|
----------------------------------------------------------
Predicate Information (identified by operation id):
1 - filter("DEPARTMENT"='IT')
Statistics:
0 recursive calls
0 db block gets
5 consistent gets
0 physical reads
426 bytes sent via SQL*Net to client
382 bytes received via SQL*Net from client
2 rows processed
Step 4: Create Index
Query:
CREATE INDEX idx_department ON employees(department);
Output:
Index IDX_DEPARTMENT created.
Step 5: Search Operation (With Index)
Query:
SELECT * FROM employees WHERE department = 'IT';
Query Output:
EMP_ID | EMP_NAME | DEPARTMENT | SALARY
-------+----------+------------+--------
102 | Bob | IT | 60000
104 | David | IT | 55000
Execution Plan (Indexed Access):
---------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Cost (%CPU)| Time |
---------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 2 | 2 (0)| 00:00:01 |
|* 1 | TABLE ACCESS BY INDEX ROWID| EMPLOYEES | 2 | 2 (0)| 00:00:01 |
|* 2 | INDEX RANGE SCAN | IDX_DEPARTMENT | 2 | 1 (0)| 00:00:01 |
---------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
1 - filter("DEPARTMENT"='IT')
2 - access("DEPARTMENT"='IT')
Statistics:
0 recursive calls
0 db block gets
3 consistent gets
0 physical reads
2 rows processed
Summary
| Step | Operation | Access Method | I/O Cost | Performance |
|------|--------------------------|------------------------|----------|--------------|
| 3 | Search without index | Full Table Scan | Higher | Slower |
| 5 | Search with index | Index Range Scan + ROWID| Lower | Faster |