0

I have a query as below, and need to create a index for the XYZ field, can we create index in the select statement:

SELECT ABC,
CASE
WHEN B IS NULL AND C IS NOT NULL THEN CONCAT(C,'/',D)
WHEN B IS NOT NULL AND C IS NULL THEN CONCAT(B,'/',D)
WHEN C IS NOT NULL AND C IS NOT NULL THEN CONCAT(B,'/',C,'/',D)
ELSE -1
END AS XYZ,
FROM TABLE_NAME
WHERE ABC=123

Since this XYZ field is not available in 'from table', we unable to create index as usual in create table. Please help with this.

Thanks

4
  • What use is an index on a query result? Is this a part of another query? Commented Dec 14, 2021 at 7:41
  • Create an index by (ABC) or by (ABC, B, C, D). Since this XYZ field is not available in 'from table', we unable to create index as usual in create table. You do NOT need by such index. Or you may add generated column using shown expression and index it. Commented Dec 14, 2021 at 7:44
  • .. WHEN C IS NOT NULL AND C IS NOT NULL .. What's the reason for to check the column twice? Commented Dec 14, 2021 at 7:45
  • Your CASE can be replaced with simple CONCAT_WS('/', B, C, D). Commented Dec 14, 2021 at 7:47

2 Answers 2

1

You could alter your table definition to include XYZ as a generated computed column. Then, add an index on that computed column.

ALTER TABLE TABLE_NAME ADD COLUMN XYZ VARCHAR(50) GENERATED ALWAYS AS
CASE
    WHEN B IS NULL AND C IS NOT NULL THEN CONCAT(C, '/', D)
    WHEN B IS NOT NULL AND C IS NULL THEN CONCAT(B, '/', D)
    WHEN C IS NOT NULL AND C IS NOT NULL THEN CONCAT(B, '/', C, '/', D)
    ELSE '-1' END
STORED;

CREATE INDEX idx_xyz ON TABLE_NAME (XYZ);
Sign up to request clarification or add additional context in comments.

1 Comment

I doubt if that index will help the query.
0

Usually, one looks at the WHERE clause first to decide on an INDEX. In this case, INDEX(ABC) is very likely to be helpful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.