Showing posts with label How to Create function. Show all posts
Showing posts with label How to Create function. Show all posts

18 Dec 2025

๐Ÿ‘‰ “SQL Server 2025 Express Edition (FREE): Features, Limits & Why It’s a Game Changer”

๐Ÿš€ Introduction

SQL Server 2025 Express Edition is the latest free database from Microsoft, designed for developers and small applications. But this version is not just a small update — it brings major improvements in storage, features, and usability.


๐Ÿ”ฅ What is SQL Server 2025 Express?

SQL Server Express is a free edition used for:

  • Learning SQL Server

  • Small applications

  • Development & testing

๐Ÿ‘‰ It’s widely used because it is cost-effective and production-ready for small workloads


⭐ Key Features (Make this section strong)

1. Increased Database Size (BIG UPDATE)

  • Old versions: 10 GB

  • SQL Server 2025: 50 GB per database

๐Ÿ‘‰ This is a 5× increase, making it useful for real-world apps


2. Advanced Features Now Included

No need for separate version (Advanced Services removed)

Now includes:

  • Full-Text Search

  • Reporting Services

  • Basic ML features

๐Ÿ‘‰ Everything is now in one package


3. Better Performance & Engine Improvements

  • Improved query handling

  • Better concurrency

  • Stable execution plans

๐Ÿ‘‰ Means faster queries & fewer performance issues


⚠️ Limitations (Very important for SEO)

  • Max DB size: 50 GB

  • CPU: 1 socket / 4 cores

  • Memory: ~1.4 GB

  • ❌ No SQL Server Agent

  • ❌ No High Availability

๐Ÿ‘‰ Still best for small to medium applications


๐Ÿ’ก When Should You Use It?

Use SQL Server 2025 Express if:

  • You are learning SQL

  • Building small ERP / web apps

  • Need a free production database


๐Ÿ”ฅ Real Use Case (Add this — increases engagement)

Example:

  • Small ERP system

  • Blog CMS

  • Internal company tools


๐Ÿ“ฅ How to Download

๐Ÿ‘‰ Go to official Microsoft site
๐Ÿ‘‰ Download SQL Server 2025 Express
๐Ÿ‘‰ Install using basic setup


✅ Final Verdict

SQL Server 2025 Express is the most powerful free version ever, especially with:

  • 50 GB database limit

  • Built-in advanced features

  • Improved performance

๐Ÿ‘‰ Perfect for beginners + small production apps


๐Ÿš€ Why this version will perform better

  • SEO keywords added:

    • SQL Server 2025 Express features

    • SQL Server Express limits

    • free SQL Server download

  • Clear headings → Google friendly

  • Problem + value driven

  • More readable


12 Dec 2025

Best SQL Query to Find Duplicates – Step by Step Guide

 inding duplicate rows is one of the most common tasks in SQL, especially when working with real-world data like customer records, invoices, transactions, or log data.

In this article, you will learn the best SQL queries to identify duplicates, how to remove them, and how to prevent them in the future.

This is a beginner-friendly and practical tutorial you can use in SQL Server, MySQL, Oracle, PostgreSQL, and even BigQuery.


๐Ÿ” Why Finding Duplicates Is Important

Duplicate rows can create multiple problems:

  • Wrong totals in reports

  • Incorrect customer counts

  • Issues in billing

  • Slow performance

  • Errors in downstream systems (Power BI, ETL, APIs)

Cleaning duplicates is one of the first tasks in data quality improvement.


✅ 1. Find Duplicates Using GROUP BY (Best & Easiest Method)

This is the most common and universal method.

Query:

SELECT column1, column2, COUNT(*) AS duplicate_count FROM table_name GROUP BY column1, column2 HAVING COUNT(*) > 1;

✔ When to use:

  • When you want to know which values are duplicated

  • Works in SQL Server, MySQL, Oracle, PostgreSQL, BigQuery


๐Ÿ“Œ Example: Find Duplicate Email IDs

Suppose you have a table:

The email raj@gmail.com is repeated.

Query:

SELECT email, COUNT(*) AS duplicate_count FROM users GROUP BY email HAVING COUNT(*) > 1;

Output:

emailduplicate_count
 
        raj@gmail.com

๐Ÿ”ฅ 3. Find Duplicates Using ROW_NUMBER() (Best for Deleting)

This is the most powerful method.
It uses window functions and gives a row number to each duplicate group.

Query:

WITH cte AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn FROM users ) SELECT * FROM cte WHERE rn > 1;

✔ When to use:

  • When you need to delete only duplicates and keep 1 record

  • When you want to mark duplicates


๐Ÿ—‘ 4. Delete Duplicate Rows (Keep Only One)

Using the same CTE:

WITH cte AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn FROM users ) DELETE FROM cte WHERE rn > 1;

This deletes all duplicate rows but keeps the first row.


๐Ÿง  5. Find Duplicates by Date or Conditional Columns

Example: Find duplicates only for rows created today.

SELECT name, email, created_date, COUNT(*) FROM users WHERE created_date = CURRENT_DATE GROUP BY name, email, created_date HAVING COUNT(*) > 1;

This is useful for ETL loads and daily imports.


๐Ÿ›‘ 6. Prevent Duplicates Using Constraints

Best long-term solution.

In SQL Server / MySQL / PostgreSQL:

ALTER TABLE users ADD CONSTRAINT uq_email UNIQUE (email);

In Oracle:

ALTER TABLE users ADD CONSTRAINT uq_email UNIQUE (email);

After this, the database will automatically block duplicate values.


๐Ÿ“ธ Screenshots You Should Add (To Increase SEO + AdSense Earnings)

You can add these screenshots:

  • SSMS window showing query

  • Duplicate rows in a sample table

  • Execution result window

(If you want, I can generate clean screenshots for you.)


❓ FAQ – Frequently Asked Questions

1. What is the fastest way to find duplicates in SQL?

Using GROUP BY + HAVING COUNT(*) > 1 is the simplest and fastest method.


2. Does ROW_NUMBER() find duplicates?

Yes. ROW_NUMBER assigns sequence numbers to rows allowing you to identify duplicate rows easily.


3. Will deleting duplicates improve performance?

Yes.
Removing duplicates improves:

  • Query performance

  • Joins

  • Aggregations

  • ETL workflows


4. How to avoid duplicates permanently?

Use a UNIQUE constraint or PRIMARY KEY on important columns like email, mobile, employee code, etc.


5. Does this work in all SQL databases?

Yes — all examples work in:

  • SQL Server

  • MySQL

  • PostgreSQL

  • Oracle

  • BigQuery


⭐ Final Thoughts

Finding and removing duplicates is a critical part of database maintenance.
By using the queries shown above—GROUP BY, ROW_NUMBER, and unique constraints—you can quickly identify and eliminate duplicate data efficiently.

If you want more SQL tutorials, feel free to browse my other posts or ask in the comments!


๐Ÿ‘‰ Want more articles like this for your blog?

I can write complete SEO-optimized posts on:

  • SQL Server

  • MySQL

  • BigQuery

  • Oracle

  • DBeaver

  • Power BI

  • ASP.NET

  • Data analysis topics

Just tell me your next topic!

7 Dec 2025

FULL PYTHON + MS SQL SCRIPT (BEST PRACTICE)

 

FULL PYTHON + MS SQL SCRIPT (BEST PRACTICE)

import pyodbc


# -----------------------------------------

# SQL CONNECTION (EDIT THIS PART)

# -----------------------------------------

def get_connection():

    try:

        conn = pyodbc.connect(

            "DRIVER={ODBC Driver 17 for SQL Server};"

            "SERVER=YOUR_SERVER_NAME;"      # e.g. DESKTOP-123\SQLEXPRESS

            "DATABASE=YOUR_DATABASE_NAME;"

            "UID=YOUR_USERNAME;"

            "PWD=YOUR_PASSWORD;",

            autocommit=False                # Manual commit = safer

        )

        return conn

    except Exception as ex:

        print("Database connection failed:", ex)

        return None



# -----------------------------------------

# INSERT RECORD

# -----------------------------------------

def insert_employee(emp_id, name, salary):

    conn = get_connection()

    if not conn:

        return

    try:

        cursor = conn.cursor()

        query = """

            INSERT INTO Employees (EmpID, Name, Salary)

            VALUES (?, ?, ?)

        """

        cursor.execute(query, (emp_id, name, salary))

        conn.commit()

        print("Record inserted successfully!")

    except Exception as ex:

        conn.rollback()

        print("Insert failed:", ex)

    finally:

        conn.close()



# -----------------------------------------

# UPDATE RECORD

# -----------------------------------------

def update_employee(emp_id, new_salary):

    conn = get_connection()

    if not conn:

        return

    try:

        cursor = conn.cursor()

        query = """

            UPDATE Employees

            SET Salary = ?

            WHERE EmpID = ?

        """

        cursor.execute(query, (new_salary, emp_id))

        conn.commit()

        print("Record updated successfully!")

    except Exception as ex:

        conn.rollback()

        print("Update failed:", ex)

    finally:

        conn.close()



# -----------------------------------------

# DELETE RECORD

# -----------------------------------------

def delete_employee(emp_id):

    conn = get_connection()

    if not conn:

        return

    try:

        cursor = conn.cursor()

        query = "DELETE FROM Employees WHERE EmpID = ?"

        cursor.execute(query, (emp_id,))

        conn.commit()

        print("Record deleted successfully!")

    except Exception as ex:

        conn.rollback()

        print("Delete failed:", ex)

    finally:

        conn.close()



# -----------------------------------------

# SELECT ALL RECORDS

# -----------------------------------------

def get_all_employees():

    conn = get_connection()

    if not conn:

        return

    try:

        cursor = conn.cursor()

        cursor.execute("SELECT EmpID, Name, Salary FROM Employees")


        print("\n--- Employee List ---")

        for row in cursor.fetchall():

            print(row.EmpID, row.Name, row.Salary)


    except Exception as ex:

        print("Select failed:", ex)

    finally:

        conn.close()



# -----------------------------------------

# CALL STORED PROCEDURE

# -----------------------------------------

def call_stored_procedure():

    """

    Example Stored Procedure:

    CREATE PROCEDURE GetEmployees

    AS

    BEGIN

        SELECT * FROM Employees

    END

    """

    conn = get_connection()

    if not conn:

        return

    try:

        cursor = conn.cursor()

        cursor.execute("{CALL GetEmployees}")   # or EXEC GetEmployees

        rows = cursor.fetchall()


        print("\n--- Stored Procedure Result ---")

        for row in rows:

            print(row.EmpID, row.Name, row.Salary)


    except Exception as ex:

        print("Stored procedure failed:", ex)

    finally:

        conn.close()



# -----------------------------------------

# MAIN TESTING

# -----------------------------------------

if __name__ == "__main__":

    insert_employee(1, "Vijay", 50000)

    update_employee(1, 60000)

    get_all_employees()

    delete_employee(1)

    get_all_employees()

    call_stored_procedure()

๐Ÿš€ How to Use

  1. Update:

SERVER= DATABASE= UID= PWD=
  1. Create sample table in SQL:

CREATE TABLE Employees ( EmpID INT PRIMARY KEY, Name VARCHAR(100), Salary DECIMAL(18,2) );
  1. Run the Python file:

python mssql_python_demo.py

4 Dec 2025

SQL Server 2025 introduces vector data types and functions

 SQL Server 2025 introduces vector data types and functions, enabling native AI-driven similarity searches and machine learning tasks directly in SQL queries without external tools.​


Key AI Features

Vector data types store embeddings as optimized binary JSON arrays for efficient operations like distance calculations (e.g., VECTOR_DISTANCE, VECTOR_NORM). New vector indexes support approximate nearest neighbor searches, accelerating AI workloads. External AI model management allows invoking REST endpoints for embeddings via sp_invoke_external_rest_endpoint.​


Developer Enhancements

Regular expressions functions like REGEXP_LIKE and REGEXP_REPLACE enable pattern matching and text manipulation in queries. Fuzzy string matching with EDIT_DISTANCE_SIMILARITY computes similarity scores for approximate searches. Change event streaming captures real-time DML changes to Azure Event Hubs in JSON or Avro formats.​


Performance Improvements

Optimized locking reduces blocking and memory use, while tempdb governance prevents space exhaustion from runaway jobs. Cardinality estimation feedback for expressions adapts query plans across executions, and optional parameter plan optimization (OPPO) handles varying parameters dynamically. These align with 2025 trends like AI integration and query tuning for modern data stacks

21 Apr 2024

How to Create Functions in MS Sql Database

 Creating functions in Microsoft SQL Server allows you to encapsulate reusable logic that can be called within SQL queries. There are two types of functions in SQL Server: scalar functions and table-valued functions. Here's how you can create both types with examples:

Scalar Function Example:

A scalar function returns a single value based on the input parameters.

sql
CREATE FUNCTION dbo.AddTwoNumbers ( @Num1 INT, @Num2 INT ) RETURNS INT AS BEGIN DECLARE @Result INT; SET @Result = @Num1 + @Num2; RETURN @Result; END;

Explanation:

  • dbo.AddTwoNumbers is the name of the function.
  • @Num1 and @Num2 are input parameters.
  • RETURNS INT specifies the return data type.
  • Inside the function body, we calculate the sum of @Num1 and @Num2 and return the result.

You can then use this function in SQL queries like any built-in function:

sql
SELECT dbo.AddTwoNumbers(5, 3) AS SumResult; -- Output: 8

Table-Valued Function Example:

A table-valued function returns a result set in the form of a table.

sql
CREATE FUNCTION dbo.GetEmployeesByDepartment ( @DepartmentID INT ) RETURNS TABLE AS RETURN ( SELECT EmployeeID, FirstName, LastName FROM Employees WHERE DepartmentID = @DepartmentID );

Explanation:

  • dbo.GetEmployeesByDepartment is the name of the function.
  • @DepartmentID is the input parameter.
  • RETURNS TABLE specifies that the function returns a table.
  • Inside the function body, we select employee details from the Employees table based on the input DepartmentID.

You can use this function in a SELECT statement to retrieve employee details for a specific department:

sql
SELECT * FROM dbo.GetEmployeesByDepartment(1);

This will return the employee details for the department with DepartmentID = 1.

Considerations:

  • When creating functions, consider the performance impact, especially for table-valued functions, as they can sometimes result in performance issues due to row-by-row processing.
  • Test your functions thoroughly to ensure they produce the expected results and perform well, especially in scenarios with large datasets.

By creating functions in SQL Server, you can modularize your code, improve code reusability, and simplify complex queries.

๐Ÿ‘‰ “Why Your SQL LEFT JOIN Is Creating Duplicate Rows (And How to Fix It Fast)”

  ๐Ÿšจ Problem (Relatable Hook) You wrote a simple LEFT JOIN … But suddenly your data is duplicated ๐Ÿ˜ต ๐Ÿ‘‰ Example: Expected: 100 rows ...