Oracle DB SQL Quiz!
I’ve been taking lessons on oracle database and
PL/SQL, trying to get up to speed with the huge number of features. In one of my classes we’ve been going over indexes and have open discussion forums with quizes. Here’s a rundown on one such quiz
Suppose you have created the following tables:
Create table Customer (c_id integer,c_name varchar(40),c_phone char(20),c_address varchar(200),primary key (c_id));Create table Product(p_id integer,p_name varchar(40),description varchar(200),primary key (p_id));Create table Orders(o_id integer,c_id integer,p_id integer,o_date date,price real,primary key (o_id),foreign key (c_id) references customer(c_id),foreign key (p_id) references product(p_id));
What indexes have been created automatically by Oracle once you created these tables?
Although we know Oracle indexes primary keys let’s check with the
all_ind_columns table. In the oracle database this table contains ALL the indexes!
select table_name, column_namefrom all_ind_columnswhere table_name in ('ORDERS', 'PRODUCT', 'CUSTOMER');
Which gives us the names of tables and the column name of their index(s).
It looks like we were correct and the primary keys were indexed!
Given the tables created in question 1, please specify which of the following indexes is the most useful for answering the following query:
select * from orders where o_date < date ‘2004-1-1’ and price = 100
- Index 1: on
- Index 2: on
- Index 3: on
- Index 4: on
Let’s use some logic…
Now that we know indexes are most commonly B+- trees we can apply logic to figure out the most appropriate index. To make the biggest difference in query performance we want to narrow our search down to the smallest set of data. Because there are probably lots of orders on the same date but relatively few with the same total price we should index price first. It is questionable whether we should index the date field at all but having our index secondarily ordered by date should allow the database to further narrow down the search space quickly.
To recap, we want to narrow down the search space quickly so pick
Index 4: on
Given tables created in Question 1, please specify what indexes you want to create to speed up the following SQL queries:
select * from customer where c_name like ‘John%’;
select * from orderswhere o_date <= date ‘2005-1-31’and o_date >= date ‘2005-1-1’and price > 10;
select p_name from product P, orders O where P.p_id = o.P_id;
select sum(price) from orders group by p_id;
- index on