Ensure Data Integrity with Primary, Foreign Keys, and More
Master SQL data types and constraints in this beginner-friendly guide. Learn how to use PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK, default values, and auto-increment columns. Practice adding constraints to employee tables to ensure data integrity.
1. Introduction
Data types and constraints are essential for maintaining data integrity and accuracy in SQL databases.
- Data types define the kind of data a column can store (e.g., integer, text, date).
- Constraints enforce rules on data to prevent invalid entries.
Key Points:
- Constraints help avoid duplicate, null, or inconsistent data.
- Default values and auto-increment columns simplify data entry and unique identifiers.
2. SQL Data Types
| Data TypeDescription | |
| INT / BIGINT | Integer numbers |
| DECIMAL / NUMERIC | Fixed-point numbers |
| FLOAT / REAL | Approximate numbers |
| VARCHAR(n) | Variable-length string |
| CHAR(n) | Fixed-length string |
| DATE / DATETIME | Date and time |
| BOOLEAN | TRUE/FALSE values |
3. SQL Constraints
3.1 PRIMARY KEY
- Uniquely identifies each row in a table.
- Cannot be NULL.
3.2 FOREIGN KEY
- Maintains referential integrity between two tables.
3.3 UNIQUE
- Ensures column values are unique.
3.4 NOT NULL
- Ensures column cannot have NULL values.
3.5 CHECK
- Ensures column values meet a specific condition.
4. Default Values and Auto-Increment
4.1 Default Values
4.2 Identity / Auto-Increment Columns
- Automatically generate unique numbers for each row.
5. Practical Exercises
- Add a PRIMARY KEY to the Employees table.
- Create a FOREIGN KEY to link Employees to Departments.
- Add a UNIQUE constraint on the Email column.
- Apply NOT NULL to Name and Department columns.
- Add a CHECK constraint to ensure Salary > 0.
- Set a default value for the Country column.
- Convert ID column to auto-increment for automatic numbering.
6. Tips for Beginners
- Always define a PRIMARY KEY for each table.
- Use FOREIGN KEYS to maintain relational integrity.
- Apply UNIQUE and NOT NULL to prevent bad data.
- Use CHECK constraints for business rules like valid salaries or ages.
- Use default values and auto-increment to simplify inserts.
- Plan constraints before populating large tables for efficiency.
Next Step: After mastering data types and constraints, the next module is Advanced Data Handling in SQL, where you’ll learn temporary tables, table variables, bulk insert, and data import/export.