In previous articles we discussed about the basic query structure to find any information in database. furthermore in this article we will discuss about clause order in a query.
Each query we write to find data in a database. Then on that query we apply different clauses and conditions to filter out the specific data as per requirement. Every clause we apply execute sequentially. Therefore it is important to understand the order of execution of clauses. Syntax for a complete SELECT query as below:
Simple Clause Order in Query
SELECT DISTINCT col-name, AGG_FUNC(col-name_or_expression), … FROM table-name-1 JOIN table-name-2 ON table-name-1.col-name = table-name-2.col-name WHERE (condition) GROUP BY col-name HAVING col-name = “specific-col-member” ORDER BY col-name ASC/DESC LIMIT number OFFSET number;
Now, let’s talk a little more about the use of these clauses and keywords in the query.
FROM, JOIN – These are the most important clauses in sql query. because they are required almost in every query.
WHERE (condition) – next come the WHERE clause, which includes constraints on individual set of rows.
GROUP BY – After WHERE clause we use GROUP BY clause. Because it groups rows based on common values in the column after WHERE constraints.
HAVING – Having clause is useful when using aggregate functions. We use HAVING after GROUP BY clause for it returns very specific value from the query.
DISTINCT – Distinct keyword discards duplicate values from the rows for an specific column.
ORDER BY – We use order by clause to sort rows in specific order.
LIMIT, and OFFSET – LIMIT restricts the number of returns, and OFFSET discards the number of rows in return.
This is important to remember that every query we apply doesn’t need to have all of these components. But we can use any of them or all of them in our query as per requirement.
More articles on SQL, coming soon, here »
Find original resources here »