100 Essential SQL Queries Explained
100 Essential SQL Queries Explained
Primary keys enforce unique identification of records, while foreign keys maintain referential integrity by linking tables. They ensure valid and related data entries across tables, preventing orphaned records, but may complicate data manipulation due to constraints .
Using the ALTER TABLE statement allows modification of column data types, e.g., ALTER TABLE courses MODIFY title VARCHAR(200). This operation can lead to data truncation if the new type has a smaller size than existing data .
Creating views (e.g., CREATE VIEW young_students AS SELECT * FROM students WHERE age < 22) structures data presentation and simplifies complex queries. Views can enhance performance by optimizing query execution plans but may degrade performance if poorly designed due to additional abstraction layers .
UNION removes duplicate records whereas UNION ALL includes duplicates. UNION may lead to slower performance due to the duplicate removal process, while UNION ALL is faster as it processes records directly. UNION ALL is preferable when all records are needed .
JOIN operations (e.g., INNER, LEFT, RIGHT) allow drawing connections between tables, enriching data queries. For instance, SELECT s.name, c.title FROM students s JOIN enrollments e ON s.id = e.student_id JOIN courses c ON e.course_id = c.course_id. Complexity arises from ensuring correct joins and managing result set duplication or NULL-entry scenarios .
Aggregate functions like AVG() and SUM(), when used with GROUP BY, break data into subsets, applying calculations to each group (e.g., SELECT age, COUNT(*) FROM students GROUP BY age). This facilitates detailed analysis of distinct groups, though grouping can complicate composite analyses .
TRUNCATE TABLE is a high-level, non-transactional operation that quickly removes all rows without logging individual row deletions, resetting identity values, and removing indexes. DELETE FROM table can be transactional, allowing selective row removal with constraints and triggers intact .
Indexes improve query performance for operations like SELECT by reducing data retrieval time. They are particularly beneficial for large datasets with frequent read requires. Limitations include increased storage requirements and slower INSERT/UPDATE operations due to index maintenance .
The CASE statement offers flexible multi-condition logic, handling complex when/then scenarios elegantly within SELECT statements, as seen in SELECT name, CASE WHEN age < 21 THEN 'Teen' ELSE 'Adult' END AS category FROM students. It provides greater readability and reduces code redundancy unlike simple IF conditions .
A RIGHT JOIN retains all records from the right table and matched records from the left table, filling with NULLs as necessary. It is useful when you need all entries from the right table regardless of matches. A LEFT JOIN contrasts this by retaining all left table records .