What I have here today is a article for beginners. It will be full of sql query examples. We will start from the most basic ones and continue up. SQL queries will be organized chronologically according to their difficulty. I will add more later on.
SQL knowledge is a must for any IT department nowadays. But these days not only IT guys but also analytics and people working with reports use SQL querying since it is making their work much more effective.
Examples of how can SQL query help you with your work:
- You can load data from a database to Excel and analyze it in contingent table – more in article How to launch SQL query in Excel
- Connect to database in Power BI and create some cool report
- Connect to Excel database via Power Query – Connecting to SQL server in Power Query
- Many other uses
Simplest SQL Query Without Conditions
Query with all columns selection using * without limiting conditions (tutorial on select clause here):
SELECT
*
FROM [AdventureWorksDW2014].[dbo].[udv_SalesByProducts];
SQL Queries With WHERE Condition
Query with limiting condition on year 2010 in where (tutorial on where clause here):
SELECT *
FROM [AdventureWorksDW2014].[dbo].[udv_SalesByProducts]
WHERE [Year] = 2010;
Compound Condition in WHERE
SQL query in which we used many conditions and some basic operators IN, BETWEEN, LIKE and >
SELECT *
FROM [AdventureWorksDW2014].[dbo].[udv_SalesByProducts]
WHERE [Product Subcategory] LIKE ('%bike%')
AND [Year] IN (2013,2014)
AND [Month] BETWEEN 1 AND 6
AND [AverageAmount] > 0;
Selection of First 10 Records Organized in Ascending Order (ASC) Or In Descending Order (DESC) Using ORDER BY
We select 10 (TOP) highest sales in the year 2013 organized in descending order (ORDER BY <Column> DESC)
SELECT TOP 10 *
FROM [AdventureWorksDW2014].[dbo].[udv_SalesByProducts]
WHERE [Year] = 2013
ORDER BY [Amount] DESC;
Aggregating Records Using Functions and Clause GROUP BY
We apply aggregation functions SUM, COUNT, AVG, MAX, MIN on sales through calendar year. Similar sql queries with use of at least 1 aggregation function are usual:
SELECT
[Year],
SUM([Amount]) AS [Amount],
COUNT(*) AS [Sales Count],
AVG([Amount]) AS [Average Amount],
MAX([Amount]) AS [Max Amount]
,
MIN([Amount]) AS [Min_Amount]
FROM [AdventureWorksDW2014].[dbo].[udv_SalesByProducts]
GROUP BY [Year]
ORDER BY [Year] ASC;
Basic Application of HAVING Clause – Condition On Aggregated Data
SQL query on how limit result on records fulfilling the condition after aggregation by using having (we will use base of query as in example 5)
SELECT
[Year],
AVG([Amount]) AS [Average]
FROM [AdventureWorksDW2014].[dbo].[udv_SalesByProducts]
GROUP BY [Year]
HAVING AVG([Amount]) < 5000
ORDER BY [Year] ASC;