In SQL, a view is a virtual table based on the result-set of an SQL statement. It's like a table in that it has rows and columns, but it doesn't store any data itself. Instead, it acts like a filter on one or more underlying tables, presenting data as if it were a single table.
Here's a more detailed breakdown:
- Virtual Table: A view doesn't physically store data; it's a stored query.
- Based on a Query: The data in a view is derived from the results of a SELECT statement that defines the view.
- Like a Table: You can query, insert, update, and delete data through a view as if it were a regular table.
- Security and Simplification: Views can be used for security purposes by limiting user access to specific data subsets. They can also simplify complex queries by combining multiple tables into a single, user-friendly view.
- Dynamic Updates: Changes to the underlying tables are reflected in the view's data.
In SQL Server, a trigger is a special type of stored procedure that automatically executes when a specific event occurs within the database. These events are typically data manipulation language (DML) operations like INSERT, UPDATE, or DELETE on a table. Triggers help automate tasks, enforce data integrity, and maintain accurate records of database activities.
Elaboration
- Purpose: Triggers are designed to respond to specific events within the database, allowing you to automatically execute code in reaction to those events.
- DML Triggers: These are the most common type of trigger and are associated with tables or views. They fire when a DML operation is performed on that table or view.
- Event-Driven: Triggers are event-driven, meaning they are activated by a specific event occurring in the database.
- Data Integrity and Business Rules: Triggers can be used to enforce business rules and data integrity by automatically executing code that validates or modifies data during an INSERT, UPDATE, or DELETE operation.
Examples
- Automatically updating an audit log table whenever data is modified in another table.
- Preventing invalid data from being inserted into a table by checking constraints within the trigger.
- Triggering a notification when a specific event occurs, such as a large number of orders being placed.
In SQL Server, DELETE and TRUNCATE are both used to remove data from a table, but they differ in their approach and impact. DELETE removes rows based on specified conditions and logs each deleted row, allowing for rollback within a transaction. TRUNCATE removes all rows from a table faster by deallocating data pages, doesn't log individual deletions, and is typically not rollbackable.
Key Differences
Deletion Method
- DELETE: Removes individual rows based on a
WHEREclause condition. Logs each deleted row, allowing for rollbacks within a transaction. - TRUNCATE: Removes all rows in the table by deallocating the data pages. It does not log individual row deletions and is not typically rollbackable.
Logging
- DELETE: Logs each deleted row, consuming more transaction log space.
- TRUNCATE: Logs only the page deallocation, using less transaction log space.
Speed
- DELETE: Slower due to row-by-row deletion and transaction logging.
- TRUNCATE: Faster as it deallocates the entire table's data pages in one operation.
Rollback
- DELETE: Can be rolled back within a transaction.
- TRUNCATE: Typically not rollbackable.
Triggers
- DELETE: Triggers defined on the table are fired for each deleted row.
- TRUNCATE: Triggers are not fired.
Constraints
- DELETE: Respects constraints (e.g., foreign keys) during deletion.
- TRUNCATE: Bypasses constraints, making it faster.
Use Cases
- DELETE: Used for removing specific rows or subsets of data based on conditions.
- TRUNCATE: Used for resetting a table to an empty state or for quickly removing all data when rollback is not needed.
Summary
DELETE is more flexible for removing specific rows, while TRUNCATE is faster for removing all rows when rollback is not a concern.
In SQL Server, there are several types of joins, each designed to combine data from two or more tables based on a specific relationship. The main types are: Inner Join, Left Outer Join, Right Outer Join, Full Outer Join, and Cross Join. Additionally, Self Join, while not a distinct join type, can be implemented using any of the joins mentioned above.
Join Types Breakdown
Inner Join
Returns only the rows where the join condition is met in both tables.
Left Outer Join (or Left Join)
Returns all rows from the left table and the matching rows from the right table.
If a match isn't found, NULL values are returned for the right table columns.
Right Outer Join (or Right Join)
Returns all rows from the right table and the matching rows from the left table.
If a match isn't found, NULL values are returned for the left table columns.
Full Outer Join (or Full Join)
Returns all rows from both tables.
If a match is found, the matching values are returned; otherwise, NULL values are used for the missing columns.
Cross Join
Returns the Cartesian product of the two tables, meaning all possible combinations of rows from both tables.
Self Join
Joins a table to itself. This is useful for comparing rows within the same table. A Self Join can be implemented using Inner Join, Outer Join, or Cross Join depending on the specific requirements.
In SQL Server, WHERE and HAVING are both used for filtering data, but they apply to different stages of the query process. WHERE filters rows before any grouping or aggregation, while HAVING filters grouped data after aggregation. In essence, WHERE works on individual rows, and HAVING works on groups of rows.
Detailed Breakdown
WHERE Clause
- Filters rows based on conditions that apply to individual rows in the table.
- Applies before the
GROUP BYclause. - Used with standard operators and comparisons.
-
Examples:
WHERE salary > 50000WHERE department = 'IT'
HAVING Clause
- Filters groups of rows based on conditions that apply to aggregated values (e.g.,
SUM(),AVG(),COUNT()). - Applies after the
GROUP BYclause. - Must be used with aggregate functions.
-
Examples:
HAVING AVG(salary) > 60000HAVING COUNT(*) > 5
In Simpler Terms
- Think of WHERE as filtering the data before you group it.
- Think of HAVING as filtering the groups after they are created.
- If you want to filter rows based on individual column values, use WHERE.
- If you want to filter groups based on aggregate values of those groups, use HAVING.
In SQL Server, indexing refers to creating special lookup tables that speed up data retrieval operations. These indexes act like a table of contents, allowing the database server to quickly locate data within a table without scanning every row. By using indexes, you can significantly improve query performance, especially for tables with large amounts of data.
Key Concepts
Purpose
Indexes help the database engine quickly find the specific rows that match a query's criteria.
Speed
Without indexes, the database would have to scan every row in a table to find the data you're looking for, which can be slow for large tables.
Structure
Indexes are typically implemented as B-tree structures, which are efficient data structures for searching.
Columns
Indexes are usually created on columns that are frequently used in WHERE clauses or JOIN conditions in queries.
Types
SQL Server supports various index types, including:
- Clustered Indexes
- Nonclustered Indexes
How It Works
- Data Organization: An index stores a sorted representation of the indexed columns, along with pointers to the actual data rows in the table.
- Efficient Search: When a query uses a column that is indexed, the database engine can use the index to quickly find the rows that match the query’s criteria.
- Reduced Full Table Scans: Indexes help avoid scanning the entire table, saving time and system resources.
Benefits of Using Indexes
- Faster Query Performance: Significantly reduces the time it takes to retrieve data.
- Improved Application Responsiveness: Faster queries lead to a better user experience.
- Reduced Disk I/O: Less data needs to be read from disk when using indexes.
Considerations
Over-Indexing
Adding too many indexes can slow down INSERT, UPDATE, and DELETE operations and consume extra storage.
Maintenance
Indexes need to be maintained. They can become fragmented or outdated if the underlying data changes frequently, which may require regular rebuilding or reorganizing.
RANK(): Gaps in ranking
DENSE_RANK(): No gaps
🔹 Miscellaneous / Scenario-Based
sp_helpdb 'DatabaseName'KILL <SPID>sp_who2sp_who2, sys.dm_exec_requests, and review lock chains.