SQL Notes - Practice Questions - Interview Questions
SQL Notes - Practice Questions - Interview Questions
General Questions:
1. What is SQL?
2. What is a database?
DDL includes commands like CREATE, DROP, and ALTER to define and
modify database structures.
A view is a virtual table created by a query, which can select data from
one or more tables.
A primary key uniquely identifies each row in a table and cannot have
null values.
Data integrity ensures data is accurate and consistent over its lifecycle.
General Questions:
1. What are UNION, MINUS, and INTERSECT commands?
2. What is T-SQL?
Yes, using the ALTER TRIGGER statement with the DISABLE option.
10. What is the difference between primary key and unique constraints?
Primary key cannot have null values and there can be only one primary
key per table, while unique constraints can have null values and there
can be multiple unique constraints per table.
The WITH clause defines a temporary result set that can be used in a
SELECT, INSERT, UPDATE, or DELETE statement.
19. What is the difference between SQL DELETE and SQL TRUNCATE
commands?
DELETE removes rows one at a time and logs each row deletion, while
TRUNCATE deallocates entire data pages and is faster but cannot be
rolled back.
24. What are local and global variables and their differences?
Local variables are defined within functions and have local scope, while
global variables are defined outside functions and have global scope.
25. Name the function which is used to remove spaces at the end of a string?
General Questions:
1. What is the difference between TRUNCATE and DROP statements?
TRUNCATE: Removes all rows from a table but keeps the table
structure for future use. It is faster and uses fewer system and
transaction log resources.
DROP: Deletes the table and its structure from the database completely.
12. How do we avoid getting duplicate entries in a query without using the
DISTINCT keyword?
15. Name the operator which is used in the query for appending two strings?
Coding Questions:
1. Write a query to find employees with the highest salary in each
department.
SELECT Name
FROM Employees
GROUP BY Name
HAVING COUNT(DISTINCT Department) > 1;
3. Write a query to list all departments along with the total number of
employees in each department.
4. Write a query to find all employees whose name starts with 'J' and ends
with 'n'.
5. Write a query to find the second highest salary in the employees' table
without using LIMIT or TOP.
4 Naman HR 55000
Products Table:
ProductID ProductName
1 Widget A
2 Widget B
Sales Table:
1 1 10 20
2 1 15 20
3 2 5 30
Customers Table:
CustomerID CustomerName
1 Prasad
2 Maheshwar
3 Harshitha
Orders Table:
1 1 1 2
2 2 1 1
3 1 2 3
5 2 1 2
6 3 1 1
7 1 2 1
SQL Questions:
1. Basic SQL Queries:
Question 1: Write a SQL query to find the second highest salary from
the Employees table.
SELECT MAX(Salary)
FROM Employees
WHERE Salary < (SELECT MAX(Salary) FROM Employees);
Question 3: Write a SQL query to find the total sales for each product.
Question 6: Find the employees who have the highest salary in their
respective departments, but the overall highest salary in the company.
WITH DeptMax AS (
SELECT Department, MAX(Salary) AS MaxSalary
FROM Employees
GROUP BY Department
)
SELECT e.Name, e.Department, e.Salary
FROM Employees e
JOIN DeptMax d ON e.Department = d.Department AND e.S
alary = d.MaxSalary
WHERE e.Salary = (SELECT MAX(Salary) FROM Employees);
Index
What is SQL?
CREATE DATABASE
CREATE TABLE
Data Types
INSERT INTO
SELECT
UPDATE
DELETE
String Functions
CONCAT
SUBSTRING
LENGTH
Numeric Functions
ABS
FLOOR
Date Functions
CURRENT_DATE
DATEADD
DATEDIFF
Operators
Arithmetic Operators
Comparison Operators
Logical Operators
4. SQL Clauses
WHERE Clause
Filtering Data
ORDER BY Clause
Sorting Data
GROUP BY Clause
Aggregating Data
HAVING Clause
Types of Joins
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
CROSS JOIN
Single-Row Subqueries
Multi-Row Subqueries
Correlated Subqueries
Views
Indexes
Stored Procedures
Triggers
Transactions
ACID Properties
Query Optimization
Index Optimization
Database Normalization
8. SQL Security
Introduction to SQL
What is SQL?
SQL, or Structured Query Language, is the standard language used to interact with
relational databases. It's the tool we use to communicate with a database, to
perform tasks such as retrieving data, updating records, and creating tables. Think
of SQL as a way to ask your database a question or give it an instruction. Whether
you want to find a list of customers, add a new order, or update a product's price,
SQL is the language that makes it happen.
By the late 1970s, SQL had gained traction and was adopted by several database
vendors. In 1986, the American National Standards Institute (ANSI) standardized
SQL, solidifying its role in the world of databases. Over the years, SQL has evolved,
adding new features and capabilities with each update. Major databases like
Oracle, MySQL, SQL Server, and PostgreSQL have their own versions and
extensions of SQL, but the core language remains the same.
3. Data Manipulation: SQL lets you insert, update, delete, and retrieve data
efficiently. It also supports transaction processing, ensuring data integrity.
4. Security: SQL includes robust security features, such as user permissions and
roles, to protect sensitive data.
TRUNCATE: Removes all records from a table but retains the structure for
future use.
Real-life Example: A retail store using an inventory system would use DML
commands to update stock levels as products are sold and restocked.
CREATE DATABASE
The CREATE DATABASE command is used to create a new database. A database is a
collection of tables and other objects that store and organize data.
Syntax:
Example:
Imagine you’re setting up a database for a Telugu movie rental store. You would
start by creating a database named
TeluguMoviesDB :
Real-life Example:
Think of
CREATE DATABASEas setting up a new file cabinet for organizing all the documents
related to your project. Just like you would name a file cabinet, you give your
database a name that reflects its purpose.
CREATE TABLE
The CREATE TABLE command is used to create a new table within a database. A table
is a collection of related data held in a structured format within a database. It
consists of rows and columns.
Syntax:
Example:
Continuing with the Telugu movie rental store example, you might create a table for
movies:
Real-life Example:
Creating a table is like setting up a new drawer in your file cabinet with labeled
folders (columns) where each folder holds documents (rows) of a specific type.
Data Types
Data types define the kind of data that can be stored in a column. Common data
types include:
MovieID is an integer.
ReleaseYear is an integer.
Real-life Example:
Choosing data types is like deciding what kind of documents go into each folder in
your drawer. Some folders might hold numbers, others text, and some might have
dates.
INSERT INTO
The INSERT INTO command is used to add new records to a table.
Syntax:
Example:
Adding a new Telugu movie to the
Movies table:
SELECT
The SELECT command is used to retrieve data from one or more tables. It's the most
commonly used SQL command.
Syntax:
Example:
Retrieving all movies directed by 'S. S. Rajamouli':
Real-life Example:
Using
SELECT is like pulling out documents from your drawer that match a certain criteria.
UPDATE
The UPDATE command is used to modify existing records in a table.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example:
Updating the genre of a movie:
Real-life Example:
Updating a record is like editing a document in one of your folders.
DELETE
The DELETE command is used to remove records from a table.
Syntax:
Example:
Deleting a movie from the
Movies table:
Real-life Example:
Deleting a record is like removing a document from a folder and discarding it.
String Functions
String functions allow you to manipulate text data in various ways. Here are some
of the most commonly used string functions in SQL:
CONCAT
The CONCAT function is used to combine two or more strings into one.
Example:
Imagine you have a table
with columns
Actors FirstName and LastName . You want to create a full name for
each actor.
Real-life Example:
Think of
CONCAT as pasting together different pieces of text to form a complete message. For
example, combining a first name and last name to form a full name.
SUBSTRING
The SUBSTRING function extracts a portion of a string.
Syntax:
Example:
You have a table
Movies with a column Title . You want to extract the first three characters of each
title.
Real-life Example:
Using
SUBSTRINGis like taking a specific segment of text from a paragraph, such as
extracting the first word from a sentence.
LENGTH(string);
Example:
To find out the length of movie titles in the
Movies table:
Real-life Example:
Using
is similar to counting the number of characters in a sentence, including
LENGTH
Numeric Functions
Numeric functions perform operations on numerical data. Here are some key
numeric functions:
ABS
The ABS function returns the absolute value of a number, removing any negative
sign.
Syntax:
ABS(number);
Example:
If you have a column
in the Movies table that stores the change in revenue, and you want to
RevenueChange
Real-life Example:
Using
is like considering only the magnitude of a number without its sign, similar to
ABS
ROUND
The ROUND function rounds a number to a specified number of decimal places.
Syntax:
ROUND(number, decimal_places);
Example:
Rounding the revenue of movies to the nearest thousand in the
Movies table:
Real-life Example:
Using
ROUNDis like rounding prices to the nearest dollar when shopping to simplify
calculations.
FLOOR
The FLOOR function returns the largest integer less than or equal to a number.
Syntax:
FLOOR(number);
Real-life Example:
Using
FLOOR is like rounding down a number to the nearest whole number, similar to
dropping any fractional part when dealing with counts.
Date Functions
Date functions are used to manipulate date and time values. Here are some
essential date functions:
CURRENT_DATE
The CURRENT_DATE function returns the current date.
Syntax:
SELECT CURRENT_DATE;
Example:
To get the current date in a report:
Real-life Example:
Using
CURRENT_DATE is like checking today’s date on your calendar.
DATEADD
The DATEADD function adds a specified number of intervals to a date.
Syntax:
Example:
Adding 7 days to the current date:
Real-life Example:
Using
DATEADD is like scheduling a reminder for a week from today.
DATEDIFF
The DATEDIFF function returns the difference between two dates.
Syntax:
Example:
Calculating the number of days between the release date and today's date for
movies in the
Movies table:
Real-life Example:
Using
is like calculating the number of days between two events, such as the
DATEDIFF
Operators
Operators are used to perform operations on data. Here are some commonly used
SQL operators:
Operators:
+ (Addition)
(Subtraction)
(Multiplication)
/ (Division)
% (Modulus)
Example:
Calculating the total revenue after applying a discount:
Real-life Example:
Using arithmetic operators is like calculating the total cost of items in your
shopping cart after applying discounts.
Comparison Operators
Comparison operators compare two values.
Operators:
= (Equal)
SELECT Title
FROM Movies
WHERE ReleaseYear > 2015;
Real-life Example:
Using comparison operators is like filtering search results based on criteria, such
as finding all movies released after a certain year.
Logical Operators
Logical operators are used to combine multiple conditions.
Operators:
AND
OR
NOT
Example:
Finding movies that are either action or drama and have a rating greater than 8:
SELECT Title
FROM Movies
WHERE (Genre = 'Action' OR Genre = 'Drama') AND Rating > 8;
Real-life Example:
Using logical operators is like refining your search criteria on a movie streaming
service to find movies that meet multiple conditions.
SQL Clauses
WHERE Clause
Filtering Data
The WHERE clause allows you to specify conditions that the data must meet to be
included in the result set.
Syntax:
Example:
Imagine you have a table
TeluguMovies with columns MovieID , Title , Director , and ReleaseYear . To find all
movies directed by S. S. Rajamouli:
Real-life Example:
Using the
WHEREclause is like applying a filter to your search results on a movie database to
only show movies by a specific director.
ORDER BY Clause
The ORDER BY clause is used to sort the result set by one or more columns, either in
ascending (default) or descending order.
Sorting Data
The ORDER BY clause arranges the records in a specified order.
Syntax:
Example:
To list all movies sorted by their release year in descending order:
Real-life Example:
Using the
ORDER BY clause is like sorting your movie collection by release date to find the most
GROUP BY Clause
The GROUP BY clause groups rows that have the same values in specified columns
into summary rows, like "total", "average", "count", etc.
Aggregating Data
The GROUP BY clause is often used with aggregate functions (COUNT, MAX, MIN,
SUM, AVG) to group the result set by one or more columns.
Syntax:
Example:
To find the number of movies directed by each director:
Real-life Example:
Using
is like organizing your movie list by director and then counting how many
GROUP BY
HAVING Clause
The HAVING clause is used to filter groups based on a specified condition. It is
similar to the WHERE clause but is used for groups rather than individual rows.
Example:
To find directors who have directed more than 3 movies:
Real-life Example:
Using the
HAVINGclause is like filtering a summary report to only show entries that meet
certain criteria, such as showing only those directors who have made a significant
number of films.
WHERE Clause
Let's explore more about the WHERE clause with Telugu movie examples.
Example 1:
Finding movies released after the year 2010:
Example 2:
Finding movies with the genre 'Action':
Real-life Example:
Using
WHERE is like searching for movies in your personal collection that are only from the
ORDER BY Clause
The ORDER BY clause helps organize your result set.
Example 1:
Sorting movies by title in ascending order:
Example 2:
Sorting movies by release year and then by title:
Real-life Example:
Using
ORDER BY is like sorting your movie shelf first by release year and then alphabetically
by title.
GROUP BY Clause
The GROUP BY clause helps summarize data.
Example 1:
Finding the average rating of movies by each director:
Example 2:
Counting the number of movies in each genre:
Real-life Example:
Using
GROUP BYis like categorizing your movies by genre and counting how many you
have in each category.
HAVING Clause
The HAVING clause refines your grouped data.
Example 2:
Finding directors with an average movie rating above 7:
Real-life Example:
Using
HAVING is like filtering your movie summary report to only show genres that have a
significant number of movies or directors whose movies have high ratings.
Types of Joins
Joins are used to combine rows from two or more tables based on a related
column. Let's explore the different types of joins with examples.
INNER JOIN
An INNER JOIN returns only the rows that have matching values in both tables.
Syntax:
SELECT columns
FROM table1
Example:
Suppose we have two tables,
Movies and Directors :
Title DirectorName
Eega S. S. Rajamouli
Real-life Example:
An
INNER JOIN is like finding books in a library that are written by authors present in the
authors' list.
LEFT JOIN
A LEFT JOIN returns all rows from the left table and the matched rows from the right
table. If there is no match, the result is NULL on the right side.
Syntax:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
Example:
To get a list of all movies along with their directors, including movies without a
director in the
Directors table:
Title DirectorName
Eega S. S. Rajamouli
Real-life Example:
A
LEFT JOINis like getting a list of students and their grades, including those who
haven't taken any exams yet.
RIGHT JOIN
A RIGHT JOIN returns all rows from the right table and the matched rows from the left
table. If there is no match, the result is NULL on the left side.
Syntax:
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
Example:
To get a list of all directors and the movies they have directed, including directors
with no movies:
Title DirectorName
Eega S. S. Rajamouli
NULL Sukumar
Real-life Example:
A
RIGHT JOINis like getting a list of all courses and the students enrolled in them,
including courses with no students enrolled.
FULL JOIN
A FULL JOIN returns all rows when there is a match in either the left or right table. If
there is no match, the result is NULL from the side where there is no match.
Syntax:
SELECT columns
FROM table1
FULL JOIN table2
ON table1.column = table2.column;
Example:
To get a complete list of all movies and directors, including those with no matching
records:
Title DirectorName
Eega S. S. Rajamouli
NULL Sukumar
Real-life Example:
A
is like merging two lists of employees and departments, showing all
FULL JOIN
CROSS JOIN
A CROSS JOIN returns the Cartesian product of the two tables, combining all rows
from the left table with all rows from the right table.
Syntax:
SELECT columns
FROM table1
CROSS JOIN table2;
Example:
To get all possible combinations of movies and directors:
Title DirectorName
Eega S. S. Rajamouli
Real-life Example:
A
outfit combination.
Subqueries
Subqueries are queries nested inside another query. They can be used to perform
operations that require multiple steps or to simplify complex queries.
Single-Row Subqueries
A single-row subquery returns one row. It is typically used with comparison
operators like = , < , > , etc.
Example:
Finding the director of the most recent movie:
SELECT DirectorName
FROM Directors
WHERE DirectorID = (SELECT DirectorID
FROM Movies
ORDER BY ReleaseYear DESC
LIMIT 1);
DirectorName
Trivikram Srinivas
Real-life Example:
A single-row subquery is like finding the best-performing student in a class and
then getting their details.
Multi-Row Subqueries
A multi-row subquery returns multiple rows. It is typically used with operators like
IN , ANY , ALL .
Example:
Finding all movies directed by directors who have directed more than one movie:
Eega
Real-life Example:
A multi-row subquery is like finding all courses taught by professors who teach
multiple courses.
Correlated Subqueries
A correlated subquery is a subquery that uses values from the outer query. It is
executed once for each row processed by the outer query.
Example:
Finding movies where the director has directed another movie in the same year:
SELECT Title
FROM Movies m1
WHERE EXISTS (SELECT 1
FROM Movies m2
WHERE m1.DirectorID = m2.DirectorID
AND m1.ReleaseYear = m2.ReleaseYear
AND m1.MovieID <> m2.MovieID);
Real-life Example:
A correlated subquery is like checking each student's score and comparing it with
the class average to identify above-average students.
Views
A view is a virtual table based on the result set of an SQL query. Views simplify
complex queries, enhance security, and make data more accessible.
Example:
Imagine we have a table
TeluguMovies and we want to create a view that shows only movies directed by 'S. S.
Rajamouli'.
Managing Views
Views can be updated, dropped, or replaced as needed.
Updating a View
Dropping a View
Real-life Example:
Creating a view is like setting up a specific filter or report in your software
application that shows only relevant data to the user without them needing to write
complex queries.
Indexes
Indexes improve the speed of data retrieval operations on a database table at the
cost of additional storage space and slower write operations.
1. Clustered Index: Determines the physical order of data in a table. Each table
can have only one clustered index.
2. Non-Clustered Index: Does not alter the physical order of the data. Each table
can have multiple non-clustered indexes.
Example:
Creating an index on the
Title column of the TeluguMovies table.
Example:
Creating a unique index on the
MovieID column.
Dropping an Index
Syntax:
Example:
Dropping the index on the
Title column.
Real-life Example:
Using an index is like having a detailed table of contents in a book that allows you
to quickly find the information you need without flipping through every page.
Stored Procedures
Stored procedures are a collection of SQL statements that can be executed as a
single unit. They help in reusing code and improving performance.
Example:
Creating a stored procedure to add a new movie.
Real-life Example:
A stored procedure is like a macro in Excel that performs a series of actions
automatically when you run it.
Triggers
Triggers are special types of stored procedures that automatically execute in
response to certain events on a table or view.
Example:
Creating a trigger that logs changes to the
TeluguMovies table.
Real-life Example:
A trigger is like a notification system that alerts you whenever specific changes
happen in your database.
Transactions
Transactions are used to ensure that a series of SQL operations are executed as a
single unit of work. They follow the ACID properties.
ACID Properties
1. Atomicity: Ensures that all operations within a transaction are completed
successfully. If not, the transaction is aborted and no changes are made.
2. Consistency: Ensures that a transaction brings the database from one valid
state to another.
COMMIT;
Example:
BEGIN TRANSACTION;
UPDATE TeluguMovies SET ReleaseYear = 2020 WHERE MovieID = 1;
COMMIT;
ROLLBACK
The ROLLBACK statement is used to undo changes made during the current
transaction.
Syntax:
ROLLBACK;
Example:
BEGIN TRANSACTION;
UPDATE TeluguMovies SET ReleaseYear = 2020 WHERE MovieID = 1;
ROLLBACK;
SAVEPOINT
Syntax:
SAVEPOINT savepoint_name;
Example:
BEGIN TRANSACTION;
UPDATE TeluguMovies SET ReleaseYear = 2020 WHERE MovieID = 1;
SAVEPOINT Savepoint1;
UPDATE TeluguMovies SET Genre = 'Drama' WHERE MovieID = 2;
ROLLBACK TO Savepoint1;
COMMIT;
Real-life Example:
Using
, ROLLBACK , and SAVEPOINT is like writing in pencil. You can save your work
COMMIT
Query Optimization
Query optimization is the process of improving the efficiency of SQL queries. This
involves using strategies to reduce the time and resources required to execute
queries.
Example:
Real-life Example:
Reading an execution plan is like following a recipe to see each step involved in
cooking a dish. It helps identify where you might save time or improve efficiency.
Index Optimization
Indexes improve query performance by allowing faster data retrieval. However, too
many indexes or poorly designed indexes can degrade performance.
Creating Effective Indexes:
Real-life Example:
Using indexes effectively is like having an optimized filing system where frequently
accessed files are easy to find, improving overall efficiency.
Database Normalization
Normal Forms
1. First Normal Form (1NF): Ensures that each column contains atomic
(indivisible) values and each entry in a column is of the same data type.
Example:
Before 1NF:
MovieID Director
1 S. S. Rajamouli, S. S. Rajamouli
After 1NF:
MovieID Director
1 S. S. Rajamouli
1 S. S. Rajamouli
2. Second Normal Form (2NF): Achieves 1NF and ensures that non-key columns
are fully dependent on the primary key.
Example:
Before 2NF:
After 2NF:
1 Baahubali 101
2 Eega 101
DirectorID DirectorName
101 S. S. Rajamouli
Example:
Before 3NF:
After 3NF:
1 Baahubali 101
101 S. S. Rajamouli 47
1 Baahubali 101
DirectorID Country
101 India
Real-life Example:
Normalization is like organizing your library by genres, authors, and publication
years to avoid duplication and ensure easy access to books.
Example:
Identifying a slow query:
Add an index:
Example:
Using a transaction with a smaller scope:
BEGIN TRANSACTION;
UPDATE TeluguMovies
SET ReleaseYear = 2021
WHERE MovieID = 1;
COMMIT;
Upgrade hardware.
Real-life Example:
Resolving performance bottlenecks is like fixing a traffic jam by identifying the
cause (slow cars, roadblocks) and taking corrective actions (building a bypass,
managing traffic flow).
SQL Security
User Management
Effective user management is crucial for database security. It involves creating and
managing database users and ensuring that only authorized individuals have
access to the database.
Creating a User
Syntax:
Example:
Creating a user named
telugu_movie_admin :
Managing Users
You can manage users by changing their passwords, renaming them, or deleting
them.
Renaming a User
Deleting a User
Real-life Example:
Creating and managing users is like giving employees their own access cards to
enter different parts of a building, and ensuring their access is updated or revoked
as needed.
Syntax:
Example:
Granting SELECT and INSERT privileges to
telugu_movie_admin on the TeluguMoviesDB :
Revoking Privileges
Syntax:
Example:
Revoking INSERT privilege from
telugu_movie_admin :
Creating Roles
Roles are created to group specific privileges and then granted to users.
Syntax:
Example:
Creating a role for read-only access and assigning it to a user:
Real-life Example:
Granting and revoking privileges is like giving an employee keys to certain rooms in
a building and taking back keys when they no longer need access.