---
title: "Help with Writing a Query to Compare Two Tables in SQL Server"  
description: "Help with Writing a Query to Compare Two Tables in SQL Server"  
author: "Ravi Vishwakarma"  
published: 2024-07-16  
updated: 2024-07-16  
canonical: https://www.mindstick.com/forum/160926/help-with-writing-a-query-to-compare-two-tables-in-sql-server  
category: "SQL Server"  
tags: ["database", "sql server", "sql server 2008", "sql server 2012", "sql server 2022"]  
reading_time: 2 minutes  

---

# Help with Writing a Query to Compare Two Tables in SQL Server

I have [two tables](https://www.mindstick.com/forum/159646/how-to-join-two-tables-in-oracle-to-get-single-line-results), `OldCustomers` and `NewCustomers`, and I need to find [records](https://www.mindstick.com/forum/34640/how-to-create-a-stored-procedure-for-display-all-records) that are [present](https://answers.mindstick.com/qa/96635/explain-about-the-various-features-present-in-ms-access) in `OldCustomers` but not in `NewCustomers`. How can I write this [query](https://www.mindstick.com/blog/202/sub-query-in-sqlserver)?

## Replies

### Reply by Ravi Vishwakarma

To find records that are present in the `OldCustomers` table but not in the `NewCustomers` table, you can use a `LEFT JOIN` combined with a `WHERE` clause to identify records in `OldCustomers` that do not have corresponding records in `NewCustomers`.

Here’s a general query for this scenario:

```plaintext
SELECT o.*
FROM OldCustomers o
LEFT JOIN NewCustomers n
    ON o.CustomerID = n.CustomerID
WHERE n.CustomerID IS NULL;
```

In this query:

- `o` is an alias for `OldCustomers`.
- `n` is an alias for `NewCustomers`.
- The `LEFT JOIN` ensures that all records from `OldCustomers` are included, even if there is no matching record in `NewCustomers`.
- The `WHERE n.CustomerID IS NULL` clause filters out records that have matches in `NewCustomers`, leaving only those that do not.

If your [tables](https://www.mindstick.com/articles/336597/introduction-of-html-tables-for-web-development) have multiple columns that need to be checked for matching (e.g., `CustomerID`, `Name`, `Email`), you can adjust the `ON` clause accordingly:

```plaintext
SELECT o.*
FROM OldCustomers o
LEFT JOIN NewCustomers n
    ON o.CustomerID = n.CustomerID
   AND o.Name = n.Name
   AND o.Email = n.Email
WHERE n.CustomerID IS NULL;
```

This ensures that a record is considered a match only if all specified columns match. Adjust the column names as necessary based on the structure of your tables.


---

Original Source: https://www.mindstick.com/forum/160926/help-with-writing-a-query-to-compare-two-tables-in-sql-server

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
