Applying Functions in SQL Queries:

How to Know Which Function to Use:

You can use these functions to transform data, calculate values, or extract specific information in your queries.

Let’s go through some examples that clarify how to use different functions in SQL.

Example 1: String Functions - Formatting Names

Let’s say you want to format employee names, ensuring the first letter of their first and last names is 


SELECT 

    CONCAT(UPPER(SUBSTRING(e.first_name, 1, 1)), LOWER(SUBSTRING(e.first_name, 2))) AS formatted_first_name,

    CONCAT(UPPER(SUBSTRING(e.last_name, 1, 1)), LOWER(SUBSTRING(e.last_name, 2))) AS formatted_last_name

FROM Employees e;

Explanation:

  • UPPER() and LOWER() are string functions used to make the first letter uppercase and the rest of the name lowercase.
  • CONCAT() is used to join the modified first and last names together.
Example 2: Date Functions - Calculating Years of Employment

If you want to calculate how long an employee has been working based on their hire_date, you can use the DATEDIFF() function:

SELECT 
    e.first_name,
    e.last_name,
    DATEDIFF(CURDATE(), e.hire_date) AS days_employed,
    DATEDIFF(CURDATE(), e.hire_date) / 365 AS years_employed
FROM Employees e;


Explanation:

  • DATEDIFF(CURDATE(), e.hire_date) calculates the number of days between today (CURDATE()) and the employee’s hire_date.
  • Dividing the number of days by 365 gives an approximate number of years the employee has been with the company.
Example 3: Aggregate Functions - Average Salary by Department

If you want to calculate the average salary by department, you can use the AVG() function:

SELECT 
    d.department_name,
    AVG(e.salary) AS avg_salary
FROM 
    Employees e
JOIN 
    Departments d ON e.department_id = d.department_id
GROUP BY 
    d.department_name;

Explanation:

  • AVG(e.salary) calculates the average salary of employees in each department.
  • GROUP BY groups the employees by department, so the aggregation happens for each department separately.

Example 4: Mathematical Functions - Rounding Salaries

Suppose you want to round employee salaries to the nearest thousand for a report:

SELECT e.first_name, e.last_name, ROUND(e.salary, -3) AS rounded_salary FROM Employees e;

Explanation:

  • ROUND(e.salary, -3) rounds the salary to the nearest thousand
  • (the negative value indicates rounding to a place before the decimal point,
  • in this case,
  • to the thousands).

Example 5: Using CASE Statements - Conditional Logic in Queries

You can use the CASE function to apply conditional logic in SQL.

For example, you want to display a bonus eligibility column based on the employee's salary:

SELECT e.first_name, e.last_name, e.salary, CASE WHEN e.salary > 80000 THEN 'Eligible' ELSE 'Not Eligible' END AS bonus_eligibility FROM Employees e;


Explanation:

  • The CASE function evaluates the salary: if it’s greater than 80,000, the employee is
  • marked as "Eligible" for a bonus, otherwise "Not Eligible".
 

Example 6: Conversion Functions - Converting Data Types

To convert a salary to a string format:


SELECT e.first_name, e.last_name, CAST(e.salary AS CHAR) AS salary_as_string FROM Employees e;


Explanation:

  • CAST(e.salary AS CHAR) converts the numerical salary to a string (CHAR).

Categories of SQL Functions useful methods Name

Categories of SQL Functions:

  1. Aggregate Functions: These operate on a group of rows and return a single result (used in conjunction with GROUP BY).

    • Examples: AVG(), SUM(), COUNT(), MAX(), MIN()
  2. Scalar Functions: These operate on a single value and return a single result.

    • Examples: UPPER(), LOWER(), LENGTH(), CONCAT(), ROUND()
  3. String Functions: Used to manipulate string (text) data.

    • Examples: CONCAT(), TRIM(), SUBSTRING(), REPLACE()
  4. Date Functions: Used to manipulate date and time values.

    • Examples: NOW(), DATEADD(), DATEDIFF(), YEAR(), MONTH()
  5. Mathematical Functions: Used to perform mathematical calculations.

    • Examples: ROUND(), CEILING(), FLOOR(), ABS(), POW()
  6. Conversion Functions: Used to convert one data type to another.

    • Examples: CAST(), CONVERT()
Categories of SQL Functions useful methods Name


SQL best example ever for learning

 The "best" SQL example depends on the context or the task you're looking to solve. But here's a comprehensive SQL example that covers multiple aspects of SQL queries, such as SELECT, JOIN, GROUP BY, HAVING, and Subqueries. This can showcase SQL power and flexibility in real-world scenarios.


Scenario:

Let's assume we have two tables:

  1. Employees

    • employee_id (Primary Key)
    • first_name
    • last_name
    • department_id
    • salary
    • hire_date
  2. Departments

    • department_id (Primary Key)
    • department_name

Task:

We want to retrieve:

  • The department name,
  • The average salary of employees in each department,
  • The highest salary in each department,
  • The total number of employees in each department,
  • Only for departments with more than 5 employees,
  • Ordered by highest salary.

Additionally, we want to show the top 5 highest-paid employees and their respective department names.


-- Retrieve department statistics

SELECT 

    d.department_name,

    AVG(e.salary) AS avg_salary,

    MAX(e.salary) AS highest_salary,

    COUNT(e.employee_id) AS total_employees

FROM 

    Employees e

JOIN 

    Departments d

ON 

    e.department_id = d.department_id

GROUP BY 

    d.department_name

HAVING 

    COUNT(e.employee_id) > 5

ORDER BY 

    highest_salary DESC;


-- Retrieve top 5 highest-paid employees

SELECT 

    e.first_name, 

    e.last_name, 

    e.salary,

    d.department_name

FROM 

    Employees e

JOIN 

    Departments d

ON 

    e.department_id = d.department_id

ORDER BY 

    e.salary DESC

LIMIT 5;

Explanation:

  1. JOIN: Combines the Employees and Departments tables based on the department_id field, so you can access both employee details and their respective department names.

  2. Aggregation (AVG, MAX, COUNT):

    • AVG(e.salary): Calculates the average salary of employees within each department.
    • MAX(e.salary): Finds the highest salary within each department.
    • COUNT(e.employee_id): Counts the total number of employees in each department.
  3. GROUP BY: Groups the result by department_name so that aggregation functions like AVG, MAX, and COUNT operate on each department separately.

  4. HAVING: Filters out departments that have 5 or fewer employees.

  5. ORDER BY: Orders the result by the highest_salary in descending order, so the department with the highest salary appears first.

  6. LIMIT 5: Retrieves only the top 5 highest-paid employees from the second query.


Sample Output:

  1. Department Statistics (for departments with more than 5 employees):
department_nameavg_salaryhighest_salarytotal_employees
IT750001200008
Marketing60000900006
  1. Top 5 Highest-Paid Employees:
first_namelast_namesalarydepartment_name
JohnDoe120000IT
JaneSmith115000IT
MichaelBrown110000HR
EmilyDavis95000Marketing
SarahWilson92000Marketing

This example combines several key SQL operations, including joins, grouping, filters, sorting, and limiting, to solve a business problem effectively and is a great demonstration of SQL's capabilities.

.NET OOP Concepts basic things

Object-Oriented Programming (OOP) is a programming paradigm that is based on the concept of "objects", which are instances of classes. .NET, being an object-oriented framework, supports OOP principles such as Encapsulation, Inheritance, Polymorphism, and Abstraction.


Here’s an explanation of each OOP concept with examples in C#:

Key Points:

  • Encapsulation ensures that the internal state of an object is protected from outside manipulation.
  • Inheritance allows new classes to inherit behaviors and attributes from existing ones.
  • Polymorphism enables objects of different types to be treated uniformly, and their methods to behave differently depending on the object type.
  • Abstraction hides the complex implementation and exposes only necessary functionalities.

Applying Functions in SQL Queries:

How to Know Which Function to Use: You can use these functions to transform data, calculate values, or extract specific information in your ...

Best for you