β Useful SQL Concepts You Should Know
Essential database concepts to improve performance, integrity, and scalability π
1οΈβ£ Constraints in SQL
Constraints are rules applied to table columns to maintain data accuracy and integrity.
- PRIMARY KEY β Uniquely identifies each row in a table
- FOREIGN KEY β Establishes a relationship with another table
- UNIQUE β Ensures all column values are different
- NOT NULL β Prevents empty (NULL) values
- CHECK β Validates data before insertion or update
2οΈβ£ SQL Views
Views are virtual tables created using SQL queries. They simplify complex queries and improve security.
CREATE VIEW top_students AS
SELECT name, marks
FROM students
WHERE marks > 90;
3οΈβ£ Indexing
Indexes significantly improve query performance by allowing faster data retrieval.
CREATE INDEX idx_name
ON employees(name);
4οΈβ£ SQL Transactions
Transactions ensure that multiple operations are executed safely and maintain database consistency.
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
5οΈβ£ Triggers
Triggers automatically execute SQL code in response to database events like INSERT, UPDATE, or DELETE.
CREATE TRIGGER log_update
AFTER UPDATE ON employees
FOR EACH ROW
INSERT INTO logs(action)
VALUES ('Employee updated');
6οΈβ£ Stored Procedures
Stored procedures are reusable SQL blocks that improve performance and reduce redundancy.
CREATE PROCEDURE getTopStudents()
BEGIN
SELECT *
FROM students
WHERE marks > 90;
END;
7οΈβ£ Common Table Expressions (CTEs)
CTEs are temporary result sets that make complex queries easier to read and maintain.
WITH dept_count AS (
SELECT department, COUNT(*) AS total
FROM employees
GROUP BY department
)
SELECT *
FROM dept_count;
Comments (0)
No comments yet
Be the first to share your thoughts!
Leave a Comment