Categories: MySQL

Subquery in MySQL

Share

Subquery in MySQL means Query inside another query on SELECT, INSERT, UPDATE or DELETE.

A subquery must be enclosed with parentheses and can be used anywhere in an expression.

The main advantages of subqueries is that it allow queries that are structured so that, it is possible to isolate each part of the statement and they provide an alternative ways to perform the operations that would otherwise require the complex joins and unions.

Most of the people find subqueries that are more readable than complex joins or unions.

Example of Subquery:

SELECT * from users WHERE user_country IN (SELECT country_id FROM countries);

Few things you need to remember:

  • Never use IN with a subquery as this is slow sometimes.
  • Only ever use IN with a fixed list of values.

Read Also: MySQL Query Functions

More tips:

  • If you want to make your query more faster, don’t run a SELECT *. Only select the fields that you really need.
  • Remember to make an index on relevant_field to speed up the equi join.
  • Make sure to group by on a primary key.
  • If you are uning InnoDB storage engine and you only select indexed fields then MySQL will resolve the query using only the indexes, speeding things way up.

Recent Posts

The Sharp-Looking Guy: 5 Essential Tips for Men to Become Sharp

We've gotten so used to seeing men streetwear joggers, ripped jeans, and sleeveless shirts. Hair…

1 day ago

How to Use Your Wedding Jewellery In Unique Ways At Festivals

When it comes to festivals, the options for wedding jewellery are endless. You can go…

1 day ago

5 Tips On Window Cleaning

Whether it concerns your home or an office building, the state of a property’s windows…

1 day ago

Sustainable Business Practices: A Win-Win Strategy

You know that running an environmentally sustainable business is the right thing to do. But…

1 day ago

Unlock Growth – Guide to Online Financing and Business Loans for Entrepreneurs

If you are in a financial crisis , or need to start a new business…

1 day ago

7 Key Factors That Help In Selecting the Best Fleet Management Software

To realize the strategic advantage from the fleet management system (FMS) and differentiate the business…

1 day ago