I have a database with 300,000,000 records,
To insert new records, I want to check whether the record is already in the database or not,
I use the following query to confirm:
SELECT student_code
FROM public.student_tbl
WHERE class_type='high_school' AND class_register='true' AND (student_code='F40101197X0' OR student_code='F40101197X1' OR student_code='F40101197X2');
It will take 2 minutes to complete, it takes quite a while.
Therefore, I want to save the time to check data is already in the database or not by using the following query:
CREATE INDEX student_tbl_class_register_index
ON public.student_tbl(class_register)
WHERE class_register IS TRUE;
UPDATE1:
・[student_id] to [student_code]
・class_type, student_code are the values that can be changed, while class_register is deciding whether to insert new records or not, if class_register='false' then can insert new records.
UPDATE2:
As the answer of Gordon Linoff, Laurenz Albe, ex4 suggested (thanks for your support),
I update as below:
Query check whether the data already exists in the database or not:
SELECT student_code
FROM public.student_tbl
WHERE class_type = 'high_school' AND
class_register = 'true' AND
student_code IN ('F40101197X0', 'F40101197X1', 'F40101197X2');
Query creates the index:
CREATE UNIQUE INDEX CONCURRENTLY studenttbl_classtype_studentcode_idx
ON public.student_tbl (class_type, student_code)
WHERE class_register = 'true';
ALTER TABLE public.student_tbl
ADD CONSTRAINT studenttbl_classtype_studentcode_idx
UNIQUE USING INDEX studenttbl_classtype_studentcode_idx;
Is it okay with the CREATE INDEX statement above?
Or how can I do well in this case, please tell me!
Any hint will be great.
Thanks!