MySQL: How to optimize this QUERY? Calculating SUM by year(date) -


i have query calculating sums of values per every year based on date.

it works, heavy, takes minute 2 minutes running on 10k records

is there way optimize this, or write in more efficient way?

"select departments sum(case when year(employment_date) = '1990' 1 else  0 end) '1990',"     + "sum(case when year(employment_date) = '2010' 1 else  0 end) '2010',"     + "sum(case when year(employment_date) = '2011' 1 else  0 end) '2011',"     + "sum(case when year(employment_date) = '2012' 1 else  0 end) '2012',"     + "sum(case when year(employment_date) = '2013' 1 else  0 end) '2013',"     + "sum(case when year(employment_date) = '2014' 1 else  0 end) '2014',"     + "sum(case when year(employment_date) = '2015' 1 else  0 end) '2015',"      + "sum(case when year(employment_date) = '2016' 1 else  0 end) '2016',"      + " count(departments.dept_id) total "     + "from employees inner join departments on employees.employee_id=departments.employee_id , departments.dept_id = ?";   sample resuts      |departments  | total | 2010 | 2011 | 2012 | 2013 | 2014 | 2015 | 2016 |     |data systems | 100   | 30   | 10   | 5    | 15   | 20   | 12   | 8    |     |social ssmp  | 70    | 10   | 10   | 15   | 15   | 4    | 6    | 10   | 

in mysql, 1 of best way improve query performance indexing.the whole point of having index speed search queries cutting down number of records/rows in table need examined.

create index emp_index on employee (employment_date, employee_id); create index dept_index on departments(departments , dept_id );

please refer link more info.

just quick suggestion.. indexing costs additional writes , storage space, if application requires more insert/update operation, might want use tables without indexes, if requires more data retrieval operations, should go indexed table.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -