SlideShare a Scribd company logo
SQL INterview Questions .pTop 45 SQL Interview Questions And Answers In 2025 | SQL Interview Questions 2025 | Simplilearnptx
SQL
INTERVIEW
QUESTIONS
What is SQL?
1
•SQL, which stands for Structured Query Language, is the language used
to talk to databases.
•You can also use SQL to add new data, like entering a new customer’s
details into the database.
•With SQL, you can query, update, insert, and delete data.
SELECT * FROM customers WHERE city = 'New York';
INSERT INTO customers (name, city) VALUES ('John Doe', 'Los Angeles');
What are the different types of SQL commands?
2
What is a primary key in SQL?
3
•A primary key in SQL is like a unique ID for each record in a table.
• It’s also a rule that the primary key column can’t have empty (null)
values.
•The primary key ensures: Each customer_id is unique (no duplicates).
•No customer_id is left blank (no null values).
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(50),
city VARCHAR(50)
);
What is a foreign key?
4
•A foreign key in SQL is like a connection or link between two tables.
•It’s a field in one table that refers to the primary key in another table.
•This creates a relationship between the tables and ensures that the data
stays consistent.
What is a foreign key?
4
-- Create the Customers table
CREATE TABLE Customers (
customer_id INT PRIMARY KEY, -- Primary key
first_name VARCHAR(50),
last_name VARCHAR(50),
email_address VARCHAR(100),
number_of_complaints INT
);
-- Create the Sales table
CREATE TABLE Sales (
purchase_number INT PRIMARY KEY, -- Primary key
date_of_purchase DATE,
customer_id INT, -- Foreign key
item_code VARCHAR(20),
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);
DELETE and TRUNCATE commands
5
•The DELETE and TRUNCATE commands in SQL both remove data from a
table, but they work in different ways.
What is a JOIN in SQL, and what are its types?
6
A JOIN in SQL is used to combine data from two or more tables based on a
related column, like a common key that links them together.
What do you mean by a NULL value in SQL?
7
A NULL value in SQL means that a column has no data—it’s missing or unknown.
It’s not the same as an empty string ('') or the number zero.
Define a Unique Key in SQL
8
• A Unique Key in SQL ensures that all values in a column (or a combination of
columns) are unique—no duplicates are allowed.
• Unlike a primary key, a table can have more than one unique key.
• Unique keys allow NULL values, while primary keys do not.
CREATE TABLE users (
user_id INT PRIMARY KEY,
email VARCHAR(50) UNIQUE
);
What is a database?
9
• A database is an organized way to store and manage data.
• Each row represents a record (like a single entry), and each column
represents a specific detail about that record (like a name or date).
Difference between SQL and NoSQL databases
10
What is a table and a field in SQL?
11
• A table is like a spreadsheet that stores data in an organized way using rows and
columns. Each table contains records (rows) and their details (columns)
• A field is a column in the table. It represents a specific attribute or property of the
data.
Describe the SELECT statement.
12
• The SELECT statement in SQL is used to retrieve data from a table (or multiple
tables).
SELECT name FROM customers;
Retrieve All Data
Apply Filters
Sort the Results
SELECT * FROM customers;
SELECT name FROM customers WHERE city = 'New
York';
SELECT name FROM customers ORDER BY name ASC;
What is a constraint in SQL? Name a few.
13
• A constraint in SQL is a rule applied to a table to ensure that the data stored is
accurate and consistent.
• It helps maintain data integrity by restricting what values can be added or modified
in a table.
What is normalization in SQL?
14
• Normalization in SQL is a process used to organize data in a database to make it more
efficient and reliable.
• The goal is to reduce redundancy (duplicate data) and ensure data consistency.
• This is done by splitting a large table into smaller, related tables and linking them using
relationships like primary and foreign keys.
How do you use the WHERE clause?
15
• The WHERE clause within SQL queries serves the purpose of selectively filtering rows
according to specified conditions, thereby enabling you to fetch exclusively those rows
that align with the criteria you define.
SELECT * FROM employees WHERE department =
'HR';
Difference between UNION and Union ALL
17
• UNION merges the contents of two structurally-compatible tables into a single
combined table. The difference between UNION and UNION ALL is that UNION will omit
duplicate records whereas UNION ALL will include duplicate records.
• The performance of UNION ALL will typically be better than UNION, since UNION
requires the server to do the additional work of removing any duplicates. So, in cases
where is is certain that there will not be any duplicates, or where having duplicates is
not a problem, use of UNION ALL would be recommended for performance .
What will be the result of the query?
18
SELECT * FROM runners WHERE id NOT IN (SELECT winner_id FROM
races)
Surprisingly, given the sample data provided, the result
of this query will be an empty set. The reason for this is
as follows: If the set being evaluated by the SQL NOT IN
condition contains any values that are null, then the
outer query here will return an empty set, even if there
are many runner ids that match winner_ids in the races
table.
What are indexes in SQL?
19
CREATE INDEX idx_customer_name ON customers(name);
• Indexes in SQL are like a shortcut to quickly find data in a table. Instead of searching
through every row one by one, an index creates a sorted structure based on one or
more columns, making data retrieval much faster.
SELECT * FROM customers WHERE name = 'John';
Explain GROUP BY in SQL
20
SELECT region, SUM(amount) AS total_sales
FROM sales
GROUP BY region;
• The GROUP BY clause in SQL groups rows with the same values in a column, allowing
you to apply functions like SUM, COUNT, or AVG to each group.
What is an SQL alias?
21
SELECT first_name AS "First Name", last_name AS "Last
Name"
FROM employees;
• An SQL alias is a temporary name you give to a table or a column in a query to make
it easier to read or work with. It’s like giving a nickname to something for clarity.
SELECT e.first_name, d.department_name
FROM employees AS e
JOIN departments AS d ON e.department_id =
d.department_id;
Explain ORDER BY in SQL.
22
SELECT * FROM products ORDER BY price DESC;
• The ORDER BY clause is used to sort the result set of a query based on one or more
columns. You can specify each column's sorting order (ascending or descending).
Difference between WHERE and HAVING in SQL
23
What is a view in SQL?
24
• An SQL view is essentially a virtual table that derives its data from the outcome of a
SELECT query.
• Views serve multiple purposes, including simplifying intricate queries, enhancing data
security through an added layer, and enabling the presentation of targeted data
subsets to users.
What is a stored procedure?
25
• A SQL stored procedure comprises precompiled SQL statements that can be executed
together as a unified entity.
• These procedures are commonly used to encapsulate business logic, improve
performance, and ensure consistent data manipulation practices.
What is a trigger in SQL?
26
• An SQL trigger consists of a predefined sequence of actions that are executed
automatically when a particular event occurs, such as when an INSERT or DELETE
operation is performed on a table.
• Triggers are employed to ensure data consistency, conduct auditing, and streamline
various tasks.
What are aggregate functions? Can you name a few?
27
How do you update a value in SQL?
28
• The UPDATE statement serves the purpose of altering pre-existing records within
a table. It involves specifying the target table for the update, the specific columns
to be modified, and the desired new values to be applied.
UPDATE employees SET salary = 60000 WHERE department
= 'IT';
What is a self-join, and how would you use it?
29
• A self-join in SQL is a type of join where a table is joined with itself. It’s useful for
comparing rows within the same table or exploring hierarchical relationships, such
as finding employees and their managers in an organization.
SELECT e.name AS Employee, m.name AS Manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.employee_id;
What is a self-join, and how would you use it?
29
• A self-join in SQL is a type of join where a table is joined with itself. It’s useful for
comparing rows within the same table or exploring hierarchical relationships, such
as finding employees and their managers in an organization.
Explain different types of joins with examples.
30
INNER JOIN: Gathers rows that have matching values in both
tables.
RIGHT JOIN: Gathers all rows from the right table and any
matching rows from the left table.
LEFT JOIN: Gathers all rows from the left table and any
matching rows from the right table.
FULL JOIN: Gathers all rows when there's a match in either
table, including unmatched rows from both tables.
What is a subquery? Provide an example
31
A subquery refers to a query that is embedded within another query, serving
the purpose of fetching information that will subsequently be employed as a
condition or value within the encompassing outer query.
SELECT name
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
How do you optimize SQL queries?
32
• SQL query optimization involves improving the performance of SQL
queries by reducing resource usage and execution time.
• Strategies include using appropriate indexes, optimizing query
structure, and avoiding costly operations like full table scans.
What are correlated subqueries?
33
• It is a type of subquery that makes reference to columns from the
surrounding outer query.
• This subquery is executed repeatedly, once for each row being
processed by the outer query, and its execution depends on the
outcomes of the outer query.
What is a transaction in SQL?
34
• A transaction in SQL is a group of one or more SQL commands that are
treated as a single unit. It ensures that all the operations in the group
either succeed completely or fail entirely. This guarantees the integrity of
the database.
Explain ACID properties in SQL
35
How do you implement error handling in SQL?
36
• Error handling in SQL is a process to manage and respond to errors
that occur during query execution. Different database systems have
specific ways to handle errors.
Describe the data types in SQL
37
• SQL supports various data types, which define the kind of data a column can hold.
These are broadly categorized into numeric, character, date/time, and binary
types.
Explain normalization and denormalization.
38
• Normalization is about breaking big tables into smaller ones to remove duplicate
data and improve accuracy.
• Denormalization, on the other hand, is when you combine or duplicate data to
make it faster to retrieve. For instance, you might add customer details directly to
the orders table so you don’t need to join tables during a query
What is a clustered index?
39
• A clustered index in SQL determines the physical order of data rows in a table.
Each table can have only one clustered index, which impacts the table's storage
structure.
How do you prevent SQL injection?
39
• SQL injection is a security risk where attackers insert harmful code into SQL
queries, potentially accessing or tampering with your database.
• Validate inputs to allow only expected values, use stored procedures to separate
logic from data, limit database permissions, and escape special characters.
Explain the concept of a database schema.
40
• In SQL, a database schema functions as a conceptual container for housing
various database elements, such as tables, views, indexes, and procedures.
• Its primary purpose is to facilitate the organization and segregation of these
database elements while specifying their structure and interconnections.
How is data integrity ensured in SQL?
41
• Data integrity in SQL is ensured through various means, including constraints
(e.g., primary keys, foreign keys, check constraints), normalization, transactions,
and referential integrity constraints. These mechanisms prevent invalid or
inconsistent data from being stored in the database.
What is an SQL injection?
42
• SQL injection is a cybersecurity attack method that involves the insertion of
malicious SQL code into an application's input fields or parameters.
• This unauthorized action enables attackers to illicitly access a database, extract
confidential information, or manipulate data.
How do you create a stored procedure?
43
• You use the CREATE PROCEDURE statement to create a stored procedure in SQL.
A stored procedure can contain SQL statements, parameters, and variables.
CREATE PROCEDURE GetEmployeeByID(@EmployeeID INT)
AS
BEGIN
SELECT * FROM employees WHERE employee_id =
@EmployeeID;
END;
What is a deadlock in SQL? How can it be prevented?
44
• A deadlock in SQL occurs when two or more transactions cannot proceed
because they are waiting for resources held by each other.
• Deadlocks can be prevented or resolved by using techniques such as locking
hierarchies, timeouts, or deadlock detection and resolution mechanisms.
Difference between IN and EXISTS?
45
• IN:
• Works on List result set
• Doesn’t work on subqueries resulting in Virtual tables with multiple columns
• Compares every value in the result list
• Performance is comparatively SLOW for larger resultset of subquery
• EXISTS:
• Works on Virtual tables
• Is used with co-related queries
• Exits comparison when match is found
• Performance is comparatively FAST for larger resultset of subquery

More Related Content

PPTX
Machine Learning Interview Questions 2024 | ML Interview Questions And Answer...
Simplilearn
 
PDF
Wildcard In database
jamilmalik19
 
PDF
Chapter9 more on database and sql
KV(AFS) Utarlai, Barmer (Rajasthan)
 
PPTX
Relational Algebra,Types of join
raj upadhyay
 
PDF
Uniform-Cost Search Algorithm in the AI Environment
Hitesh Mohapatra
 
PPTX
Genetic algorithm
Megha V
 
PPT
Joins in SQL
Vigneshwaran Sankaran
 
PPTX
joins in database
Sultan Arshad
 
Machine Learning Interview Questions 2024 | ML Interview Questions And Answer...
Simplilearn
 
Wildcard In database
jamilmalik19
 
Chapter9 more on database and sql
KV(AFS) Utarlai, Barmer (Rajasthan)
 
Relational Algebra,Types of join
raj upadhyay
 
Uniform-Cost Search Algorithm in the AI Environment
Hitesh Mohapatra
 
Genetic algorithm
Megha V
 
Joins in SQL
Vigneshwaran Sankaran
 
joins in database
Sultan Arshad
 

Similar to SQL INterview Questions .pTop 45 SQL Interview Questions And Answers In 2025 | SQL Interview Questions 2025 | Simplilearnptx (20)

PDF
SQL -Beginner To Intermediate Level.pdf
DraguClaudiu
 
PPT
Module08
Sridhar P
 
PPT
Module08
guest5c8fba1
 
PPTX
More Complex SQL and Concurrency ControlModule 4.pptx
bgscseise
 
PDF
DBMS and SQL Questions and Answers (1).pdf
sifatullah42
 
PPTX
SQL.pptx for the begineers and good know
PavithSingh
 
PPTX
Aggregate functions in SQL.pptx
SherinRappai1
 
PPTX
SQL Commands
Sachidananda M H
 
PPTX
Aggregate functions in SQL.pptx
SherinRappai
 
PDF
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
PreetiKushwah6
 
PDF
MSSQL_Book.pdf
DubsmashTamizhan
 
PPTX
SQL UNIT FOUR.pptxDiscDiscoverabilitDiscoverability Scorey Scoreoverability S...
sultanahimed3
 
PPTX
SQL Interview Questions and Answers for Business Analyst
HireQuotient
 
PPTX
02 database oprimization - improving sql performance - ent-db
uncleRhyme
 
PDF
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
ssuserb5bb0e
 
PPTX
SQL things ace series of the thing useful
avinash4210singh
 
PDF
Top 50 SQL Interview Questions and Answer.pdf
Rajkumar751652
 
PPTX
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
Abhishek590097
 
PPSX
MS SQL Server
Md. Mahedee Hasan
 
PDF
Steps towards of sql server developer
Ahsan Kabir
 
SQL -Beginner To Intermediate Level.pdf
DraguClaudiu
 
Module08
Sridhar P
 
Module08
guest5c8fba1
 
More Complex SQL and Concurrency ControlModule 4.pptx
bgscseise
 
DBMS and SQL Questions and Answers (1).pdf
sifatullah42
 
SQL.pptx for the begineers and good know
PavithSingh
 
Aggregate functions in SQL.pptx
SherinRappai1
 
SQL Commands
Sachidananda M H
 
Aggregate functions in SQL.pptx
SherinRappai
 
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
PreetiKushwah6
 
MSSQL_Book.pdf
DubsmashTamizhan
 
SQL UNIT FOUR.pptxDiscDiscoverabilitDiscoverability Scorey Scoreoverability S...
sultanahimed3
 
SQL Interview Questions and Answers for Business Analyst
HireQuotient
 
02 database oprimization - improving sql performance - ent-db
uncleRhyme
 
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
ssuserb5bb0e
 
SQL things ace series of the thing useful
avinash4210singh
 
Top 50 SQL Interview Questions and Answer.pdf
Rajkumar751652
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
Abhishek590097
 
MS SQL Server
Md. Mahedee Hasan
 
Steps towards of sql server developer
Ahsan Kabir
 
Ad

More from Simplilearn (20)

PPTX
Top 50 Scrum Master Interview Questions | Scrum Master Interview Questions & ...
Simplilearn
 
PPTX
Bagging Vs Boosting In Machine Learning | Ensemble Learning In Machine Learni...
Simplilearn
 
PPTX
Future Of Social Media | Social Media Trends and Strategies 2025 | Instagram ...
Simplilearn
 
PPTX
SQL Query Optimization | SQL Query Optimization Techniques | SQL Basics | SQL...
Simplilearn
 
PPTX
How To Start Influencer Marketing Business | Influencer Marketing For Beginne...
Simplilearn
 
PPTX
Cyber Security Roadmap 2025 | How To Become Cyber Security Engineer In 2025 |...
Simplilearn
 
PPTX
How To Become An AI And ML Engineer In 2025 | AI Engineer Roadmap | AI ML Car...
Simplilearn
 
PPTX
What Is GitHub Copilot? | How To Use GitHub Copilot? | How does GitHub Copilo...
Simplilearn
 
PPTX
Top 10 Data Analyst Certification For 2025 | Best Data Analyst Certification ...
Simplilearn
 
PPTX
Complete Data Science Roadmap For 2025 | Data Scientist Roadmap For Beginners...
Simplilearn
 
PPTX
Top 7 High Paying AI Certifications Courses For 2025 | Best AI Certifications...
Simplilearn
 
PPTX
Data Cleaning In Data Mining | Step by Step Data Cleaning Process | Data Clea...
Simplilearn
 
PPTX
Top 10 Data Analyst Projects For 2025 | Data Analyst Projects | Data Analysis...
Simplilearn
 
PPTX
AI Engineer Roadmap 2025 | AI Engineer Roadmap For Beginners | AI Engineer Ca...
Simplilearn
 
PPTX
Machine Learning Roadmap 2025 | Machine Learning Engineer Roadmap For Beginne...
Simplilearn
 
PPTX
Kotter's 8-Step Change Model Explained | Kotter's Change Management Model | S...
Simplilearn
 
PPTX
Gen AI Engineer Roadmap For 2025 | How To Become Gen AI Engineer In 2025 | Si...
Simplilearn
 
PPTX
Top 10 Data Analyst Certification For 2025 | Best Data Analyst Certification ...
Simplilearn
 
PPTX
Complete Data Science Roadmap For 2025 | Data Scientist Roadmap For Beginners...
Simplilearn
 
PPTX
Top 7 High Paying AI Certifications Courses For 2025 | Best AI Certifications...
Simplilearn
 
Top 50 Scrum Master Interview Questions | Scrum Master Interview Questions & ...
Simplilearn
 
Bagging Vs Boosting In Machine Learning | Ensemble Learning In Machine Learni...
Simplilearn
 
Future Of Social Media | Social Media Trends and Strategies 2025 | Instagram ...
Simplilearn
 
SQL Query Optimization | SQL Query Optimization Techniques | SQL Basics | SQL...
Simplilearn
 
How To Start Influencer Marketing Business | Influencer Marketing For Beginne...
Simplilearn
 
Cyber Security Roadmap 2025 | How To Become Cyber Security Engineer In 2025 |...
Simplilearn
 
How To Become An AI And ML Engineer In 2025 | AI Engineer Roadmap | AI ML Car...
Simplilearn
 
What Is GitHub Copilot? | How To Use GitHub Copilot? | How does GitHub Copilo...
Simplilearn
 
Top 10 Data Analyst Certification For 2025 | Best Data Analyst Certification ...
Simplilearn
 
Complete Data Science Roadmap For 2025 | Data Scientist Roadmap For Beginners...
Simplilearn
 
Top 7 High Paying AI Certifications Courses For 2025 | Best AI Certifications...
Simplilearn
 
Data Cleaning In Data Mining | Step by Step Data Cleaning Process | Data Clea...
Simplilearn
 
Top 10 Data Analyst Projects For 2025 | Data Analyst Projects | Data Analysis...
Simplilearn
 
AI Engineer Roadmap 2025 | AI Engineer Roadmap For Beginners | AI Engineer Ca...
Simplilearn
 
Machine Learning Roadmap 2025 | Machine Learning Engineer Roadmap For Beginne...
Simplilearn
 
Kotter's 8-Step Change Model Explained | Kotter's Change Management Model | S...
Simplilearn
 
Gen AI Engineer Roadmap For 2025 | How To Become Gen AI Engineer In 2025 | Si...
Simplilearn
 
Top 10 Data Analyst Certification For 2025 | Best Data Analyst Certification ...
Simplilearn
 
Complete Data Science Roadmap For 2025 | Data Scientist Roadmap For Beginners...
Simplilearn
 
Top 7 High Paying AI Certifications Courses For 2025 | Best AI Certifications...
Simplilearn
 
Ad

Recently uploaded (20)

PPTX
Understanding operators in c language.pptx
auteharshil95
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
PPTX
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PDF
Landforms and landscapes data surprise preview
jpinnuck
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Understanding operators in c language.pptx
auteharshil95
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
Landforms and landscapes data surprise preview
jpinnuck
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 

SQL INterview Questions .pTop 45 SQL Interview Questions And Answers In 2025 | SQL Interview Questions 2025 | Simplilearnptx

  • 3. What is SQL? 1 •SQL, which stands for Structured Query Language, is the language used to talk to databases. •You can also use SQL to add new data, like entering a new customer’s details into the database. •With SQL, you can query, update, insert, and delete data. SELECT * FROM customers WHERE city = 'New York'; INSERT INTO customers (name, city) VALUES ('John Doe', 'Los Angeles');
  • 4. What are the different types of SQL commands? 2
  • 5. What is a primary key in SQL? 3 •A primary key in SQL is like a unique ID for each record in a table. • It’s also a rule that the primary key column can’t have empty (null) values. •The primary key ensures: Each customer_id is unique (no duplicates). •No customer_id is left blank (no null values). CREATE TABLE customers ( customer_id INT PRIMARY KEY, name VARCHAR(50), city VARCHAR(50) );
  • 6. What is a foreign key? 4 •A foreign key in SQL is like a connection or link between two tables. •It’s a field in one table that refers to the primary key in another table. •This creates a relationship between the tables and ensures that the data stays consistent.
  • 7. What is a foreign key? 4 -- Create the Customers table CREATE TABLE Customers ( customer_id INT PRIMARY KEY, -- Primary key first_name VARCHAR(50), last_name VARCHAR(50), email_address VARCHAR(100), number_of_complaints INT ); -- Create the Sales table CREATE TABLE Sales ( purchase_number INT PRIMARY KEY, -- Primary key date_of_purchase DATE, customer_id INT, -- Foreign key item_code VARCHAR(20), FOREIGN KEY (customer_id) REFERENCES Customers(customer_id) );
  • 8. DELETE and TRUNCATE commands 5 •The DELETE and TRUNCATE commands in SQL both remove data from a table, but they work in different ways.
  • 9. What is a JOIN in SQL, and what are its types? 6 A JOIN in SQL is used to combine data from two or more tables based on a related column, like a common key that links them together.
  • 10. What do you mean by a NULL value in SQL? 7 A NULL value in SQL means that a column has no data—it’s missing or unknown. It’s not the same as an empty string ('') or the number zero.
  • 11. Define a Unique Key in SQL 8 • A Unique Key in SQL ensures that all values in a column (or a combination of columns) are unique—no duplicates are allowed. • Unlike a primary key, a table can have more than one unique key. • Unique keys allow NULL values, while primary keys do not. CREATE TABLE users ( user_id INT PRIMARY KEY, email VARCHAR(50) UNIQUE );
  • 12. What is a database? 9 • A database is an organized way to store and manage data. • Each row represents a record (like a single entry), and each column represents a specific detail about that record (like a name or date).
  • 13. Difference between SQL and NoSQL databases 10
  • 14. What is a table and a field in SQL? 11 • A table is like a spreadsheet that stores data in an organized way using rows and columns. Each table contains records (rows) and their details (columns) • A field is a column in the table. It represents a specific attribute or property of the data.
  • 15. Describe the SELECT statement. 12 • The SELECT statement in SQL is used to retrieve data from a table (or multiple tables). SELECT name FROM customers; Retrieve All Data Apply Filters Sort the Results SELECT * FROM customers; SELECT name FROM customers WHERE city = 'New York'; SELECT name FROM customers ORDER BY name ASC;
  • 16. What is a constraint in SQL? Name a few. 13 • A constraint in SQL is a rule applied to a table to ensure that the data stored is accurate and consistent. • It helps maintain data integrity by restricting what values can be added or modified in a table.
  • 17. What is normalization in SQL? 14 • Normalization in SQL is a process used to organize data in a database to make it more efficient and reliable. • The goal is to reduce redundancy (duplicate data) and ensure data consistency. • This is done by splitting a large table into smaller, related tables and linking them using relationships like primary and foreign keys.
  • 18. How do you use the WHERE clause? 15 • The WHERE clause within SQL queries serves the purpose of selectively filtering rows according to specified conditions, thereby enabling you to fetch exclusively those rows that align with the criteria you define. SELECT * FROM employees WHERE department = 'HR';
  • 19. Difference between UNION and Union ALL 17 • UNION merges the contents of two structurally-compatible tables into a single combined table. The difference between UNION and UNION ALL is that UNION will omit duplicate records whereas UNION ALL will include duplicate records. • The performance of UNION ALL will typically be better than UNION, since UNION requires the server to do the additional work of removing any duplicates. So, in cases where is is certain that there will not be any duplicates, or where having duplicates is not a problem, use of UNION ALL would be recommended for performance .
  • 20. What will be the result of the query? 18 SELECT * FROM runners WHERE id NOT IN (SELECT winner_id FROM races) Surprisingly, given the sample data provided, the result of this query will be an empty set. The reason for this is as follows: If the set being evaluated by the SQL NOT IN condition contains any values that are null, then the outer query here will return an empty set, even if there are many runner ids that match winner_ids in the races table.
  • 21. What are indexes in SQL? 19 CREATE INDEX idx_customer_name ON customers(name); • Indexes in SQL are like a shortcut to quickly find data in a table. Instead of searching through every row one by one, an index creates a sorted structure based on one or more columns, making data retrieval much faster. SELECT * FROM customers WHERE name = 'John';
  • 22. Explain GROUP BY in SQL 20 SELECT region, SUM(amount) AS total_sales FROM sales GROUP BY region; • The GROUP BY clause in SQL groups rows with the same values in a column, allowing you to apply functions like SUM, COUNT, or AVG to each group.
  • 23. What is an SQL alias? 21 SELECT first_name AS "First Name", last_name AS "Last Name" FROM employees; • An SQL alias is a temporary name you give to a table or a column in a query to make it easier to read or work with. It’s like giving a nickname to something for clarity. SELECT e.first_name, d.department_name FROM employees AS e JOIN departments AS d ON e.department_id = d.department_id;
  • 24. Explain ORDER BY in SQL. 22 SELECT * FROM products ORDER BY price DESC; • The ORDER BY clause is used to sort the result set of a query based on one or more columns. You can specify each column's sorting order (ascending or descending).
  • 25. Difference between WHERE and HAVING in SQL 23
  • 26. What is a view in SQL? 24 • An SQL view is essentially a virtual table that derives its data from the outcome of a SELECT query. • Views serve multiple purposes, including simplifying intricate queries, enhancing data security through an added layer, and enabling the presentation of targeted data subsets to users.
  • 27. What is a stored procedure? 25 • A SQL stored procedure comprises precompiled SQL statements that can be executed together as a unified entity. • These procedures are commonly used to encapsulate business logic, improve performance, and ensure consistent data manipulation practices.
  • 28. What is a trigger in SQL? 26 • An SQL trigger consists of a predefined sequence of actions that are executed automatically when a particular event occurs, such as when an INSERT or DELETE operation is performed on a table. • Triggers are employed to ensure data consistency, conduct auditing, and streamline various tasks.
  • 29. What are aggregate functions? Can you name a few? 27
  • 30. How do you update a value in SQL? 28 • The UPDATE statement serves the purpose of altering pre-existing records within a table. It involves specifying the target table for the update, the specific columns to be modified, and the desired new values to be applied. UPDATE employees SET salary = 60000 WHERE department = 'IT';
  • 31. What is a self-join, and how would you use it? 29 • A self-join in SQL is a type of join where a table is joined with itself. It’s useful for comparing rows within the same table or exploring hierarchical relationships, such as finding employees and their managers in an organization. SELECT e.name AS Employee, m.name AS Manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.employee_id;
  • 32. What is a self-join, and how would you use it? 29 • A self-join in SQL is a type of join where a table is joined with itself. It’s useful for comparing rows within the same table or exploring hierarchical relationships, such as finding employees and their managers in an organization.
  • 33. Explain different types of joins with examples. 30 INNER JOIN: Gathers rows that have matching values in both tables. RIGHT JOIN: Gathers all rows from the right table and any matching rows from the left table. LEFT JOIN: Gathers all rows from the left table and any matching rows from the right table. FULL JOIN: Gathers all rows when there's a match in either table, including unmatched rows from both tables.
  • 34. What is a subquery? Provide an example 31 A subquery refers to a query that is embedded within another query, serving the purpose of fetching information that will subsequently be employed as a condition or value within the encompassing outer query. SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
  • 35. How do you optimize SQL queries? 32 • SQL query optimization involves improving the performance of SQL queries by reducing resource usage and execution time. • Strategies include using appropriate indexes, optimizing query structure, and avoiding costly operations like full table scans.
  • 36. What are correlated subqueries? 33 • It is a type of subquery that makes reference to columns from the surrounding outer query. • This subquery is executed repeatedly, once for each row being processed by the outer query, and its execution depends on the outcomes of the outer query.
  • 37. What is a transaction in SQL? 34 • A transaction in SQL is a group of one or more SQL commands that are treated as a single unit. It ensures that all the operations in the group either succeed completely or fail entirely. This guarantees the integrity of the database.
  • 39. How do you implement error handling in SQL? 36 • Error handling in SQL is a process to manage and respond to errors that occur during query execution. Different database systems have specific ways to handle errors.
  • 40. Describe the data types in SQL 37 • SQL supports various data types, which define the kind of data a column can hold. These are broadly categorized into numeric, character, date/time, and binary types.
  • 41. Explain normalization and denormalization. 38 • Normalization is about breaking big tables into smaller ones to remove duplicate data and improve accuracy. • Denormalization, on the other hand, is when you combine or duplicate data to make it faster to retrieve. For instance, you might add customer details directly to the orders table so you don’t need to join tables during a query
  • 42. What is a clustered index? 39 • A clustered index in SQL determines the physical order of data rows in a table. Each table can have only one clustered index, which impacts the table's storage structure.
  • 43. How do you prevent SQL injection? 39 • SQL injection is a security risk where attackers insert harmful code into SQL queries, potentially accessing or tampering with your database. • Validate inputs to allow only expected values, use stored procedures to separate logic from data, limit database permissions, and escape special characters.
  • 44. Explain the concept of a database schema. 40 • In SQL, a database schema functions as a conceptual container for housing various database elements, such as tables, views, indexes, and procedures. • Its primary purpose is to facilitate the organization and segregation of these database elements while specifying their structure and interconnections.
  • 45. How is data integrity ensured in SQL? 41 • Data integrity in SQL is ensured through various means, including constraints (e.g., primary keys, foreign keys, check constraints), normalization, transactions, and referential integrity constraints. These mechanisms prevent invalid or inconsistent data from being stored in the database.
  • 46. What is an SQL injection? 42 • SQL injection is a cybersecurity attack method that involves the insertion of malicious SQL code into an application's input fields or parameters. • This unauthorized action enables attackers to illicitly access a database, extract confidential information, or manipulate data.
  • 47. How do you create a stored procedure? 43 • You use the CREATE PROCEDURE statement to create a stored procedure in SQL. A stored procedure can contain SQL statements, parameters, and variables. CREATE PROCEDURE GetEmployeeByID(@EmployeeID INT) AS BEGIN SELECT * FROM employees WHERE employee_id = @EmployeeID; END;
  • 48. What is a deadlock in SQL? How can it be prevented? 44 • A deadlock in SQL occurs when two or more transactions cannot proceed because they are waiting for resources held by each other. • Deadlocks can be prevented or resolved by using techniques such as locking hierarchies, timeouts, or deadlock detection and resolution mechanisms.
  • 49. Difference between IN and EXISTS? 45 • IN: • Works on List result set • Doesn’t work on subqueries resulting in Virtual tables with multiple columns • Compares every value in the result list • Performance is comparatively SLOW for larger resultset of subquery • EXISTS: • Works on Virtual tables • Is used with co-related queries • Exits comparison when match is found • Performance is comparatively FAST for larger resultset of subquery