0% found this document useful (0 votes)
4 views4 pages

SQL

The document provides an overview of SQL, including its commands, differences between SQL and NoSQL databases, and concepts like joins, normalization, indexes, primary and foreign keys, views, and stored procedures. It also covers query optimization, aggregate functions, transactions, subqueries, self-joins, triggers, cursors, and window functions. Each section explains the definitions, functionalities, and examples of these SQL concepts.

Uploaded by

pratikkalaghan1
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
4 views4 pages

SQL

The document provides an overview of SQL, including its commands, differences between SQL and NoSQL databases, and concepts like joins, normalization, indexes, primary and foreign keys, views, and stored procedures. It also covers query optimization, aggregate functions, transactions, subqueries, self-joins, triggers, cursors, and window functions. Each section explains the definitions, functionalities, and examples of these SQL concepts.

Uploaded by

pratikkalaghan1
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 4

1.What is SQL? Explain the different types of SQL commands.

SQL (Structured Query Language) is a standardized language used to communicate with


relational databases. It is used to perform tasks such as querying, updating, and
managing data.
Types of SQL commands include:
DDL (Data Definition Language): CREATE, ALTER, DROP
DML (Data Manipulation Language): SELECT, INSERT, UPDATE, DELETE
DCL (Data Control Language): GRANT, REVOKE
TCL (Transaction Control Language): COMMIT, ROLLBACK, SAVEPOINT

2.What is the difference between SQL and NoSQL databases?


SQL Databases:
Use structured query language (SQL) for defining and manipulating data.
Are relational databases.
Have a predefined schema.
Examples: MySQL, PostgreSQL, SQLite.
NoSQL Databases:
Use various data models, including document, key-value, graph, and columnar.
Are non-relational databases.
Are schema-less or have dynamic schema.
Examples: MongoDB, Cassandra, Redis.

3.Explain the difference between INNER JOIN and OUTER JOIN.


INNER JOIN: Returns only the rows that have matching values in both tables.
SELECT * FROM table1 INNER JOIN table2 ON table1.id = table2.id;
OUTER JOIN: Returns all the rows from one table and the matched rows from the
second table. If there is no match, the result is NULL on the side of the table
without a match.
LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table, and the
matched rows from the right table.
SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.id;
RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table, and the
matched rows from the left table.
SELECT * FROM table1 RIGHT JOIN table2 ON table1.id = table2.id;
FULL JOIN (or FULL OUTER JOIN): Returns rows when there is a match in one of the
tables.
SELECT * FROM table1 FULL OUTER JOIN table2 ON table1.id = table2.id;

4.What is normalization? Explain the different normal forms.


Normalization is the process of organizing data in a database to reduce redundancy
and improve data integrity.
Normal Forms:
1NF (First Normal Form): Ensures that the table has only atomic (indivisible)
values and each column contains unique values.
2NF (Second Normal Form): Meets all requirements of 1NF and ensures that all non-
key attributes are fully functional dependent on the primary key.
3NF (Third Normal Form): Meets all requirements of 2NF and ensures that all
attributes are not transitively dependent on the primary key.
BCNF (Boyce-Codd Normal Form): A stronger version of 3NF, where every determinant
is a candidate key.
4NF (Fourth Normal Form): Meets all requirements of BCNF and ensures no multi-
valued dependencies.
5NF (Fifth Normal Form): Ensures that no join dependencies exist.

5.What are indexes in SQL? How do they work and what are their benefits and
drawbacks?
Indexes are special data structures that improve the speed of data retrieval
operations on a database table at the cost of additional writes and storage space.
Benefits:
Faster data retrieval.
Improved query performance.
Drawbacks:
Slower write operations (INSERT, UPDATE, DELETE) due to index maintenance.
Increased storage space.

6.What is a primary key? Can a table have multiple primary keys?


A primary key is a column or a set of columns that uniquely identifies each row in
a table. It cannot contain NULL values and must contain unique values.
A table cannot have multiple primary keys. However, it can have a composite primary
key, which is a primary key made up of multiple columns.

7.What is a foreign key? How does it enforce referential integrity?


A foreign key is a column or a set of columns in one table that uniquely identifies
a row in another table. The foreign key establishes a relationship between two
tables.
Referential Integrity: Ensures that the value of a foreign key corresponds to a
valid, existing value in the referenced primary key column. It prevents actions
that would destroy these links (e.g., deleting or updating a record that is being
referenced).

8.What is a view in SQL? How can it be used?


A view is a virtual table that is based on the result of an SQL query. It contains
rows and columns, just like a real table, and the fields in a view are fields from
one or more real tables in the database.
Usage: Views can be used to simplify complex queries, enhance security by
restricting access to specific data, and provide a layer of abstraction over the
actual tables.

9.Explain the difference between DELETE, TRUNCATE, and DROP commands.


DELETE: Removes rows from a table based on a condition. It can be rolled back.
DELETE FROM table_name WHERE condition;
TRUNCATE: Removes all rows from a table without logging individual row deletions.
It cannot be rolled back.
sql
Copy code
TRUNCATE TABLE table_name;
DROP: Removes the entire table structure along with its data. It cannot be rolled
back.
DROP TABLE table_name;

10.What are stored procedures? How do they differ from functions in SQL?
Stored Procedures: Precompiled collections of one or more SQL statements that can
be executed as a single unit. They can perform actions such as modifying data and
managing database transactions.
Functions: Precompiled collections of SQL statements that return a single value.
They cannot modify data and are used mainly for computations.
Differences:
Stored procedures can perform both actions (INSERT, UPDATE, DELETE) and
computations, while functions are used primarily for computations.
Functions must return a value, whereas stored procedures may or may not return a
value.

11.How can you optimize a query in SQL?


Use appropriate indexes.
Avoid using SELECT *, specify the required columns.
Use EXISTS instead of IN for subqueries.
Use joins instead of subqueries where possible.
Optimize the database schema (normalization, denormalization where necessary).
Avoid unnecessary columns in joins and where clauses.
Analyze and optimize query execution plans.

12.What is the difference between HAVING and WHERE clauses?


WHERE: Filters rows before grouping and aggregation.
SELECT column1, SUM(column2) FROM table_name WHERE condition GROUP BY column1;
HAVING: Filters rows after grouping and aggregation.

SELECT column1, SUM(column2) FROM table_name GROUP BY column1 HAVING condition;

13.What are aggregate functions? Give examples.


Aggregate functions perform a calculation on a set of values and return a single
value.
Examples:
COUNT(): Counts the number of rows.
SUM(): Calculates the total sum of a numeric column.
AVG(): Calculates the average value of a numeric column.
MAX(): Finds the maximum value in a column.
MIN(): Finds the minimum value in a column.

14.Explain the concept of transactions in SQL. What are the properties of a


transaction (ACID properties)?
A transaction is a sequence of one or more SQL operations treated as a single unit
of work. It ensures data integrity and consistency.
ACID properties:
Atomicity: Ensures that all operations within the transaction are completed
successfully or none at all.
Consistency: Ensures that the database remains in a consistent state before and
after the transaction.
Isolation: Ensures that transactions are executed independently of each other.
Durability: Ensures that once a transaction is committed, it remains permanent,
even in the event of a system failure.

15.What are subqueries? Provide an example of a correlated subquery.


A subquery is a query nested inside another query.
Correlated Subquery: A subquery that references columns from the outer query.
SELECT e1.name, e1.salary
FROM Employees e1
WHERE e1.salary > (SELECT AVG(e2.salary) FROM Employees e2 WHERE e1.department_id =
e2.department_id);

16.What is the difference between UNION and UNION ALL?


UNION: Combines the results of two or more SELECT statements and removes duplicate
rows.
SELECT column1 FROM table1
UNION
SELECT column1 FROM table2;

UNION ALL: Combines the results of two or more SELECT statements without removing
duplicates.
SELECT column1 FROM table1
UNION ALL
SELECT column1 FROM table2;

17.Explain the concept of a self-join and provide an example.


A self-join is a regular join, but the table is joined with itself.
SELECT a.employee_id, a.name, b.name AS manager_name
FROM Employees a
JOIN Employees b ON a.manager_id = b.employee_id;
18.What are triggers in SQL? How can they be used?
Triggers are special types of stored procedures that are automatically executed in
response to certain events on a particular table or view (INSERT, UPDATE, DELETE).
Usage: Enforcing business rules, validating input data, keeping audit trails, and
synchronizing tables.
CREATE TRIGGER trigger_name
AFTER INSERT ON table_name
FOR EACH ROW
BEGIN
-- trigger logic here
END;

19.What is a cursor in SQL? How does it work?


A cursor is a database object used to retrieve, manipulate, and navigate through a
result set row by row.
Working:
Declare the cursor.
Open the cursor.
Fetch rows from the cursor.
Close the cursor.
DECLARE cursor_name CURSOR FOR SELECT statement;
OPEN cursor_name;
FETCH NEXT FROM cursor_name INTO variable_list;
CLOSE cursor_name;

20.Explain the concept of window functions and provide examples of their use.
Window functions perform calculations across a set of table rows related to the
current row. Unlike aggregate functions, they do not group the result set into a
single output row.
Examples:
ROW_NUMBER(): Assigns a unique number to each row within a partition.
sql
Copy code
SELECT employee_id, salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num
FROM Employees;
RANK(): Assigns a rank to each row within a partition of the result set.
SELECT employee_id, salary, RANK() OVER (ORDER BY salary DESC) AS rank
FROM Employees;
SUM() OVER: Calculates a running total.
SELECT employee_id, salary, SUM(salary) OVER (ORDER BY employee_id) AS
running_total
FROM Employees;

You might also like