Wednesday, September 24, 2025

πŸ”ΉSQL Server Math Functions — ROUND(), ABS(), CEILING(), FLOOR() Explained (With Examples)


1) Quick overview

  • ROUND(): Round a numeric expression to a specified precision (can also truncate).

  • ABS(): Return the absolute (non-negative) value of a numeric expression.

  • CEILING(): Return the smallest integer greater than or equal to the input (always rounds up).

  • FLOOR(): Return the largest integer less than or equal to the input (always rounds down).

These functions are available in T‑SQL (SQL Server, Azure SQL DB) and are indispensable for reporting, finance calculations, and data transformations.


2) ROUND() — syntax, examples, and tips

Syntax

ROUND(numeric_expression, length [, function])
  • numeric_expression: the value to round (FLOAT, DECIMAL, MONEY, etc.).

  • length: number of decimal places to round to. Can be negative to round left of the decimal.

  • function: optional. If 0 or omitted → standard rounding; if 1 → truncate (no rounding).

Examples

SELECT ROUND(123.4567, 2) AS RoundedTo2; -- 123.46
SELECT ROUND(123.4567, 0) AS RoundedTo0; -- 123
SELECT ROUND(123.4567, -1) AS RoundedTo10; -- 120
SELECT ROUND(123.4567, 2, 1) AS Truncated2; -- 123.45 -- truncates instead of rounding

Edge cases / notes

  • If length is negative and larger than the number of digits left of the decimal, the result can be 0.

  • ROUND() preserves numeric scale/type depending on input types (DECIMAL keeps precision better than FLOAT).

  • To deliberately truncate (drop trailing decimals without rounding), use the third argument 1.

Use-case: rounding currency values to 2 decimal places for display, or rounding averages in reports.


3) ABS() — absolute value

Syntax

ABS(numeric_expression)

Examples

SELECT ABS(-10) AS Pos1; -- 10
SELECT ABS(25) AS Pos2; -- 25
SELECT ABS(-123.45) AS Pos3; -- 123.45

Use-case: measuring magnitude of differences (e.g., ABS(Sales - Cost)), distance calculations, or when you only care about magnitude, not direction.

Tip: ABS() does not change zero or positive values; it returns the same data type as the input when possible.


4) CEILING() and FLOOR() — always up, always down

CEILING — smallest integer greater than or equal to the expression.

Syntax

CEILING(numeric_expression)

Examples

SELECT CEILING(123.45) AS Ceil1; -- 124
SELECT CEILING(10.00) AS Ceil2; -- 10
SELECT CEILING(-123.45) AS Ceil3; -- -123 -- note how "up" behaves with negatives

FLOOR — largest integer less than or equal to the expression.

Syntax

FLOOR(numeric_expression)

Examples

SELECT FLOOR(123.45) AS Floor1; -- 123
SELECT FLOOR(10.99) AS Floor2; -- 10
SELECT FLOOR(-123.45) AS Floor3; -- -124 -- note how "down" behaves with negatives

Important: For negative numbers CEILING() and FLOOR() move in different directions relative to zero:

  • CEILING(-2.3)-2 (moves up toward zero)

  • FLOOR(-2.3)-3 (moves down away from zero)

Use-case: CEILING() for computing required counts (e.g., how many pages are needed), FLOOR() for bucketizing values into integer thresholds.


5) Comparison & behavior with negative numbers

FunctionWhat it returns (example)Notes on negative values
ROUND(x, n)Rounded value to n decimalsRounds normally; can also truncate with 3rd param
ABS(x)Absolute valueRemoves sign
CEILING(x)Smallest integer >= xCEILING(-2.3)-2
FLOOR(x)Largest integer <= xFLOOR(-2.3)-3

Examples in one query

SELECT
3.5 AS Value,
ROUND(3.5,0) AS Round_3_5,
CEILING(3.5) AS Ceiling_3_5,
FLOOR(3.5) AS Floor_3_5,
ABS(-3.5) AS Abs__Neg3_5;

-- Expected output row: 3.5 | 4 | 4 | 3 | 3.5

Rounding of .5 values: SQL Server’s ROUND() uses standard arithmetic rounding (commonly: round .5 away from zero). If your application demands banker's rounding (round half to even), implement a custom function or handle it in application code.


6) Real-world examples and patterns

A. Currency display (round to 2 decimals)

SELECT ProductId, Price, ROUND(Price, 2) AS Price_Display
FROM Products;

B. Bill generation (always charge full unit)

-- Charge full rupee/dollar if there is any fraction
SELECT OrderId, Price, CEILING(Price) AS AmountToBill
FROM Orders;

C. Page count (how many pages for N rows)

DECLARE @rows INT = 1023; DECLARE @pageSize INT = 100;
SELECT CEILING(@rows * 1.0 / @pageSize) AS PagesNeeded; -- 11 pages

D. Absolute difference (profit/loss magnitude)

SELECT OrderId, ABS(Revenue - Cost) AS DiffMagnitude
FROM OrderFinance;

E. Bucketing / grouping (floor)

-- Price buckets of size 10
SELECT FLOOR(Price / 10) * 10 AS PriceBucket, COUNT(*)
FROM Products
GROUP BY FLOOR(Price / 10);

7) Common pitfalls & best practices

  • Floating point precision: Avoid FLOAT for exact money calculations — prefer DECIMAL(18,2) to prevent binary-floating precision surprises.

  • Rounding ties: If you must use bankers rounding (round half to even) for financial accuracy, implement it explicitly — SQL Server’s built-in ROUND() follows arithmetic rounding conventions by default.

  • Truncation vs rounding: Use ROUND(..., function = 1) when you want to truncate without rounding.

  • NULL values: These functions return NULL if the input expression is NULL — handle with ISNULL() or COALESCE() if needed.

  • Performance: Numeric functions are cheap, but avoid applying them in large-scale JOIN/WHERE predicates on columns without indexing — consider persisted computed columns if frequently used for filtering.


Below are the key authoritative sources I used to verify the factual points in the article (useful to cite or keep for reference):

Tuesday, September 23, 2025

DELETE vs TRUNCATE vs DROP in SQL Server

 1. DELETE

  • Used to remove rows one at a time from a table.

  • Can be filtered with WHERE clause.

  • Each deleted row is logged in transaction log (slower).

  • Identity column value does not reset unless explicitly used with DBCC CHECKIDENT.

  • Can be rolled back if inside a transaction.

✅ Example:

DELETE FROM Employees WHERE DeptId = 2;

2. TRUNCATE

  • Removes all rows from a table (no WHERE).

  • Logs only page deallocations (faster than DELETE).

  • Resets identity column to seed value.

  • Cannot be used if:

    • Table is referenced by a foreign key.

    • Indexed views exist on the table.

  • Can be rolled back if inside a transaction.

✅ Example:

TRUNCATE TABLE Employees;

3. DROP

  • Deletes the entire table structure and data.

  • Table definition, constraints, indexes, triggers — all removed.

  • Cannot be rolled back (once committed).

  • After DROP, table is gone from database; must be recreated to use again.

✅ Example:

DROP TABLE Employees;

4. Key Differences Table

FeatureDELETETRUNCATEDROP
RemovesSpecific rows (WHERE) or allAll rowsEntire table (structure + data)
WHERE Clause✅ Allowed❌ Not allowed❌ Not applicable
LoggingRow-by-row (slow)Minimal logging (fast)Logs table removal
Identity Reset❌ No✅ Yes❌ Not applicable
Rollback Possible✅ Yes✅ Yes❌ No (unless inside transaction)
Foreign Key Restriction✅ Allowed❌ Not allowed if referenced✅ Allowed (but drops constraints)
Table Structure Exists?✅ Yes (after delete)✅ Yes (empty table)❌ No (removed completely)
SpeedSlower (row-by-row)Faster (deallocate pages)Fastest (drops object)

5. When to Use?

  • DELETE → When you need to remove specific rows or want triggers to fire.

  • TRUNCATE → When you want to remove all rows quickly and reset identity.

  • DROP → When you want to completely remove table and free space.


6. Interview Tip

If interviewer asks:
πŸ‘‰ “Can we rollback TRUNCATE?”
✅ Answer: Yes, TRUNCATE can be rolled back if executed inside a transaction.

BEGIN TRAN; TRUNCATE TABLE Employees; ROLLBACK; -- restores data

πŸ‘‰ “Why TRUNCATE is faster than DELETE?”
✅ Answer: Because TRUNCATE logs only extent (page) deallocation, while DELETE logs each row removal.

Understanding Singleton Design Pattern in C# with Real-Time Examples

 πŸ“Œ Introduction

In software design patterns, the Singleton Design Pattern plays a crucial role when we want to ensure that only one instance of a class exists throughout the lifecycle of an application. Singleton provides a global access point to this single instance, making it widely used in scenarios like logging, configuration management, caching, and database connections.

In this article, we will explore:

  • What is Singleton Design Pattern?

  • Importance of private constructor, static variable, and static constructor.

  • Real-time example with C#.

  • Difference between Singleton and Static class.

  • Lazy Singleton with thread safety implementation.



πŸš€ What is Singleton Design Pattern?

The Singleton Pattern ensures that a class has only one instance and provides a global access point to it. This prevents duplicate objects from being created unnecessarily and helps in maintaining a single state across the application.

For example, imagine a Logger class – instead of creating multiple loggers in different modules, a singleton logger ensures all logs go through one centralized object.


πŸ”Ž Importance of Components in Singleton

✅ Private Constructor

  • Prevents the creation of an object using the new keyword.

  • Ensures external classes cannot instantiate multiple objects.

private Logger() { }

✅ Static Variable

  • Stores the single instance of the class.

  • Ensures only one instance exists globally.

private static Logger _instance;

✅ Static Constructor

  • Initializes the singleton instance only once, automatically by the CLR.

  • Ensures thread-safe initialization.

static Logger() { _instance = new Logger(); }

πŸ’‘ Real-Time Example: Logger Singleton

public sealed class Logger { private static readonly Logger _instance; // Static constructor static Logger() { _instance = new Logger(); } // Private constructor private Logger() { } // Public global access point public static Logger Instance => _instance; public void Log(string message) { Console.WriteLine($"[Log]: {message}"); } } // Usage class Program { static void Main() { Logger.Instance.Log("Application started"); Logger.Instance.Log("User logged in"); } }

πŸ“Œ Output:

[Log]: Application started [Log]: User logged in

Here, Logger.Instance always points to the same object.


πŸ†š Singleton vs Static Class

FeatureSingleton ClassStatic Class
InstanceSingle object (controlled creation)No instance (direct static access)
InheritanceCan implement interfaces & inheritCannot inherit or implement interfaces
FlexibilityCan be extended, mocked, injected (DI)Rigid, cannot be mocked/tested
State ManagementCan maintain state inside instanceUses static fields (global state)
InitializationCan use lazy loading for performanceAlways loaded at first access

πŸ‘‰ Use Singleton for shared resources like Database Connections, Logger, Cache Manager.
πŸ‘‰ Use Static Class for utility/helper methods like Math or Convert.


πŸ›‘️ Lazy Singleton with Thread Safety in C#

In high-performance applications, it is better to create the singleton instance only when needed (Lazy Initialization). This saves memory and improves performance.

✅ Thread-Safe Lazy Singleton Example

public sealed class ConfigurationManager { // Lazy ensures thread safety and lazy initialization private static readonly Lazy<ConfigurationManager> _instance = new Lazy<ConfigurationManager>(() => new ConfigurationManager()); // Private constructor private ConfigurationManager() { Console.WriteLine("Configuration Manager Initialized"); } // Global access point public static ConfigurationManager Instance => _instance.Value; public string GetConfig(string key) { return $"Value of {key}"; } } // Usage class Program { static void Main() { var config1 = ConfigurationManager.Instance; Console.WriteLine(config1.GetConfig("ConnectionString")); var config2 = ConfigurationManager.Instance; Console.WriteLine(ReferenceEquals(config1, config2)); // true } }

πŸ“Œ Output

Configuration Manager Initialized Value of ConnectionString True

✔ The constructor runs only once.
✔ Both config1 and config2 point to the same instance.
✔ The Lazy<T> type ensures thread safety automatically.


🎯 Conclusion

The Singleton Design Pattern in C# is one of the most powerful and commonly used design patterns for managing shared resources. With the help of private constructor, static variables, and static constructors, we can ensure that only one instance exists throughout the application.

For modern .NET applications, the Lazy Singleton with thread safety approach is the most efficient and recommended implementation.

Key Takeaway:

  • Use Singleton when you need a shared, single instance with controlled access.

  • Use Static Class when you need utility functions without state.

Complete Guide to ReactJS with .NET Core and CRUD Example

 1. What is ReactJS?

ReactJS is a popular JavaScript library developed by Facebook for building fast, dynamic, and scalable frontend user interfaces (UI).

  • It follows a component-based architecture.

  • Uses Virtual DOM for high performance rendering.

  • Supports declarative programming and reusable components.

  • Works well with REST APIs or GraphQL for backend integration.

πŸ‘‰ SEO Keywords: ReactJS in .NET Core, React Frontend Development, ReactJS Tutorial, React CRUD with Web API.


2. Installing ReactJS in a .NET Core Application

When building apps in .NET Core + ReactJS, you can set up in two ways:

Option A: Create a React Template with .NET Core

dotnet new react -o MyReactApp cd MyReactApp dotnet run

This scaffolds a .NET Core backend with a React frontend inside ClientApp.

Option B: Add ReactJS to an existing .NET Core project

  1. Go to your project root.

  2. Create React app:

    npx create-react-app ClientApp
  3. Install dependencies:

    cd ClientApp npm install
  4. Configure Startup.cs (or Program.cs in .NET 6+) to serve React app.

    app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseReactDevelopmentServer(npmScript: "start"); } });

3. How ReactJS Supports Frontend UI Development

ReactJS is frontend-only but it integrates seamlessly with backends like .NET Web API.

  • Reusable Components → Build buttons, forms, tables once and reuse.

  • State Management → Manage UI data using hooks (useState, useReducer).

  • Routingreact-router-dom handles single-page app navigation.

  • Data Fetching → Fetch data from .NET Web API using fetch or axios.

  • Cross-platform UI → Works for web, mobile (React Native), and desktop (Electron).


4. Overview: Learn ReactJS from Scratch

πŸ”‘ Core Concepts to Master

  1. JSX (JavaScript XML) → Write HTML inside JS.

  2. Components → Class and Functional components.

  3. Props → Pass data between components.

  4. State → Store component data.

  5. Lifecycle Methods & HooksuseEffect, useState.

  6. Routing → Navigation between pages.

  7. Forms & Validation → Controlled and uncontrolled components.

  8. API Integration → Connect with .NET Core Web API.

πŸ‘‰ Start with functional components + hooks (modern standard).


5. Main Components in ReactJS

React apps are built using three main types of components:

  1. Functional Components – Simplest, uses hooks.

    function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
  2. Class Components – Older style, supports lifecycle methods.

    class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
  3. Higher-Order Components (HOC) – Wraps another component to add features.


6. CRUD Example (ReactJS + .NET Web API)

Step 1: Create .NET Web API (Employee Example)

// Employee.cs (Model) public class Employee { public int Id { get; set; } public string Name { get; set; } public string Department { get; set; } }
// EmployeesController.cs [ApiController] [Route("api/[controller]")] public class EmployeesController : ControllerBase { private static List<Employee> employees = new List<Employee> { new Employee { Id = 1, Name = "John", Department = "IT" }, new Employee { Id = 2, Name = "Sara", Department = "HR" } }; [HttpGet] public IActionResult Get() => Ok(employees); [HttpGet("{id}")] public IActionResult Get(int id) => Ok(employees.FirstOrDefault(e => e.Id == id)); [HttpPost] public IActionResult Post(Employee emp) { emp.Id = employees.Max(e => e.Id) + 1; employees.Add(emp); return Ok(emp); } [HttpPut("{id}")] public IActionResult Put(int id, Employee emp) { var employee = employees.FirstOrDefault(e => e.Id == id); if (employee == null) return NotFound(); employee.Name = emp.Name; employee.Department = emp.Department; return Ok(employee); } [HttpDelete("{id}")] public IActionResult Delete(int id) { var emp = employees.FirstOrDefault(e => e.Id == id); if (emp == null) return NotFound(); employees.Remove(emp); return Ok(); } }

Step 2: ReactJS Frontend (CRUD UI)

import React, { useState, useEffect } from "react"; import axios from "axios"; function Employees() { const [employees, setEmployees] = useState([]); const [newEmp, setNewEmp] = useState({ name: "", department: "" }); useEffect(() => { axios.get("/api/employees").then(res => setEmployees(res.data)); }, []); const addEmployee = () => { axios.post("/api/employees", newEmp).then(res => { setEmployees([...employees, res.data]); setNewEmp({ name: "", department: "" }); }); }; const deleteEmployee = (id) => { axios.delete(`/api/employees/${id}`).then(() => { setEmployees(employees.filter(emp => emp.id !== id)); }); }; return ( <div> <h2>Employee List</h2> <ul> {employees.map(emp => ( <li key={emp.id}> {emp.name} - {emp.department} <button onClick={() => deleteEmployee(emp.id)}>Delete</button> </li> ))} </ul> <h3>Add Employee</h3> <input placeholder="Name" value={newEmp.name} onChange={e => setNewEmp({ ...newEmp, name: e.target.value })} /> <input placeholder="Department" value={newEmp.department} onChange={e => setNewEmp({ ...newEmp, department: e.target.value })} /> <button onClick={addEmployee}>Add</button> </div> ); } export default Employees;

✅ With this setup:

  • .NET Web API → Handles backend CRUD operations.

  • ReactJS → Provides UI with API integration.


⚡ Would you like me to also create a step-by-step folder structure (Backend + Frontend) so you can directly scaffold this in your project?

You said:
yes
ChatGPT said:

Perfect πŸ‘ Let’s set up a step-by-step folder structure for a React + .NET Core CRUD project so you can scaffold it directly and start coding without confusion.


πŸ“‚ Folder Structure: ReactJS + .NET Core CRUD Application

We’ll call the solution EmployeeManagementApp.


1. Backend (.NET Core Web API)

πŸ“ EmployeeManagementApp

EmployeeManagementApp/ │── EmployeeManagementApp.sln # Solution file │ ├── EmployeeManagementApp.API/ # .NET Core Web API Project │ │── Program.cs # Entry point │ │── Startup.cs (if .NET 5) # Middleware & services │ │── appsettings.json # Configurations │ │ │ ├── Controllers/ │ │ └── EmployeesController.cs # CRUD API │ │ │ ├── Models/ │ │ └── Employee.cs # Employee model │ │ │ ├── Data/ (Optional if using EF Core) │ │ └── AppDbContext.cs # DbContext for EF Core │ │ │ └── Properties/ │ └── launchSettings.json # Local server settings

πŸ‘‰ If you’re using Entity Framework Core, you’d add a Migrations/ folder here after running dotnet ef migrations add InitialCreate.


2. Frontend (ReactJS App)

πŸ“ ClientApp (inside the root solution folder)

ClientApp/ │── package.json # React dependencies │── public/ # Static files (index.html, favicon) │── src/ # React source code │ │── index.js # App entry point │ │── App.js # Root component │ │── services/ │ │ └── employeeService.js # Axios API calls │ │ │ ├── components/ # React UI Components │ │ ├── EmployeeList.js # List employees │ │ ├── EmployeeForm.js # Add/Edit employee │ │ └── Navbar.js # Navigation bar (optional) │ │ │ ├── pages/ # Page-level components │ │ ├── HomePage.js │ │ └── EmployeePage.js │ │ │ └── styles/ # CSS or Tailwind setup │ └── App.css

3. Integration Setup

✅ In Program.cs (or Startup.cs for .NET 5):

app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseReactDevelopmentServer(npmScript: "start"); } });

✅ In React (employeeService.js):

import axios from "axios"; const API_URL = "/api/employees"; export const getEmployees = () => axios.get(API_URL); export const addEmployee = (emp) => axios.post(API_URL, emp); export const deleteEmployee = (id) => axios.delete(`${API_URL}/${id}`); export const updateEmployee = (id, emp) => axios.put(`${API_URL}/${id}`, emp);

4. Project Execution

πŸ”Ή Run Backend (.NET Core Web API)

cd EmployeeManagementApp.API dotnet run

πŸ”Ή Run Frontend (React)

cd ClientApp npm start

The React app will connect to .NET Core Web API at /api/employees.


5. Workflow

  1. Open Solution in Visual Studio / VS Code.

  2. Backend (API) → Handles data storage (SQL Server / In-Memory).

  3. Frontend (React) → Calls backend APIs for CRUD operations.

  4. Shared Development → API runs on https://localhost:5001, React runs on http://localhost:3000.

Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages