What is the best approach for identifying Data Quality issues using SQL?

Mphela Legodi 0 Reputation points
2026-11-30T10:13:19.72+00:00

I am looking to improve how I use SQL for Data Quality analysis. What SQL techniques or patterns are recommended for identifying issues such as duplicates, null values, invalid values and inconsistencies between related tables?

I am particularly interested in approaches that can be reused when profiling or validating different datasets.

SQL Server Integration Services
0 comments No comments

2 answers

Sort by: Most helpful
  1. Deepesh Dhake 1,325 Reputation points
    2026-11-30T14:18:01.46+00:00
    1. Profiling: Unpivot columns with CROSS APPLY (VALUES …) so one scan gives null, blank and distinct counts per column. Generate the list from sys.columns so it works on any table. Use a top-N frequency query to find sentinel values like 'N/A' or 1900-01-01.
    2. Duplicates: Use COUNT(*) OVER (PARTITION BY key) with ROW_NUMBER() to get the duplicate rows plus a survivor ranking. Normalize keys with UPPER(TRIM(...)) to catch near-duplicates.
    3. Invalid values: One pass, one counter per rule:
    SELECT
      SUM(CASE WHEN p.DobText IS NOT NULL
                AND (p.DobText = '' OR TRY_CONVERT(date, p.DobText, 112) IS NULL) THEN 1 ELSE 0 END) AS bad_date,
      SUM(CASE WHEN p.State IS NOT NULL AND s.Code IS NULL THEN 1 ELSE 0 END) AS bad_state
    FROM dbo.Person p
    LEFT JOIN ref.State s ON s.Code = p.State;   -- Code must be unique
    
    1. Cross-table checks:

    Orphans: use NOT EXISTS, not NOT IN.

    Totals: reconcile header totals against summed lines with HAVING.

    Source vs. target: run EXCEPT both ways on GROUP BY ... COUNT(*) results, so the comparison is NULL-safe and catches duplicate-count differences.

    Foreign keys: check sys.foreign_keys for disabled or untrusted keys.

    1. Reuse: Keep a rules table where each check_sql sets @failed. A runner procedure executes each one with sp_executesql, compares the result to a threshold, and logs it with a timestamp so you can track trends. Restrict who can write to the rules table, because its contents run as code.

    Was this answer helpful?

    0 comments No comments

  2. AI answer

    2026-11-30T10:14:12.6966667+00:00

    Create a reusable library of SQL validation rules that returns offending rows in a standard format, and use the SSIS Data Profiling Task to discover which rules and thresholds each dataset requires.

    1. Standardize the output of every quality rule

    Have each check return at least:

    • RuleName
    • TableName
    • RecordKey
    • ColumnName
    • BadValue
    • IssueDescription
    • DetectedAt

    This makes rules easy to combine with UNION ALL, persist in an exceptions table, report, and use as an SSIS quality gate.

    SELECT
        'CUSTOMER_EMAIL_REQUIRED' AS RuleName,
        'dbo.Customer' AS TableName,
        CAST(CustomerID AS varchar(50)) AS RecordKey,
        'Email' AS ColumnName,
        Email AS BadValue,
        'Email is null or blank' AS IssueDescription,
        SYSUTCDATETIME() AS DetectedAt
    FROM dbo.Customer
    WHERE Email IS NULL OR LTRIM(RTRIM(Email)) = '';
    

    Implement stable rules as views or stored procedures—for example, dq.Customer_EmailRequired—rather than repeatedly writing ad hoc queries.

    2. Use focused SQL patterns

    Duplicates

    Group by the columns that define business uniqueness, not necessarily the physical primary key.

    SELECT Email, COUNT(*) AS DuplicateCount
    FROM dbo.Customer
    WHERE Email IS NOT NULL
    GROUP BY Email
    HAVING COUNT(*) > 1;
    

    To retrieve every affected row, use a window function:

    WITH d AS
    (
        SELECT *,
               COUNT(*) OVER (PARTITION BY Email) AS DuplicateCount
        FROM dbo.Customer
        WHERE Email IS NOT NULL
    )
    SELECT *
    FROM d
    WHERE DuplicateCount > 1;
    

    Invalid values and ranges

    Use explicit domain rules. TRY_CONVERT is useful when source values arrive as text.

    SELECT CustomerID, Status, BirthDate
    FROM dbo.Customer
    WHERE Status NOT IN ('Active', 'Inactive', 'Pending')
       OR BirthDate > CAST(GETDATE() AS date)
       OR BirthDate < '19000101';
    

    For text length, formats, value distributions, numeric ranges, and date ranges, SSIS provides corresponding Length Distribution, Pattern, Value Distribution, and Statistics profiles ^1^.

    Missing parent rows

    Use NOT EXISTS to identify orphaned foreign-key values:

    SELECT o.OrderID, o.CustomerID
    FROM dbo.[Order] AS o
    WHERE o.CustomerID IS NOT NULL
      AND NOT EXISTS
      (
          SELECT 1
          FROM dbo.Customer AS c
          WHERE c.CustomerID = o.CustomerID
      );
    

    This corresponds to the SSIS Value Inclusion Profile, which measures overlap between columns and can reveal child values absent from the parent table ^1^.

    Cross-column inconsistencies

    Encode relationships that should always hold:

    SELECT OrderID, OrderDate, ShipDate, Status
    FROM dbo.[Order]
    WHERE ShipDate < OrderDate
       OR (Status = 'Shipped' AND ShipDate IS NULL)
       OR (Status = 'Pending' AND ShipDate IS NOT NULL);
    

    For rules such as “each postal code must always map to the same state,” group by the determinant and count distinct dependent values:

    SELECT PostalCode, COUNT(DISTINCT StateCode) AS StateCount
    FROM dbo.Address
    GROUP BY PostalCode
    HAVING COUNT(DISTINCT StateCode) > 1;
    

    SSIS calls this a Functional Dependency Profile. Candidate Key, Functional Dependency, and Value Inclusion profiles cover uniqueness, cross-column consistency, and cross-table relationships respectively ^1^.

    3. Profile unfamiliar SQL Server datasets in SSIS

    In SSDT/Visual Studio:

    1. Add a Data Profiling Task to the package Control Flow.
    2. Open the task and, on General, select an XML output file or package variable.
    3. For initial discovery, select Quick Profile for a table or view.
    4. On Profile Requests, configure targeted profiles:
      • Column Null Ratio — missing values
      • Candidate Key — duplicates
      • Length/Pattern/Value Distribution — malformed or unexpected values
      • Column Statistics — abnormal numeric or date ranges
      • Functional Dependency — inconsistent column relationships
      • Value Inclusion — unmatched foreign-key-like values
    5. Run the package and open the output with Data Profile Viewer.

    The task supports SQL Server data only—not file-based or third-party sources—and its execution account requires read/write permissions, including CREATE TABLE permission in tempdb ^2^.

    The viewer shows summaries, details, and violations. For Candidate Key, Functional Dependency, and Value Inclusion profiles, the Details pane exposes relationship violations and can drill down to matching source rows when the source remains available ^3^.

    4. Operationalize the checks

    • Store thresholds and rule ownership in a configuration table.
    • Write violations to a history table with batch ID and detection time.
    • Distinguish warning rules from reject rules.
    • Run checks against staging tables before loading production targets.
    • Fail or redirect the SSIS load when reject-rule counts exceed thresholds.
    • Add database PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK, and NOT NULL constraints after existing data is clean; profiling detects issues, while constraints prevent recurrence.
    • Protect profiling output because it can contain sensitive source data ^2^.

    References

    1. Data Profiling Task
    2. Setup of the Data Profiling Task
    3. Data Profile Viewer
    AI-generated content may be incorrect. Read our transparency notes for more information.

    Was this answer helpful?

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.