Reputation: 5
What problems does the statement shown here present? What could be changed that would allow a more efficient statement than this one? I was asked in an interview.
SELECT
DATE, location, USER_ID
FROM
customers
WHERE
UPPER(name) = 'SATISH';
Upvotes: 0
Views: 62
Reputation: 4924
Since you use a function on the column, an index on name would probably not been used. Many DB-System support case-insensitive indexes/search anyway, so the upper is not needed.
In other cases it could be useful to store the name in uppercase(maybe an extra column). Then the upper on the search-value is needed, too.
Upvotes: 1
Reputation: 1270463
This is your query:
SELECT DATE, location, USER_ID
FROM customers
WHERE UPPER(name) = 'SATISH';
Making this query more efficient is basically about using indexes.
First, many databases are by default case-insensitive. So this query could be equivalent to:
WHERE name = 'SATISH'
This version, however, can take advantage of an index on users(name)
. Even a case-insensitive collation will probably not use an index with the UPPER()
function.
If your database is case-sensitive, three options come to mind:
Not all databases support all three methods.
You can enforce the first with a check
constraint:
check chk_user_name_uppercase (name = upper(name));
You can implement the second in some databases as:
create index idx_user_uname on user(upper(name));
You can implement the third as:
alter table user add name_upper as (upper(name));
create index idx_user_name_upper on user(name_upper);
Then the where
clause would look like:
where name_upper = 'SATISH'
Upvotes: 2