MySql Query Optimization Techniques and Performance Tuning

mysql Query Optimization Techniques

Query Optimization and technique is a feature of RDBMS(Relational Database Management System). The main purpose of Query Optimization is to reduce the usage of CPU resource and execute the Query faster for the User access. 
  
As we know single query can be written in multiple ways, So Optimization technique use the best way which consume lesser system resource and provide faster data access to the users. Query Optimization Make Application response faster and enhance the performance. Now we will go through the query optimization technique step by step.

Avoid so many column in the Table

It's not a good practice of Having large number of column ( >100 ) in single table which  start impacting the query performance and consume the system resource at the time of Query Execution. If you need more column in that case you must break the table based on the logic. Normalization Database Design Technique comes in picture which enhance the system performance.

Avoid Using Select *  

Using Select *  pulls all the column even if it is not not required which consume the resource. Imagine you have  a table which consist more then 100 column and laks or millions of record ( rows ). Querying all the record (Column) using Select * even if all the column is not required is wastage of system resource. If you use actual column what is required for the application instead of all column then your Query execution become faster.

SELECT * FROM `studetnInfo` (This will pull all the column of the studetnInfo Table)

SELECT firstName, lastName, dob, emailId  FROM `studetnInfo`

Above query is there as a example for your reference. What column is needed we must pull that particular column.

Indexing a Column 

We must use DB indexing on the column which is used in SQL Clause such as where, order by and group by etc. Once Indexing is done it will help you in faster data retrieval and also help us in sorting the data.

 Once you create MySql Indexes it will consume space and also slow down the speed of INSERT, UPDATE and DELETE Query Command.

Example : Consider you have a Table named with studentDetail which contain laks of record and indexed on primary key column Named with ID. If we try to access the record using id the query execution will be faster because it will scan minimal row to get the exact data.

SELECT * FROM `studentDetail` WHERE id= 33333

We will use EXPLAIN on the query and try to know some information about the query.

EXPLAIN SELECT * FROM `student_details` WHERE id= 33333

index based query optimization techniques

If we will refer the above image which is the output of EXPLAIN query. In that there is column named with rows which is explaining how many rows are scanned before giving the query output.

Using EXPLAIN query we can get the information about the query and row scanned once the query execution happened.

Avoid Using Correlated Sub-queries 

Basically correlated Sub-queries depend on the outer query or parent query. Sub-query runs for each row-by-row return by the parent or Outer query which slow down the process and decrease the database efficiency.

SELECT Name, dob, (SELECT SchoolName FROM School WHERE ID = Student.schoolid) 
AS SchoolName FROM Student

In the above query each time outer Query will be executed the sub-query will also run row-by-row. which is bad practice of writing queries. We can write the above query in efficient way which is below for your reference.
SELECT st.name, st.dob, sc.SchoolName FROM Student st JOIN School sc ON sc.ID = st.schoolid

Avoid NULL Values in Column

We must avoid NULL Value in our database column because it harm the execution of the query and give unexpected result.

Avoid Storing HTML, XML, JSON or other Mark Up Language

Storing HTML, XML, JSON and other Mark Up Language in database will cost us, these Data is presentation data which must be handled by our Application. We must store data and rest of the presentation data must be handled by Application. Database is there for  Data Operation( Fetching, Inserting, Deleting, Updating ) not for rendering the web page or generating the document.

Use EXPLAIN to analyze your Query

Whenever query is executed the mysql optimizer uses Execution plan. EXPLAIN will give you all the information of execution plan. You can use this EXPLAIN in the beginning of the query. Example is below for your reference.

EXPLAIN SELECT * FROM `student_details` ORDER BY student_name DESC LIMIT 10 

id 1
select_type SIMPLE
table student_details
type all
possible_keys (NULL)
key (NULL)
key_len (NULL)
ref (NULL)
rows 40716 
Extra Using filesort



GK Question On Invention and their Inventor.

Invention
Inventor
Aeroplane
Wright brothers
Air Brake
George Westinghouse
Air Pump
Otto von Guericke
Airship (rigid)
G. Ferdinand Von Zeppelin
Aniline Dyes
Hoffman
Antiseptic Surgery
Lord Joseph Lister
Arc Lamp
C. F. Brush
Archimedean Screw
Archimedies
Atom
Neils Bohr
Atomic Number
Mosley
Atomic Physics
Enrico Fermi
Atomic Structure
Bohr and Rutherford
Atomic Theory
Dalton
Automatic gearbox
Hermann Fottinger
Automobile
Daimler
Automobiles using gasoline
Karl Benz
Avogadro’s Hypothesis
Avogadro
Bacteriology
Robert Koch
Bacteriophage
Max Delbruck
Bakelite
Leo H Baekeland
Balloon
Jacques and Joseph Montgolfier
Ball-Point Pen
John J. Loud
Barometer
Evangelista Torricelli
Behaviorism
B. F. Skinner
Beri – Beri
Eijkman
Bicycle
Kirkpatrick Macmillan
Bicycle Tyre
J.B. Dunlop
Bifocal Lens
Benjamin Franklin
Binomial Nomenclature
Carl Linnaeus
Biogenetic Principle
Ernst Haeckel
Bismuth
Valentine
Blood Circulation
Harvey
Blood Groups
Karl Landsteiner
Bomb
Edward Teller
Boson
S.N.Bose
Boyle’s law
Boyle
Braille
Louis Braille
Breaking up the Nucleus of an atom
Rutherford
Calculating machine
Pascal
Camera
George Eastman
Carburetor
Gottlieb Daimler
Carburettor
Gottlieb Daimler
Cash register
William Burroughs
Cell Doctrine
Rudolf Virchow
Celluloid
A.Parker
Cement
Joseph Aspdin
Cenema
A.L. and J.L. Lumiere
Centrigrade scale
A. Celsius
Chemical Structure
August Kekule
Chemotherapy
Paul Ehrlich
Child Development
Jean Piaget
Chloroform
James Harrison and James Young Simpson
Cholera Bacillus
Robert Koch
Chromosomal Theory of Heredity
Thomas Hunt Morgan
Chronometer
John Harrison
Cine camera
Friese-Greene
Cinematograph
Thomas Alva Edison
Cinematography
Thomas Alva Edison
Circulation of the Blood
William Harvey
Classical Field Theory
Michael Faraday
Clock (machanical)
Hsing and Ling-Tsan
Clock (pendulum)
C. Hugyens
Coloured Photography
Lippman
Computer
Charles Babbage
Continental Drift
Alfred Wegener
Cosmic Rays
R.A.Millikan
Crescograph
J.C.Bose
Crystal Dynamics
C.V.Raman
Cyclotron
Lawrence
D.D.T.
Dr.Paul Muller
Deciphering the genetic code
Dr.Hargobiad Khorana
Deuterium (Heavy Water)
H.C.Urey
Diesel Engine
Rudolf Diesel
Diesel Oil Engine
Rudolf Diesel
Difference engine
Charles Babbage
Electrons
J.J.Thomson
Laws of Planetary Motion
Kepler
North Pole
Robert Peary (1909)
Solar System
Copernicus (1540)
South Pole
Amundson (1912)
Specific Gravity
Archimedes
West Indies
Columbus (1492)
Drinker’s Chamber of Iron Lung
Dr.Philip Drinker
Dynamical theory of Heat
Lord Kelvin
Dynamite
Alfred B. Nobel
Dynamo
Michael Faraday
Effect of Pressure on trough bodies
Meghnad Saha
Eightfold Way
Murray Gell-Mann
Electric Battery
Alessandro Volta
Electric Flat Iron
H. W. Seeley
Electric Furnace
William Siemens
Electric Generator
Michael Faraday
electric guitar
Adolph Rickenbacker
Electric iron
H.W. Seeley
Electric Lamp
Thomas Alva Edison
Electric Measurement
Gauss
Electric Motor (AC)
Nikola Tesla
Electric razor
Jacob Schick
Electrical Waves
Heitz
Electricity
Faraday
Electromagnet
William Sturgeon
Electromagnetic Field
James Clerk Maxwell
Electromagnetic Theory
Maxwell
Electron
Joseph J. Thomson
Electron Theory
Bohr
Electronic Computer
Dr. Alan M. Turing
Elevator
Elisha G. Otis
Energy of the Sun
Hans Bethe
Equal sign (=)?
Robert Recorde
Ethology
Konrad Lorenz
Eugenics
Francis Galton
Evolution
Charles Darwin
Evolution (theory)
Charles Darwin
Evolutionary Theory
Ernst Mayr
Fahrenheit Scale
Fahrenheit
Film & Photographic goods
Kodak
Film (with sound)
Dr. Lee de Forest
Foundations of Biology
Jean Baptiste Lamarck
Foundations of Mathematics
Euclid
Founding of Modern Physiology
Claude Bernard
Founding of Psychology
Wilhelm Wundt
Fountain Pen
Lewis E. Waterman
Fundamental Laws of Electric Attraction
Coulomb
Galvanometer
Andre-Marie Ampere
Gas lighting
William Murdoch
Gasoline engine
Karl Benz
Genetic Code
Frederick Sanger
Geometry
Euclid
Germ Theory of Disease
Louis Pasteur
Glider
Sir George Caley
Gramophone
Thomas Alva Edison
Gun powder
Rogei Bacon
Heavens
William Herschel
Heavy Hydrogen
Urey
Helicopter
Broquett
Heliocentric Universe
Nicolaus Copernicus
Helium Gas
Lockyer
Homoeopathy
Hahnemann
Hovercraft
Christopher Cockerell
Human Sexuality
Alfred Kinsey
Hydrogen
Cavendish
Hydrophobia
Louis Pasteur
I.Q. Test
Alfred Binet
In Number Theory
Ramanujam
Incandescent Bulb
Edison
Induction Coil
Rohm Korff
Induction of Electric Current
Faraday
Insulin
F.Banting
Intelligence test
Binet
Internal Combustion Engine
Otto
Jeans
Levi Strauss
Jet Engine
Sir Frank Whittle
Jet Propulsion
Frank Whittle
Kala-azar Fever
U.N.Brahmachari
Kaleidoscope
David Brewster
Laboratory Gas Burner
Robert Wilhelm Von Bunsen
Laughing Gas
Priestley
Law of Electrolysis
Faraday
Law of gases
Gay Lussac
Laws of Electrical Resistance
Ohm
Laws of Gravitation
Newton
Laws of Heredity
Gregory Mandel
Laws of Inheritance
Gregor Mendel
Laws of Motion
Newton
Laws of Multiple Proportion
Dalton
Laws of Natural Selections
Darwin
Life Boat
Henry Great Head
Lift
E.G. Otis
Lift (Elevators)
Otis
Lightning Conductor
Benjamin Franklin
Line of demarcation (ship)
Plimsoll
Linotype
Mergenthaler
Liquid Oxygen
Dewar
Locomotive
Richard Trevithick
Logarithmic Tables
John Napier
Logarithms
John Napier
Machine Gun
Dr. Richard Gatling
Malarial Parasite
Ronald Ross
Match (safety)
J.E. Lurdstrom
Mathematical Astro Physics
Chandrasekhar
Mathematical Genius
Carl Gauss (Karl Friedrich Gauss)
Mauve dye
Perkin
Measurement of Electrical Energy
Joule, James Prescoft
Mechanical Equivalent of Heat
Joules
Mercury Thermometer
Fahrenheit
Meson
Hideki Yakawa
Microphone
Johann Phillip Reis, Alexander Graham Bell, Elisha Gray, Amos E. Dolbear, and Thomas Edison
Microscopic Anatomy
Marcello Malpighi
Modern Anthropology
Franz Boas
Modern Astronomy
Arthur Eddington
Modern Computer
John von Neumann
Modern Geology
Charles Lyell
Modern Physiology
William Bayliss
Modern Synthesis
Theodosius Dobzhansky
Modern Telescope
Edwin Hubble
Molecular Biology
Francis Crick
Molecular Scattering of light in fluid
Ramanathan
Montessori Method
Maria Montessori
Motion of the Planets
Johannes Kepler
Motor Car (petrol)
Karl Butler
Movie Projector
Thomas Alva Edison
Neon Gas
Ramsay, Travers
Neon-lamp
G. Claude
Neurophysiology
Charles Sherrington
Neutron
Chadwick
New Anatomy
Andreas Vesalius
New Astronomy
Tycho Brahe
New Science
Galileo Galilei
Newtonian Mechanics
Pierre Simon de Laplace
Newtonian Revolution
Isaac Newton
Nuclear Fission
Otto Hahn, Bohr and Fermi
Nylon
Dr. Wallace H. Carothers
Nylon Plastic
Carothers
Organic Chemistry
Emil Fischer
Origin of Species
Charles Darwin
Oxygen
Priestly
Paints
Shalimar
Paper clip
Johann Vaaler
Parking meter
Carlton Mcgee
Penicillin
Alexander Fleming
Periodic Law
Mendeleef
Periodic Table of Elements
Dmitri Mendeleev
Pharmacology
Gertrude Belle Elion
Phonograph
Edison
Photograph
Dauguerre
Photography (paper)
W.H. Fox Tablot
Phototherapy
N.R.Finsen
Pneumatic Tyres
John Boyd Dunlop
Positive Electrons
Anderson
Power Loom
Edmund Cartwright
Powerloom
Cartwright
Principle for lever (S.P.Gravity)
Archimedes
Printing for the Blind
Braille
Printing Press
Johannes Gutenberg
Psycho-analysis
Dr.Sigmund Freud
Psychology of the Unconscious
Sigmund Freud
Quanta
Max Planck
Quantum Cosmology
Stephen Hawking
Quantum Electrodynamics
Richard Feynman
Quantum Mechanics
Max Born
Quantum Theory
Werner Heisenberg
Quantum Theory
Max plank
Raazor (safety)
K.G. Gillete
Rabies Vaccine
Louis Pasteur
Radar
Dr. A.H. Taylor and L.C. Young
Radio
G. Marconi
Radio transmitter
Alexanderson
Radioactive Dating
Willard Libby
Radioactivity
Marie Curie
Radio-activity of Uranium
Henry Becquerel
Radium
Madame Curie
Railway Engine
Stephenson
Raincoat
Charles Macintosh
Raman effect
C.V.Raman
Rare Gas
Cavandish
Rayon
American Viscose Co.
Razor (electric)
Col. J. Schick
Refrigerator
James Harrison, Alexander Catlin
Replacing human heart
Christian Barnard
Revolution in Chemistry
Antoine Laurent Lavoisier
Revolver
Samuel Colt
Rise of German Science
Hermann von Helmholtz
rubber (vulcanized)
Charles Goodyear
Rubber (waterproof)
Charles Macintosh
Safety lamp
Sir Humphrey Davy
Safety Pin
William Hurst
Safety Razor
King C. Gillette
Salk Vaccine
Salk
Saxophone
Antoine Joseph Sax
Scientific astronomy
Hippalus
Scientific Thinking
Lucretius
Scooter
G. Bradshaw
Seismograph
Roberts Mallet
Sewing Machine
Thomas Saint
Sextant
Hadley
Ship (steam)
J.C. Perier
Ship (turbine)
Sir Charles Parsons
Shorthand
Sir Isaac Pitman
Sociobiology
Edward O. Wilson
Soviet Genetics
Trofim Lysenko
Space flying
Braun, Dr.Wernher Von
Spectroscope
Bunsen
Spectroscopy
Gustav Kirchhoff
Spinning frame
Sir Richard Arkwight
Spinning jenny
James Hargreaves
Stainless Steel
Harry Brearley
Steam boat
Fulton
Steam Engine
James Watt
Steam engine (condenser)
James Watt
Steam engine (piston)
Thomas Newcome
Steam Turbine
Parsons
Steel Melting Process
Bessemer
Steel production
Henry Bessemer
Stethoscope
Dr. William Stokes, Rene Laennec
Stress Concept
Hans Selye
Structural Anthropology
Claude Levi-Strauss
Structure of DNA
James Watson
Structure of the Atom
Ernest Rutherford
Submarine
David Bushnell
Sulpha Drugs
Domagk
Superconductivity
Heike Kamerlingh
Symbiosis Theory
Lynn Margulis
Symbol (x)?
William Oughtred
T.N.T.
llly Brandt
Talkies
Lee-de-Frost
Tank
Sir Ernest Swington
Telegraph
Samuel Morse
Telegraphic Code
Samuel Morse
Telephone
Sir Alexander Graham Bell
Telescope
Galileo
Television
Baird
Television (mechanical)
John Logie Baird
Tempo of Evolution
George Gaylord Simpson
Terylene
J. Whinfield and H. Dickson
The long playing microgroove record
Peter Goldmark
Theory of conditioned reflex
Pavlov
Theory of Evolution
Darwin
Theory of Relativity
Einstein
Theory of the Atom
John Dalton
Thermodynamics
Ludwig Boltzmann
Thermometer
Galileo Gallei
Thermos Flasks
Dewar
Tractor
J. Froelich
Transformer
Michael Faraday
Transistor
Bardeen, Shockley, Brattain
Typewriter
C. Sholes
Uranium fusion
Oho Hahn
Uranus (Planet)
Herschel William
Vaccination
Edward Jenner
Valve of radio
Sir J.A. Fleming
Vitamins
Hopkins and Funk
Vitamin A
Elmer V. McCollum and M. Davis
Vitamin B
Elmer V. McCollum
Vitamin B1
Casimir Funk
Vitamin B2
D. T. Smith, E. G. Hendrick
Vitamin Niacin
Conrad Elvehjem
Vitamin Folic acid
Lucy Wills
Vitamin B6
Paul Gyorgy
Vitamin C
James Lind
Vitamin D
Edward Mellanby
Vitamin E
Herbert Evans and Katherine Bishop
Vulcanised Rubber
Charles Goodyear
Washing Soda
Lablanc
Watch
A.L. Breguet
Waterproof Rubber
Charles Macintosh
Wave Mechanics
Erwin Schrodinger
Wave Theory of Light
Christiaan Huygens
Wave/Particle Duality
Louis Victor de Broglie
Wireless Communication
Oliver Lodge
Wireless Telegraphy
Marcony
World Wide Web and Hypertext Markup Language
Tim Berners Lee
X – Rays
Roentgen
X-ray
Wilhelm Reontgen
X-ray Crystallography
Max von Laue
zerox machine
Chester Carlson
Zip fastener
W. L. Judson
Zipper
B. F. Goodrich

Our Feature Post

There is a tree between houses of A and B If the tree leans on As House

    There is a tree between houses of A and B. If the tree There is a tree between houses of A and B. If the tree leans on A’s House, the t...

Our Popular Post