What SQL constraints and Types and when to use
Loading
What SQL constraints and Types and when to use
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jaish MathewsPosted Jan 19, 2025, 4:57 PM
SQL constraints are foundational to creating robust and reliable databases. Here's an overview of each:
SQL Constraints
Constraints enforce rules on data in tables, ensuring accuracy and integrity. Common constraints include:
1. NOT NULL
NULLvalue.Example:
2. UNIQUE
Example:
3. PRIMARY KEY
NOT NULLandUNIQUE, uniquely identifying each row.IDcolumns).Example:
4. FOREIGN KEY
Example:
5. CHECK
Example:
6. DEFAULT
Example:
7. INDEX
Example:
Choosing the appropriate constraint and type depends on your application's requirements. Constraints ensure data accuracy and integrity, while data types dictate how data is stored and queried efficiently.
Rajanikant HawaldarPosted Jan 19, 2025, 3:40 PM
Hi,
Please refer below articles.
https://www.c-sharpcorner.com/article/an-easy-way-to-understand-constraints-in-sql-server/
https://www.c-sharpcorner.com/UploadFile/f0b2ed/constraints-in-sql-server/
Amira BedhiafiPosted Jan 19, 2025, 11:28 AM
They are rules applied to table columns to ensure the validity, integrity, and consistency of the data.
NOT NULL Constraint: a column cannot have a NULL value. For example, in an
Employeestable, theFirstNameandLastNamefields should not be NULL, as every employee must have a first and last name.UNIQUE Constraint: all values in a column are distinct. you can use it when a column must store unique values, such as an email address in a
Userstable.PRIMARY KEY Constraint: combination of NOT NULL and UNIQUE, you can assign it to a column or a set of columns that serve as the unique identifier for table records, like
EmployeeIDin anEmployeestable. Each table should have one primary key.FOREIGN KEY Constraint: establishes a relationship between columns in two tables, enforcing referential integrity. In other words we use it to link related data between tables. An
Orderstable may have aCustomerIDcolumn that references theCustomerIDin aCustomerstable to make sure that every order is associated with a valid customer.CHECK Constraint: you can make sure that all values in a column satisfy a specific condition.
For example, aSalarycolumn can have a CHECK constraint to be within a reasonable range, such as greater than zero.DEFAULT Constraint: provides a default value for a column when none is specified. For example, you can set up a default value of
GETDATE()for anOrderDatecolumn to record the date an order was placed.