Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple refactoring sql query

I have the table with rows:

ID          CountryCode Status
----------- ----------- -----------
2           PL          1
3           PL          2
4           EN          1
5           EN          1

and by the query

SELECT *
  FROM [TestTable]
  WHERE Status = 1 AND CountryCode NOT IN (SELECT CountryCode
  FROM [TestTable]
  WHERE Status != 1)

I get all countrycodes which hasn't status value = 2

ID          CountryCode Status
----------- ----------- -----------
4           EN          1
5           EN          1

I feel that this query could be more simpler and clearer.

How can I change it?

Best regards

EDIT

PL can't be in result because has a record with status 2

EDIT

Script to create and fill table:

USE [DatabaseName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TestTable](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [CountryCode] [nvarchar](2) NOT NULL,
    [Status] [int] NOT NULL
) ON [PRIMARY]

INSERT INTO dbo.TestTable
          ( CountryCode, Status )
  VALUES  ( 'PL', -- CountryCode - nvarchar(2)
            1  -- Status - int
            )

INSERT INTO dbo.TestTable
          ( CountryCode, Status )
  VALUES  ( 'PL', -- CountryCode - nvarchar(2)
            2  -- Status - int
            )

INSERT INTO dbo.TestTable
          ( CountryCode, Status )
  VALUES  ( 'EN', -- CountryCode - nvarchar(2)
            1  -- Status - int
            )
INSERT INTO dbo.TestTable
          ( CountryCode, Status )
  VALUES  ( 'EN', -- CountryCode - nvarchar(2)
            1  -- Status - int
            )
like image 607
user278618 Avatar asked Feb 15 '26 02:02

user278618


1 Answers

First: Never use SELECT * in often used code. Especially in production. Call out your columns.

Soap-Box over.

Note: i haven't tried this, and I don't currently have the management studio installed, so I can't test it. But I think you want something like this:

Select Id, CountryCode, Status
From [TestTable] t
Where Status <> 2
And Not Exists(select status from [TestTable] t2 
                             where t2.Status = 2 
                             and t2.CountryCode = tt.CountryCode)

At the least, you've got the right idea: if you only want the CountryCodes which do not (on any record) correspond to Status = 2, you need to get everything with status 1, and then exclude any existing rows with have a matching row with status 2. I may have the specific syntax for Not Exists incorrect, though.

like image 99
AllenG Avatar answered Feb 16 '26 15:02

AllenG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!