SQL Statements
Categories
Actual Order of Execution
The actual order of execution refers to the sequence in which statements must appear in your query for it to retrieve data from your database. Fundamentally, you only require the SELECT and FROM statements to execute a query, the remaining statements are optional. Below is the order in which they need to be written.
SELECT
FROM
JOIN
WHERE
GROUP BY
HAVING
ORDER BY
LIMIT
Logical Order of Execution
The logical order of execution refers to the sequence in which statements are actually run by SQL in the backend. While you will never use this structure, it will help you understand the flow of data manipulation and retrieval operations so that you could optimize your query writing. The only real difference between the actual and logical order of execution is the SELECT Statement. Having the SELECT Statement as the first statement in the actual order is just easier to visual because that is where you state the columns you want retrieve. In the logical order it is not first because we want to establish the datasource we are pulling from first.
FROM
JOIN
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
LIMIT
SELECT Statement
Used to specify the data columns that you want to retrieve. You can either write out each individual column name that you want to pull, separated by commas or you can use the asterisk symbol (*) to pull all the columns available in a table.
Syntax Example
SELECT column1, column2
SELECT *
FROM Statement
Used to specify the data source that you want to pull from. These are the databases and tables that data is retrieved or manipulated from.
Syntax Example
FROM database.table
FROM table
JOIN Statement
Used to combine data from multiple tables based on specified relationships. This allows for facilitating complex data retrieval and analysis.
Syntax Example
JOIN table2 ON table2.column1 = table1,column1
WHERE Statement
Used to indicate specific conditions you want the query to filter for when retrieving data. This ensures that only relevant information is being retrieved or manipulated in the query.
Syntax Example
WHERE column1 > 1
GROUP BY Statement
Used for the grouping of data based on specified columns, this helps with summarization and allows for the application of aggregate functions.
Syntax Example
GROUP BY column1
HAVING Statement
Used to act as a filter for data that is grouped. This allows conditions to be applied to data that has been grouped or aggregated.
Syntax Example
HAVING column1 = 100
ORDER BY Statement
Used to sort the output results of a query based on your specified columns. You can have multiple columns to sort by and can specify if you want it to be ASC (ascending) or DESC (descending). If your order type isn’t specified, the column specified will default to ASC.
Syntax Example
ORDER BY column1 DESC
LIMIT Statement
Used to control the number of rows you want to return from a query.
Syntax Example
LIMIT 5