Câu hỏi phỏng vấn SQL
Câu hỏi

Define a Temp Table

Câu trả lời

A temporary table, often referred to as a "temp table," is a type of table in SQL that is used to store data temporarily during the execution of a query or a series of queries. Temp tables are particularly useful for intermediate storage of data that is needed only for the duration of a session or transaction. Here are some key points about temp tables:

Characteristics of Temp Tables

  1. Scope and Lifespan:

    • Local Temporary Tables: These are prefixed with a single hash symbol (#). They are visible only within the session that created them and are automatically dropped when the session ends.
    • Global Temporary Tables: These are prefixed with a double hash symbol (##). They are visible to all sessions and are dropped when the session that created them ends and the last active session referencing them is closed.
  2. Creation and Usage:

    • Temp tables can be created using the CREATE TABLE statement with the appropriate prefix (# or ##).
    • They can be populated using INSERT INTO or SELECT INTO statements.
    • Temp tables support typical SQL operations such as SELECT, INSERT, UPDATE, and DELETE.
  3. Performance:

    • Temp tables are stored in the tempdb database, which is optimized for temporary storage and operations.
    • They can improve performance by reducing the need for repeated complex calculations or data transformations.
    • Temp tables can have indexes, constraints, and statistics, similar to permanent tables, which can further enhance performance for certain operations.
  4. Use Cases:

    • Intermediate Storage: Useful for storing intermediate results during complex data transformations or ETL (Extract, Transform, Load) processes.
    • Query Simplification: Breaking down complex queries into simpler steps by storing intermediate results in temp tables.
    • Data Isolation: Ensuring that temporary data used in one session does not interfere with data in other sessions.

Example of Creating and Using a Temp Table

sql Copy
-- Create a local temporary table
CREATE TABLE #TempStudents (
    StudentID INT PRIMARY KEY,
    FirstName NVARCHAR(50),
    LastName NVARCHAR(50),
    Age INT
);

-- Insert data into the temp table
INSERT INTO #TempStudents (StudentID, FirstName, LastName, Age)
VALUES (1, 'John', 'Doe', 20);

-- Select data from the temp table
SELECT * FROM #TempStudents;

-- Drop the temp table
DROP TABLE #TempStudents;

Advantages and Disadvantages

**Adv...

entry

entry

Gợi ý câu hỏi phỏng vấn

senior

What is the difference among UNION , MINUS and INTERSECT ?

middle

What is Collation?

middle

What is the difference between WHERE clause and HAVING clause?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào