Skip to content

Commit db618e8

Browse files
committed
Add SQL conditional examples documentation
0 parents  commit db618e8

10 files changed

+786
-0
lines changed

.gitignore

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Database files
2+
*.mdf
3+
*.ldf
4+
*.ndf
5+
6+
# IDE specific files
7+
.vscode/
8+
.idea/
9+
*.swp
10+
*.swo
11+
.DS_Store
12+
13+
# Backup files
14+
*.bak
15+
*.backup
16+
*.tmp
17+
18+
# Environment specific
19+
.env
20+
.env.local
21+
*.config

CONTRIBUTING.md

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Contributing to SQL Conditional Examples
2+
3+
We love your input! We want to make contributing to SQL Conditional Examples as easy and transparent as possible, whether it's:
4+
5+
- Reporting a bug
6+
- Discussing the current state of the code
7+
- Submitting a fix
8+
- Proposing new features
9+
- Becoming a maintainer
10+
11+
## We Develop with Github
12+
We use Github to host code, to track issues and feature requests, as well as accept pull requests.
13+
14+
## We Use [Github Flow](https://guides.github.com/introduction/flow/index.html)
15+
Pull requests are the best way to propose changes to the codebase. We actively welcome your pull requests:
16+
17+
1. Fork the repo and create your branch from `main`.
18+
2. If you've added code that should be tested, add tests.
19+
3. If you've changed APIs, update the documentation.
20+
4. Ensure the test suite passes.
21+
5. Make sure your code follows our coding standards.
22+
6. Issue that pull request!
23+
24+
## Any contributions you make will be under the MIT Software License
25+
In short, when you submit code changes, your submissions are understood to be under the same [MIT License](http://choosealicense.com/licenses/mit/) that covers the project. Feel free to contact the maintainers if that's a concern.
26+
27+
## Report bugs using Github's [issue tracker](https://github.com/yourusername/sql-examples/issues)
28+
We use GitHub issues to track public bugs. Report a bug by [opening a new issue](https://github.com/yourusername/sql-examples/issues/new); it's that easy!
29+
30+
## Write bug reports with detail, background, and sample code
31+
32+
**Great Bug Reports** tend to have:
33+
34+
- A quick summary and/or background
35+
- Steps to reproduce
36+
- Be specific!
37+
- Give sample code if you can.
38+
- What you expected would happen
39+
- What actually happens
40+
- Notes (possibly including why you think this might be happening, or stuff you tried that didn't work)
41+
42+
## License
43+
By contributing, you agree that your contributions will be licensed under its MIT License.

LICENSE

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2024 SQL Examples
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# SQL Conditional Expressions and Examples
2+
3+
This repository contains comprehensive examples of SQL conditional expressions, functions, and their practical applications. The examples cover various SQL flavors including SQL Server, Oracle, MySQL, and PostgreSQL.
4+
5+
## Contents
6+
7+
1. [Basic Conditional Expressions](comprehensive_conditional_examples.sql)
8+
- CASE Statements
9+
- IIF Functions
10+
- NULL Handling
11+
- Conditional Aggregates
12+
13+
2. [Case Statement Examples](case_statement_examples.sql)
14+
- Simple CASE
15+
- Searched CASE
16+
- CASE in UPDATE statements
17+
- CASE with GROUP BY
18+
19+
3. [IF Statement Alternatives](if_statement_examples.sql)
20+
- IIF usage
21+
- CASE alternatives
22+
- Complex conditions
23+
24+
4. [Conditional Column Examples](conditional_column_examples.sql)
25+
- Dynamic columns
26+
- Calculated fields
27+
- Date-based conditions
28+
29+
## Database Compatibility
30+
31+
- **SQL Server Specific**:
32+
- IIF()
33+
- ISNULL()
34+
- TRY_CONVERT()
35+
- CHOOSE()
36+
37+
- **Oracle Specific**:
38+
- NVL()
39+
- DECODE()
40+
41+
- **Universal Functions**:
42+
- CASE
43+
- COALESCE
44+
- NULLIF
45+
46+
## Common Use Cases
47+
48+
1. **Data Categorization**
49+
- Price ranges
50+
- Age groups
51+
- Performance tiers
52+
53+
2. **NULL Handling**
54+
- Default values
55+
- Data cleaning
56+
- Conditional aggregation
57+
58+
3. **Business Logic**
59+
- Discount calculations
60+
- Commission structures
61+
- Status updates
62+
63+
4. **Reporting**
64+
- KPI calculations
65+
- Performance metrics
66+
- Dynamic grouping
67+
68+
## Best Practices
69+
70+
1. Always include an ELSE clause in CASE statements
71+
2. Use appropriate NULL handling functions
72+
3. Consider performance implications with complex conditions
73+
4. Keep conditions mutually exclusive
74+
5. Use comments to explain complex logic
75+
76+
## Performance Considerations
77+
78+
- CASE statements are generally more performant than multiple IF conditions
79+
- Use appropriate indexes for columns used in conditions
80+
- Avoid unnecessary CASE expressions in WHERE clauses
81+
- Consider materialized views for complex conditional calculations
82+
83+
## Examples
84+
85+
Check the SQL files for detailed examples and implementations.

advanced_conditional_examples.sql

+204
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
/*
2+
Advanced SQL Conditional Examples
3+
-------------------------------
4+
This file contains advanced examples of SQL conditional expressions and their applications
5+
in real-world scenarios. Each section demonstrates different aspects of conditional logic
6+
in SQL.
7+
*/
8+
9+
-- 1. Advanced Data Classification
10+
-- Example: Customer Segmentation based on multiple factors
11+
SELECT
12+
customer_id,
13+
customer_name,
14+
total_purchases,
15+
avg_order_value,
16+
CASE
17+
WHEN total_purchases > 100 AND avg_order_value > 1000 THEN 'Platinum'
18+
WHEN total_purchases > 50 AND avg_order_value > 500 THEN 'Gold'
19+
WHEN total_purchases > 20 OR avg_order_value > 250 THEN 'Silver'
20+
ELSE 'Bronze'
21+
END as customer_tier,
22+
23+
-- Loyalty Score Calculation
24+
CASE
25+
WHEN months_active > 24 THEN 3
26+
WHEN months_active > 12 THEN 2
27+
ELSE 1
28+
END *
29+
CASE
30+
WHEN return_rate < 0.05 THEN 3
31+
WHEN return_rate < 0.10 THEN 2
32+
ELSE 1
33+
END as loyalty_score;
34+
35+
-- 2. Dynamic Date Handling
36+
SELECT
37+
event_date,
38+
event_name,
39+
-- Fiscal Quarter Calculation
40+
CASE
41+
WHEN MONTH(event_date) BETWEEN 1 AND 3 THEN 'Q1'
42+
WHEN MONTH(event_date) BETWEEN 4 AND 6 THEN 'Q2'
43+
WHEN MONTH(event_date) BETWEEN 7 AND 9 THEN 'Q3'
44+
ELSE 'Q4'
45+
END + '-' + CAST(YEAR(event_date) AS VARCHAR) as fiscal_quarter,
46+
47+
-- Season Classification
48+
CASE
49+
WHEN MONTH(event_date) IN (12, 1, 2) THEN 'Winter'
50+
WHEN MONTH(event_date) IN (3, 4, 5) THEN 'Spring'
51+
WHEN MONTH(event_date) IN (6, 7, 8) THEN 'Summer'
52+
ELSE 'Fall'
53+
END as season;
54+
55+
-- 3. Advanced Statistical Calculations
56+
SELECT
57+
department,
58+
AVG(salary) as avg_salary,
59+
-- Salary Variance Categories
60+
CASE
61+
WHEN STDEV(salary) > 10000 THEN 'High Variance'
62+
WHEN STDEV(salary) > 5000 THEN 'Medium Variance'
63+
ELSE 'Low Variance'
64+
END as salary_variance,
65+
66+
-- Percentile-based Categories
67+
CASE
68+
WHEN salary > PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY salary)
69+
OVER (PARTITION BY department) THEN 'Top 25%'
70+
WHEN salary > PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary)
71+
OVER (PARTITION BY department) THEN 'Top 50%'
72+
ELSE 'Bottom 50%'
73+
END as salary_percentile;
74+
75+
-- 4. Complex Business Rules
76+
-- Example: Insurance Premium Calculation
77+
SELECT
78+
policy_id,
79+
customer_age,
80+
coverage_amount,
81+
-- Base Premium Calculation
82+
CASE
83+
WHEN customer_age < 25 THEN coverage_amount * 0.05
84+
WHEN customer_age < 35 THEN coverage_amount * 0.04
85+
WHEN customer_age < 45 THEN coverage_amount * 0.035
86+
WHEN customer_age < 55 THEN coverage_amount * 0.045
87+
ELSE coverage_amount * 0.055
88+
END +
89+
-- Risk Adjustment
90+
CASE risk_factor
91+
WHEN 'Low' THEN -500
92+
WHEN 'Medium' THEN 0
93+
WHEN 'High' THEN 1000
94+
ELSE 0
95+
END as calculated_premium;
96+
97+
-- 5. Advanced String Manipulation
98+
SELECT
99+
email,
100+
-- Email Provider Classification
101+
CASE
102+
WHEN LOWER(email) LIKE '%@gmail.com' THEN 'Google'
103+
WHEN LOWER(email) LIKE '%@outlook.com' OR
104+
LOWER(email) LIKE '%@hotmail.com' OR
105+
LOWER(email) LIKE '%@live.com' THEN 'Microsoft'
106+
WHEN LOWER(email) LIKE '%@yahoo.com' THEN 'Yahoo'
107+
ELSE 'Other'
108+
END as email_provider,
109+
110+
-- Phone Number Formatting
111+
CASE
112+
WHEN LEN(phone) = 10 THEN
113+
'(' + SUBSTRING(phone, 1, 3) + ') ' +
114+
SUBSTRING(phone, 4, 3) + '-' +
115+
SUBSTRING(phone, 7, 4)
116+
ELSE phone
117+
END as formatted_phone;
118+
119+
-- 6. Hierarchical Data Processing
120+
WITH EmployeeHierarchy AS (
121+
SELECT
122+
employee_id,
123+
manager_id,
124+
salary,
125+
1 as level
126+
FROM employees
127+
WHERE manager_id IS NULL
128+
129+
UNION ALL
130+
131+
SELECT
132+
e.employee_id,
133+
e.manager_id,
134+
e.salary,
135+
eh.level + 1
136+
FROM employees e
137+
INNER JOIN EmployeeHierarchy eh
138+
ON e.manager_id = eh.employee_id
139+
)
140+
SELECT
141+
employee_id,
142+
level,
143+
CASE
144+
WHEN level = 1 THEN 'CEO'
145+
WHEN level = 2 THEN 'VP'
146+
WHEN level = 3 THEN 'Director'
147+
WHEN level = 4 THEN 'Manager'
148+
ELSE 'Staff'
149+
END as position_level;
150+
151+
-- 7. Dynamic Pivot Tables
152+
DECLARE @columns NVARCHAR(MAX);
153+
DECLARE @sql NVARCHAR(MAX);
154+
155+
SELECT @columns = STRING_AGG(
156+
QUOTENAME(category),
157+
',')
158+
FROM (SELECT DISTINCT category FROM products) as categories;
159+
160+
SET @sql = N'
161+
SELECT *
162+
FROM (
163+
SELECT
164+
department,
165+
category,
166+
CASE
167+
WHEN units_sold > 1000 THEN ''High''
168+
WHEN units_sold > 500 THEN ''Medium''
169+
ELSE ''Low''
170+
END as sales_volume
171+
FROM sales
172+
) as SourceTable
173+
PIVOT (
174+
COUNT(sales_volume)
175+
FOR category IN (' + @columns + ')
176+
) as PivotTable;
177+
';
178+
179+
EXEC sp_executesql @sql;
180+
181+
-- 8. Geographic Data Processing
182+
SELECT
183+
location_id,
184+
latitude,
185+
longitude,
186+
-- Hemisphere Classification
187+
CASE
188+
WHEN latitude > 0 AND longitude > 0 THEN 'Northeast'
189+
WHEN latitude > 0 AND longitude < 0 THEN 'Northwest'
190+
WHEN latitude < 0 AND longitude > 0 THEN 'Southeast'
191+
ELSE 'Southwest'
192+
END as hemisphere,
193+
194+
-- Time Zone Approximation
195+
CASE
196+
WHEN longitude BETWEEN -180 AND -135 THEN 'GMT-10'
197+
WHEN longitude BETWEEN -134 AND -90 THEN 'GMT-8'
198+
WHEN longitude BETWEEN -89 AND -45 THEN 'GMT-5'
199+
WHEN longitude BETWEEN -44 AND 0 THEN 'GMT'
200+
WHEN longitude BETWEEN 1 AND 45 THEN 'GMT+2'
201+
WHEN longitude BETWEEN 46 AND 90 THEN 'GMT+5'
202+
WHEN longitude BETWEEN 91 AND 135 THEN 'GMT+8'
203+
ELSE 'GMT+10'
204+
END as approximate_timezone;

0 commit comments

Comments
 (0)