Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Constraints In Sql in SQL

Constraints In Sql in SQL

? Constraints in SQL

Constraints are rules applied to columns in a database table to enforce data integrity and validity. They restrict the type of data that can be inserted into a table.


? Common Types of Constraints

ConstraintDescriptionExample
PRIMARY KEYUniquely identifies each record in a table.PRIMARY KEY (id)
FOREIGN KEYEnsures referential integrity between tables.FOREIGN KEY (dept_id) REFERENCES departments(id)
UNIQUEEnsures all values in a column are unique.UNIQUE (email)
NOT NULLEnsures a column cannot have NULL values.name VARCHAR(100) NOT NULL
CHECKEnsures values meet a specific condition.CHECK (age >= 18)
DEFAULTSets a default value for a column.status VARCHAR(10) DEFAULT 'active'

? How to Add Constraints

During Table Creation

CREATE TABLE employees (    id INT PRIMARY KEY,    name VARCHAR(100) NOT NULL,    email VARCHAR(100) UNIQUE,    age INT CHECK (age >= 18),    dept_id INT,    FOREIGN KEY (dept_id) REFERENCES departments(id));

On Existing Table

ALTER TABLE employeesADD CONSTRAINT chk_age CHECK (age >= 18);

? Why Use Constraints?

  • Maintain accuracy and reliability of data.

  • Prevent invalid or inconsistent data entry.

  • Define relationships between tables.


If you want examples of specific constraints or how to drop constraints, just ask!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql