what this constrain meaning ?

ahmed salah 3,216 Reputation points
2021-10-28T15:34:57.1+00:00

I work on sql server 2012 i see constrain but i don't know what is meaning

ALTER TABLE [Parts].[TradeCodes] ADD  CONSTRAINT [UC_PartCode] UNIQUE NONCLUSTERED 
(
    [PartID] ASC,
    [CodeTypeID] ASC,
    [PartLevel] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

so what is benefit from code above

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,493 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,705 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Guoxiong 8,206 Reputation points
    2021-10-28T15:40:35.633+00:00

    That is the unique constraint so that the combination of those three columns should be unique. It is not allowed to have the duplicates. See UNIQUE Constraints for more details.

    0 comments No comments

  2. MelissaMa-MSFT 24,216 Reputation points
    2021-10-29T01:15:30.1+00:00

    Hi @ahmed salah ,

    Constraints in SQL Server are predefined rules and restrictions that are enforced in a single column or multiple columns, regarding the values allowed in the columns, to maintain the integrity, accuracy, and reliability of that column’s data.

    In other words, if the inserted data meets the constraint rule, it will be inserted successfully. If the inserted data violates the defined constraint, the insert operation will be aborted.

    There are six main constraints:

    • SQL NOT NULL
    • UNIQUE
    • PRIMARY KEY
    • FOREIGN KEY
    • CHECK
    • DEFAULT

    In your example, it could be UNIQUE constraint.

    The UNIQUE constraint in SQL Server ensures that you do not have duplicate values in a single column or combination of columns. These columns should be part of the UNIQUE constraints.

    [PartID] ASC,
    [CodeTypeID] ASC,
    [PartLevel] ASC

    So your constraint was added to make sure that the combination of above three columns should be unique, otherwise it could report errors.

    Best regards,
    Melissa


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

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