SQL Most frequent Interview questions
Basic SQL Queries
What is SQL, and what are its major components?
Answer: SQL (Structured Query Language) is used for managing and manipulating relational databases. Its major components include:
DDL (Data Definition Language): Defines database schema (e.g., CREATE, ALTER, DROP).
DML (Data Manipulation Language): Manages data within schema objects (e.g., SELECT, INSERT, UPDATE, DELETE).
DCL (Data Control Language): Controls access to data (e.g., GRANT, REVOKE).
TCL (Transaction Control Language): Manages transactions (e.g., COMMIT, ROLLBACK).
How do you retrieve all columns from a table?
Answer: Use the SELECT statement with an asterisk:
What is the difference between WHERE and HAVING clauses?
Answer:
WHERE: Filters rows before grouping; used with SELECT, UPDATE, DELETE.
HAVING: Filters groups after aggregation; used with GROUP BY.
How do you sort query results?
Answer: Use the ORDER BY clause:
Explain how to use the LIKE operator.
Answer: The LIKE operator is used for pattern matching in a WHERE clause:
%represents zero or more characters._represents a single character.
Advanced SQL Queries
What are JOINs in SQL, and what are the different types?
Answer: JOINs combine rows from two or more tables based on related columns. Types include:
INNER JOIN: Returns matching rows from both tables.
LEFT (OUTER) JOIN: Returns all rows from the left table and matching rows from the right table.
RIGHT (OUTER) JOIN: Returns all rows from the right table and matching rows from the left table.
FULL (OUTER) JOIN: Returns all rows when there is a match in either table.
How do you find the second highest salary from a table?
Answer: Use the LIMIT and OFFSET clauses or a subquery:
What is a subquery, and how is it used?
Answer: A subquery is a query within another query, used for complex filtering and transformations:
Explain the use of the CASE statement in SQL.
Answer: The CASE statement performs conditional logic in queries:
How do you create and use temporary tables?
Answer: Temporary tables store intermediate results and exist only during the session:
Insert data and use it as a regular table.
Data Aggregation and Analysis
What are aggregate functions in SQL, and can you name a few?
Answer: Aggregate functions perform calculations on a set of values and return a single value:
COUNT: Counts rows.
SUM: Adds numeric values.
AVG: Calculates average value.
MAX/MIN: Finds maximum/minimum value.
How do you group data in SQL?
Answer: Use the GROUP BY clause:
Explain the difference between UNION and UNION ALL.
Answer:
UNION: Combines results of two queries, removing duplicates.
UNION ALL: Combines results of two queries, including duplicates.
How do you handle NULL values in SQL?
Answer: Use functions like IS NULL, IS NOT NULL, COALESCE, and NVL:
What is the purpose of the DISTINCT keyword?
Answer: DISTINCT removes duplicate rows in the result set:
Database Design and Optimization
What are primary keys and foreign keys in SQL?
Answer:
Primary Key: A unique identifier for each record in a table.
Foreign Key: A reference to the primary key in another table to establish relationships.
How do you create indexes in SQL, and why are they important?
Answer: Indexes improve query performance by speeding up data retrieval:
What is normalization, and why is it important?
Answer: Normalization organizes database tables to reduce data redundancy and improve data integrity. It involves dividing large tables into smaller, related ones.
Explain the concept of database transactions.
Answer: Transactions are a sequence of operations performed as a single unit of work. They ensure data integrity using ACID properties (Atomicity, Consistency, Isolation, Durability):
BEGIN TRANSACTION: Start a transaction.
COMMIT: Save changes.
ROLLBACK: Revert changes.
How do you optimize SQL queries for performance?
Answer: Tips for optimizing SQL queries:
Use indexes on columns used in WHERE, JOIN, and ORDER BY clauses.
Avoid SELECT *; specify columns.
Use appropriate JOINs and avoid unnecessary subqueries.
Limit the number of returned rows using LIMIT or TOP.
Use query execution plans to identify bottlenecks.
Advanced SQL Concepts
What is a Stored Procedure, and how do you create one?
Answer: Stored procedures are precompiled SQL code stored in the database, used to perform tasks and encapsulate logic:
Explain Triggers and how they are used in SQL.
Answer: Triggers automatically execute specified SQL code in response to certain events (e.g., INSERT, UPDATE, DELETE) on a table:
asic SQL Queries
What is SQL?
Answer: SQL (Structured Query Language) is a standard language used to manage and manipulate relational databases.
How do you retrieve all columns from a table?
Answer: Use the
SELECTstatement.sqlSELECT * FROM table_name;How do you filter records based on a condition?
Answer: Use the
WHEREclause.sqlSELECT * FROM table_name WHERE condition;Explain the
GROUP BYclause.Answer:
GROUP BYgroups rows that have the same values in specified columns into summary rows.sqlSELECT column1, COUNT(*) FROM table_name GROUP BY column1;What is the purpose of the
HAVINGclause?Answer:
HAVINGis used to filter groups based on conditions, similar toWHEREbut for groups.sqlSELECT column1, COUNT(*) FROM table_name GROUP BY column1 HAVING COUNT(*) > 1;
Advanced SQL Concepts
What are
JOINoperations in SQL?Answer:
JOINoperations combine rows from two or more tables based on related columns.INNER JOIN: Returns matching rows from both tables.
sqlSELECT * FROM table1 INNER JOIN table2 ON table1.common_column = table2.common_column;Explain the difference between
INNER JOINandLEFT JOIN.Answer:
INNER JOIN: Returns rows with matching values in both tables.
LEFT JOIN: Returns all rows from the left table and matching rows from the right table. Non-matching rows from the right table return NULL.
sqlSELECT * FROM table1 LEFT JOIN table2 ON table1.common_column = table2.common_column;What is a
UNIONoperator?Answer:
UNIONcombines the results of two or more SELECT queries, removing duplicates.sqlSELECT column1 FROM table1 UNION SELECT column1 FROM table2;Describe a
SUBQUERYand its use.Answer: A
SUBQUERYis a query nested within another query. Used for complex filtering and calculations.sqlSELECT * FROM table1 WHERE column1 = (SELECT MAX(column1) FROM table2);What is a
CROSS JOIN?Answer:
CROSS JOINreturns the Cartesian product of two tables, combining all rows from both tables.sqlSELECT * FROM table1 CROSS JOIN table2;
Database Design and Management
Explain
Normalizationin databases.Answer:
Normalizationorganizes data to reduce redundancy and improve data integrity. Includes several normal forms (1NF, 2NF, 3NF).What is
Denormalizationand when would you use it?Answer:
Denormalizationadds redundancy to improve read performance, often used in data warehousing.Define a
Primary Key.Answer: A
Primary Keyuniquely identifies each record in a table and cannot be NULL.sqlCREATE TABLE table_name (id INT PRIMARY KEY, column1 TEXT);What is a
Foreign Key?Answer: A
Foreign Keylinks one table to another, establishing a relationship between them.sqlCREATE TABLE child_table (id INT, parent_id INT, FOREIGN KEY (parent_id) REFERENCES parent_table(id));Describe the difference between
ACIDproperties andBASEproperties.Answer:
ACID: Atomicity, Consistency, Isolation, Durability; ensures reliable transactions.
BASE: Basically Available, Soft state, Eventual consistency; used in NoSQL databases for scalability and flexibility.
SQL Functions and Aggregate Operations
What are
Aggregate Functions?Answer: Functions that perform calculations on multiple rows and return a single value (e.g.,
SUM,AVG,COUNT,MAX,MIN).sqlSELECT AVG(column1) FROM table_name;Explain the
CASEstatement in SQL.Answer:
CASEallows conditional logic in SQL queries.sqlSELECT column1, CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE default_result END FROM table_name;What is the
COALESCEfunction?Answer:
COALESCEreturns the first non-NULL value in a list of arguments.sqlSELECT COALESCE(column1, column2, 'default') FROM table_name;How do you perform a
STRING CONCATENATIONin SQL?Answer: Use the
||operator orCONCATfunction.sqlSELECT column1 || ' ' || column2 AS concatenated FROM table_name; -- or SELECT CONCAT(column1, ' ', column2) AS concatenated FROM table_name;What is the
RANK()function and how is it used?Answer:
RANK()assigns a rank to each row within a partition of a result set.sqlSELECT column1, RANK() OVER (PARTITION BY column2 ORDER BY column3) AS rank FROM table_name;
SQL Performance and Optimization
How do you improve SQL query performance?
Answer: Techniques include:
Using indexes.
Writing efficient joins.
Avoiding unnecessary columns in SELECT.
Limiting result sets with
WHEREandLIMIT.Using query execution plans.
What are
Indexesand their types?Answer: Indexes improve query performance by speeding up data retrieval. Types include:
B-tree indexes.
Hash indexes.
Bitmap indexes.
Explain the concept of an
Execution Plan.Answer: An execution plan shows how SQL Server executes a query, including indexes used, join types, and query cost. It's used for performance tuning.
What is
Partitioningin SQL databases?Answer: Partitioning divides large tables into smaller, manageable pieces called partitions, improving query performance and manageability.
sqlCREATE TABLE table_name PARTITION BY RANGE (column_name);Describe
Database Caching.Answer: Database caching stores frequently accessed data in memory to reduce query execution time and improve performance.
Transactional SQL
What is a
Transactionin SQL?Answer: A transaction is a sequence of operations performed as a single logical unit of work, ensuring data integrity.
sqlBEGIN TRANSACTION; -- SQL operations COMMIT; -- or ROLLBACK;Explain
SAVEPOINTin transactions.Answer:
SAVEPOINTcreates a point within a transaction to which you can later roll back.sqlSAVEPOINT savepoint_name; -- SQL operations ROLLBACK TO savepoint_name;What is
Isolation Levelin SQL transactions?Answer: Isolation level determines the visibility of changes made in a transaction to other transactions. Levels include:
Read Uncommitted
Read Committed
Repeatable Read
Serializable
Describe the
ROLLBACKcommand.Answer:
ROLLBACKundoes transactions that have not been committed, reverting the database to its previous state.sqlROLLBACK;What are
Triggersin SQL?Answer: Triggers are automated actions executed in response to specific events on a table or view (e.g.,
INSERT,UPDATE,DELETE).sqlCREATE TRIGGER trigger_name AFTER INSERT ON table_name FOR EACH ROW BEGIN -- Trigger logic END;
Advanced SQL Queries and Functions
What is the difference between
UNIONandUNION ALL?Answer:
UNION: Combines results of two queries, removing duplicates.
UNION ALL: Combines results, including duplicates.
sqlSELECT column1 FROM table1 UNION SELECT column1 FROM table2; SELECT column1 FROM table1 UNION ALL SELECT column1 FROM table2;How do you use the
EXISTSoperator in SQL?Answer:
EXISTStests for the existence of rows in a subquery.sqlSELECT * FROM table1 WHERE EXISTS (SELECT 1 FROM table2 WHERE table1.id = table2.id);Explain the
RANK(),DENSE_RANK(), andROW_NUMBER()functions.Answer:
RANK(): Assigns ranks with gaps for ties.
DENSE_RANK(): Assigns ranks without gaps for ties.
ROW_NUMBER(): Assigns unique sequential numbers.
sqlSELECT column1, RANK() OVER (ORDER BY column2) AS rank FROM table_name; SELECT column1, DENSE_RANK() OVER (ORDER BY column2) AS dense_rank FROM table_name; SELECT column1, ROW_NUMBER() OVER (ORDER BY column2) AS row_num FROM table_name;How do you perform a
SELF JOINin SQL?Answer:
SELF JOINjoins a table with itself.sqlSELECT a.column1, b.column2 FROM table_name a JOIN table_name b ON a.id = b.id;
Practical SQL Scenarios
How do you find the second highest salary from a table?
Answer: Use the
DISTINCTandLIMITclauses with a subquery.sqlSELECT DISTINCT salary FROM table_name ORDER BY salary DESC LIMIT 1 OFFSET 1;How do you detect duplicate records in a table?
Answer: Use the
GROUP BYandHAVINGclauses.sqlSELECT column1, COUNT(*) FROM table_name GROUP BY column1 HAVING COUNT(*) > 1;How do you delete duplicate records from a table?
Answer: Use a
CTE(Common Table Expression) andROW_NUMBER()function.sqlWITH CTE AS ( SELECT column1, ROW_NUMBER() OVER (PARTITION BY column1 ORDER BY column1) AS row_num FROM table_name ) DELETE FROM CTE WHERE row_num > 1;How do you find the nth highest salary in a table?
Answer: Use the
DENSE_RANK()function in a subquery.sqlSELECT salary FROM ( SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rank FROM table_name ) WHERE rank = n;How do you update data in one table based on data in another table?
Answer: Use the
UPDATEstatement with aJOIN.sqlUPDATE table1 SET table1.column1 = table2.column2 FROM table2 WHERE table1.id = table2.id;
SQL Performance and Optimization
What are
Composite Indexesand their benefits?Answer: Composite indexes include multiple columns, improving query performance for searches involving those columns.
sqlCREATE INDEX idx_composite ON table_name (column1, column2);What is a
Clustered Indexand how is it different from aNon-Clustered Index?Answer:
Clustered Index: Sorts and stores data rows in the table based on the indexed column. Only one per table.
Non-Clustered Index: Creates a separate structure with pointers to the data rows. Multiple per table.
sqlCREATE CLUSTERED INDEX idx_clustered ON table_name (column1); CREATE NONCLUSTERED INDEX idx_nonclustered ON table_name (column1);How do you handle large datasets in SQL?
Answer: Techniques include:
Partitioning tables.
Indexing columns.
Using efficient joins and subqueries.
Limiting results with
LIMITorTOP.
What is the purpose of
Materialized Views?Answer: Materialized views store query results physically to improve performance for complex queries that are frequently executed.
sqlCREATE MATERIALIZED VIEW view_name AS SELECT * FROM table_name;
Transactional SQL and Data Integrity
What is
Referential Integrityand how is it enforced?Answer: Referential integrity ensures that relationships between tables remain consistent. It's enforced using
Foreign Keyconstraints.sqlALTER TABLE child_table ADD CONSTRAINT fk_name FOREIGN KEY (parent_id) REFERENCES parent_table(id);How do you implement
Soft Deletesin SQL?Answer: Use a column (e.g.,
is_deleted) to mark records as deleted instead of physically removing them.sqlUPDATE table_name SET is_deleted = 1 WHERE id = value;What is the
MERGEstatement and its use?Answer:
MERGEperforms insert, update, or delete operations based on conditions.sqlMERGE INTO target_table USING source_table ON (target_table.id = source_table.id) WHEN MATCHED THEN UPDATE SET target_table.column1 = source_table.column1 WHEN NOT MATCHED THEN INSERT (column1, column2) VALUES (source_table.column1, source_table.column2);
What is a
WINDOW FUNCTIONand how is it used?Answer: Window functions perform calculations across a set of table rows related to the current row. Examples include
ROW_NUMBER(),RANK(),DENSE_RANK(), andLAG().sqlSELECT column1, RANK() OVER (PARTITION BY column2 ORDER BY column3) AS rank FROM table_name;Explain the
LAG()andLEAD()functions.Answer:
LAG(): Accesses data from a previous row in the same result set.
LEAD(): Accesses data from a subsequent row in the same result set.
sqlSELECT column1, LAG(column2, 1) OVER (ORDER BY column3) AS previous_value FROM table_name;What are
Common Table Expressions (CTEs)and their use?Answer: CTEs provide a way to write temporary named result sets, which can be referenced within a
SELECT,INSERT,UPDATE, orDELETEstatement.sqlWITH CTE AS ( SELECT column1, column2 FROM table_name ) SELECT * FROM CTE;How do you use the
PIVOTandUNPIVOToperators in SQL?Answer:
PIVOT: Transforms rows into columns.
UNPIVOT: Transforms columns into rows.
sql-- PIVOT example SELECT * FROM ( SELECT column1, column2, column3 FROM table_name ) PIVOT (SUM(column3) FOR column2 IN ([val1], [val2], [val3])); -- UNPIVOT example SELECT * FROM ( SELECT column1, val1, val2, val3 FROM table_name ) UNPIVOT (value FOR column2 IN (val1, val2, val3));Describe the
JSON Functionsavailable in SQL.Answer: SQL provides functions to handle JSON data, such as
JSON_VALUE(),JSON_QUERY(), andOPENJSON().sqlSELECT JSON_VALUE(json_column, '$.key') AS value FROM table_name;
SQL Query Optimization and Indexing
How do you handle
NULLvalues in SQL?Answer: Use functions like
IS NULL,IS NOT NULL,COALESCE(), andIFNULL().sqlSELECT column1 FROM table_name WHERE column2 IS NULL; SELECT COALESCE(column1, 'default') FROM table_name;
Advanced SQL Techniques for Data Analysis
How do you calculate a
Moving Averagein SQL?Answer: Use window functions like
AVG()withOVER()to calculate moving averages.sqlSELECT column1, AVG(column2) OVER (ORDER BY column1 ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg FROM table_name;Describe the
FIRST_VALUE()andLAST_VALUE()functions.Answer:
FIRST_VALUE(): Returns the first value in an ordered set of values.
LAST_VALUE(): Returns the last value in an ordered set of values.
sqlSELECT column1, FIRST_VALUE(column2) OVER (ORDER BY column3) AS first_value FROM table_name;What is the
PERCENT_RANK()function?Answer:
PERCENT_RANK()calculates the relative rank of a row within a result set as a percentage.sqlSELECT column1, PERCENT_RANK() OVER (PARTITION BY column2 ORDER BY column3) AS percent_rank FROM table_name;How do you perform
Hierarchical Queriesin SQL?Answer: Use
WITH RECURSIVECTEs to perform hierarchical or recursive queries.sqlWITH RECURSIVE hierarchy AS ( SELECT column1, column2 FROM table_name WHERE column1 = root_value UNION ALL SELECT t.column1, t.column2 FROM table_name t JOIN hierarchy h ON t.parent_column = h.column1 ) SELECT * FROM hierarchy;
Transactional Control and Error Handling
How do you handle
Deadlocksin SQL?Answer: Deadlocks occur when two transactions wait for each other to release resources. Handle them by:
Implementing a retry mechanism.
Optimizing transactions to reduce lock duration.
Using
SET DEADLOCK_PRIORITYto set the priority of transactions.
What is
Error Handlingin SQL and how do you implement it?Answer: Error handling captures and manages errors during SQL execution using constructs like
TRY...CATCH.sqlBEGIN TRY -- SQL statements END TRY BEGIN CATCH -- Error handling statements END CATCH;Explain the concept of
Savepointsin transactions.Answer: Savepoints create intermediate points within a transaction to which you can roll back without affecting the entire transaction.
sqlSAVEPOINT savepoint_name; -- SQL operations ROLLBACK TO savepoint_name;How do you use
Transactional Control Commandsin SQL?Answer: Transactional control commands include
BEGIN TRANSACTION,COMMIT, andROLLBACKto manage transactions.sqlBEGIN TRANSACTION; -- SQL operations COMMIT; -- or ROLLBACK;
Complex Data Analysis and Transformation
How do you create
Derived Tablesin SQL?Answer: Derived tables are temporary tables created within a
SELECTstatement using subqueries.sqlSELECT * FROM (SELECT column1, column2 FROM table_name) AS derived_table;What is a
Pivot Tablein SQL and how do you create one?Answer: Pivot tables summarize data by transforming rows into columns using aggregation functions.
sqlSELECT * FROM ( SELECT column1, column2, column3 FROM table_name ) PIVOT (SUM(column3) FOR column2 IN ([val1], [val2], [val3]));Explain
ETL (Extract, Transform, Load)in the context of SQL.Answer: ETL processes extract data from sources, transform it to fit operational needs, and load it into a target database. It involves data cleaning, integration, and loading.
How do you perform
String Manipulationin SQL?Answer: Use functions like
CONCAT(),SUBSTRING(),REPLACE(), andLTRIM()/RTRIM().sqlSELECT CONCAT(column1, ' ', column2) AS full_name FROM table_name; SELECT SUBSTRING(column1, 1, 5) AS substring FROM table_name; SELECT REPLACE(column1, 'old', 'new') AS replaced_string FROM table_name;
What is
Data Wranglingand how is it done in SQL?Answer: Data wrangling is the process of cleaning, transforming, and preparing raw data for analysis. In SQL, it involves:
Removing duplicates:
sqlDELETE FROM table_name WHERE id NOT IN (SELECT MIN(id) FROM table_name GROUP BY column1, column2);Handling missing values:
sqlUPDATE table_name SET column1 = 'default_value' WHERE column1 IS NULL;Standardizing formats:
sqlUPDATE table_name SET column1 = UPPER(column1);
How do you perform
Recursive Queriesin SQL?Answer: Recursive queries are written using
WITH RECURSIVEto retrieve hierarchical or nested data.sqlWITH RECURSIVE subordinates AS ( SELECT employee_id, manager_id FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.employee_id, e.manager_id FROM employees e INNER JOIN subordinates s ON e.manager_id = s.employee_id ) SELECT * FROM subordinates;What are
Cross Tab Queriesand how do you create them in SQL?Answer: Cross tab queries, or pivot queries, summarize data by converting rows into columns.
sqlSELECT * FROM ( SELECT column1, column2, column3 FROM table_name ) PIVOT (SUM(column3) FOR column2 IN ([val1], [val2], [val3]));How do you implement
Row-Level Securityin SQL Server?Answer: Use security policies to restrict access to rows based on user attributes.
sqlCREATE SECURITY POLICY security_policy_name ADD FILTER PREDICATE user_has_access(column) ON table_name, ADD BLOCK PREDICATE user_has_access(column) ON table_name;What is the
MERGEstatement and its use cases?Answer:
MERGEallows performingINSERT,UPDATE, orDELETEoperations based on a condition, often used in data warehousing.sqlMERGE target_table USING source_table ON target_table.id = source_table.id WHEN MATCHED THEN UPDATE SET target_table.column1 = source_table.column1 WHEN NOT MATCHED THEN INSERT (column1, column2) VALUES (source_table.column1, source_table.column2);
What is the difference between
Batch ProcessingandStreaming Processingin SQL?Answer:
Batch Processing: Processes large volumes of data at once.
Streaming Processing: Processes data continuously as it arrives.
What are
Temporal Tablesin SQL Server?Answer: Temporal tables automatically track changes to data over time, providing historical data views.
sqlCREATE TABLE table_name ( column1 INT, column2 VARCHAR(100), PERIOD FOR SYSTEM_TIME (start_time, end_time) ) WITH (SYSTEM_VERSIONING = ON);Explain the
Spatial Datatypes and their use cases.Answer: Spatial data types store and manipulate geographical and geometric data. Use cases include GIS (Geographic Information Systems), mapping, and location-based services.
sqlCREATE TABLE spatial_table (id INT, location GEOGRAPHY);How do you handle
Recursive Relationshipsin SQL databases?Answer: Use
Recursive CTEsto query hierarchical data structures.sqlWITH RECURSIVE hierarchy AS ( SELECT id, parent_id FROM table_name WHERE parent_id IS NULL UNION ALL SELECT t.id, t.parent_id FROM table_name t JOIN hierarchy h ON t.parent_id = h.id ) SELECT * FROM hierarchy;What is the purpose of
Window Aggregatesin SQL?Answer: Window aggregates perform calculations across a set of table rows related to the current row, such as
SUM(),AVG(), andCOUNT().sqlSELECT column1, SUM(column2) OVER (PARTITION BY column3 ORDER BY column4) AS running_total FROM table_name;How do you perform
Pattern Matchingusing SQL?
Answer: Use the LIKE operator and regular expressions for pattern matching.
sql SELECT * FROM table_name WHERE column1 LIKE 'pattern%';
These additional SQL questions delve deeper into advanced topics, data integrity, performance optimization, and specialized operations, providing you with a comprehensive foundation for your interviews in data-related roles.
What are
Common Table Expressions (CTEs)and their benefits?
Answer: CTEs are temporary result sets that improve query readability and can be referenced within a larger query.
sql WITH CTE AS ( SELECT column1, column2 FROM table_name ) SELECT * FROM CTE WHERE column2 > 10;
How do you optimize a
Subquery?
Answer: Convert subqueries to joins, use indexes, and ensure subqueries are correlated efficiently.
sql SELECT * FROM table_name t1 WHERE EXISTS (SELECT 1 FROM table_name2 t2 WHERE t1.id = t2.id);
SQL Security and Data Protection
How do you implement
Row-Level Security (RLS)in SQL?
Answer: Use security policies to restrict access to rows based on user attributes.
sql CREATE SECURITY POLICY security_policy_name ADD FILTER PREDICATE user_has_access(column) ON table_name;
What is
SQL Injectionand how to prevent it?
Answer: SQL injection is a security vulnerability allowing execution of malicious SQL. Prevent it using parameterized queries and input validation.
sql -- Parameterized query example SELECT * FROM table_name WHERE column_name = @parameter;
Describe the concept of
Role-Based Access Control (RBAC).
Answer: RBAC assigns permissions to roles rather than individual users, simplifying access management.
sql CREATE ROLE role_name; GRANT SELECT, INSERT ON table_name TO role_name;
How do you handle
Temporal Datain SQL?
Answer: Use temporal tables to track historical data changes.
sql CREATE TABLE table_name ( column1 INT, column2 VARCHAR(100), PERIOD FOR SYSTEM_TIME (start_time, end_time) ) WITH (SYSTEM_VERSIONING = ON);
What are
User-Defined Functions (UDFs)and their types?
Answer: UDFs are custom functions defined by users to perform specific tasks. Types include scalar, table-valued, and inline table-valued functions.
sql CREATE FUNCTION function_name (@parameter INT) RETURNS INT AS BEGIN RETURN (@parameter * 2); END;
Comments
Post a Comment