SQL MASTER SHEET 2024 Updated
SQL MASTER SHEET 2024 Updated
op
tC
no
o
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
y
op
tC
no
o
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Chapter 1 - What is SQL ?
SQL stands for Structured Query Language. “In simple language, you can consider it as a
language which can communicate with data stored somewhere. If I ask you in English, go and
bring me one medicine from a store. You will understand it and you can ask the same to a
chemist and he will give you the medicine.
Similarly, If I need to know the sales detail of some items(consider Amazon sales order details
stored in a database), then I need to ask the system about it. But unfortunately, the system
won’t understand. So, I need to ask the system in the language which it understands. We can
store data in a database. Database understands SQL. So, to fetch information, manipulate
information stored in databases, we need a language and that is our Structured Query
y
Language.”
op
We use SQL for CRUD Operations :
● CREATE - To create databases, tables, insert tuples in tables etc
● READ - To read data present in the database.
● UPDATE - Modify already inserted data.
● DELETE - Delete database, table or specific data point/tuple/row or multiple rows.
tC
Let us see the book definition:
Data analysis: SQL is used to filter, sort, and aggregate data to support decision-making and
business intelligence. It allows users to query data from multiple tables and generate
customized reports.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Scalability and performance: SQL is designed to handle large amounts of data and is
optimized for performance. It can handle millions of rows of data, making it ideal for big data
applications.
Security: SQL includes features for controlling access to data, ensuring data integrity, and
protecting against SQL injection attacks.
y
Overall, SQL is an essential tool for working with relational databases and is widely used in
op
industry and academia. Its ability to handle large amounts of data, facilitate data analysis, and
ensure data security make it an important skill for data professionals and developers.
Types of data:
There are two main types of data:
1. Quantitative Data
2. Qualitative Data
● Quantitative data is numerical data that can be measured or counted, such as sales
revenue or the number of website visits.
o
● Qualitative data is descriptive data that cannot be easily measured, such as customer
D
Understanding tables: In the context of databases, a table is a collection of related data that
is organized into rows and columns. Each row represents a single record, while each column
represents a specific attribute of the data. Tables are the primary way to store and organize data
in a relational database.
Creating and manipulating tables: To create a table, you need to define the structure of the
table, including the column names and data types. You can then use SQL commands to insert,
update, or delete data from the table.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Some common SQL commands for manipulating tables include:
● CREATE TABLE: Creates a new table
● INSERT INTO: Inserts new data into a table
● UPDATE: Updates existing data in a table
● DELETE FROM: Deletes data from a table SELECT: Retrieves data from a table
y
fundamental skill for working with databases and managing data
effectively.
op
Types of SQL
1. DQL (Data Query Language) : Used to retrieve data from databases. (SELECT)
2. DDL (Data Definition Language) : Used to create, alter, and delete database objects
tC
like tables, indexes, etc. (CREATE, DROP, ALTER, RENAME, TRUNCATE)
4. DCL (Data Control Language): Used to grant & revoke permissions. (GRANT,
no
REVOKE)
When creating a new table or editing an existing one, you must specify the type of data that
each column accepts.
D
In the below example, data passed to the id column must be an int, whilst the first_name column
has a VARCHAR data type with a maximum of 255 characters.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
department(15));
CHAR(size) FIXED length string (can contain letters, numbers, and special
characters). The size parameter specifies the column length in
characters - can be from 0 to 255. Default is 1.
y
VARCHAR(size) VARIABLE length string (can contain letters, numbers, and
special characters). The size parameter specifies the maximum
op
column length in characters - can be from 0 to 65535
TINYBLOB Hold Binary Large Objects (BOLBs) with a max length of 255
tC bytes.
BLOB(size) Hold Binary large Objects (BOLBs) with a max length of 65535
bytes.
ENUM(val1, val2, val3, A string object that can have only one value, chosen from a list of
...) possible values. You can list up to 65535 values in an ENUM list.
If a value is added that is not in the list, a blank value will be
inserted. The values are sorted in the order you enter them
SET(val1, val2, val3, ...) A string object that can have 0 or more values, chosen from a list
of possible values. You can list up to 64 values in a SET list
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Numeric Data Types SQL
BIT (size) A bit-value type with a default value for size is 1. The allowed
number of bits in a value is set via the size parameter, which can
hold values from 1 to 64.
TINYINT(size) A very small integer with a signed range of -128 to 127 and an
unsigned range from 0 to 255. Here, the size parameter specifies
the maximum allowed display width which is 255.
y
BOOL Zero is considered as false, nonzero values are considered as
true.
op
BOOLEAN Same as BOOL
SMALLINT(size) A small integer with a signed range is from -32768 to 32767 and
an unsigned range is from 0 to 65535. The size parameter
specifies the maximum display width (which is 255)
MEDIUM(size)
tC A medium integer with the signed range is from -8388608 to
8388607 and an unsigned range is from 0 to 16777215. The size
parameter specifies the maximum display width (which is 255)
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Date / Time Data Types SQL
y
current date and time
op
seconds since the Unix epoch ('1970-01-01 00:00:00' UTC).
Format: YYYY-MM-DD hh:mm:ss. The supported range is from
'1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC.
two-digit format.
o
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Chapter 3 - Operators in SQL
Arithmetic Operators
Operator Description
+ Add
- Subtract
* Multiply
y
/ Divide
% Modulo
op
Bitwise Operator tC
Operators Description
| Bitwise OR
^ Bitwise Exclusive OR
no
~ Bitwise NOT
Comparison Operators
o
Operator Description
D
= Equal to
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Chapter 4 - Functions in SQL
String Functions
Name Description
y
CHARACTER_LENGT Same as CHAR_LENGTH
H
op
CONCAT Adds two or more strings together
FIELD Return an index value relative to the position of a value within a list
of values
FIND IN SET
tC Return the position of a string in a list of strings.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
RPAD Removes any spaces from the given string.
SPACE Return a string full of spaces equal to the amount you pass it.
SUBSTR Extracts one substring from another, string from any position.
Aggregate Functions
y
Aggregate functions are used to perform calculations on a set of values and return a single
op
result. Some of the most commonly used aggregate functions in SQL include −
● COUNT() - Returns the number of rows in a table or the number of non-NULL values in a
column
● SUM() - Returns the sum of all non-NULL values in a column
●
●
tC
AVG() - Returns the average of all non-NULL values in a column
MIN() - Returns the minimum value in a column
● MAX() - Returns the maximum value in a column
Suppose there is a table containing order details: it has columns like order_no, qty,
items, date_of_order.
no
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Q5: Find out the latest order date:
Note: You can use group by order along with this function, depending on the
requirement.
y
op
tC
no
o
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Chapter 5 - More about Functions
SQL also provides a number of functions for working with date and time values. Some examples
of date and time functions in SQL include −
y
● MONTH() - Returns the month of a date
● DAY() - Returns the day of a date
op
String Functions
SQL also provides a number of string manipulation functions. Some examples of string
functions in SQL include −
●
tC
LTRIM() - Removes the leading whitespace of the string
● RTRIM() - Removes the trailing whitespace of the string
● TRIM() - Removes both leading and trailing whitespace of the string
● SUBSTRING() - Extracts a specific portion of a string
● REPLACE() - Replaces all occurrences of a specified string with another string
no
Examples:
Scalar Functions
D
Scalar functions are used to perform calculations on a single value and return a single result.
Some examples of scalar functions in SQL include −
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Conditional Functions
SQL also provides a number of functions that perform different actions based on certain
conditions. Some examples of conditional functions in SQL include −
● CASE - evaluates a list of conditions and returns a result for the first condition that is met
● IF - return a specified value if the condition is met, otherwise return another specified
value
● COALESCE - return the first non-null expression among multiple expressions
y
SELECT order_id, total_cost, CASE
WHEN total_cost > 100 THEN 'expensive'
op
WHEN total_cost > 50 THEN 'moderately priced'
ELSE 'inexpensive'
END as "price range"
FROM orders;
Output Summary: In the above query the column named ‘Price Range’ will return the value,
tC
‘expensive’ if total cost is greater than 100. If it is less than 50, then it will return ‘moderately
priced’. Else it will return ‘inexpensive’.
Example
● In this case, the COALESCE function is used to select either the "primary_phone" or
"secondary_phone" column, whichever is not null. This is useful when you have multiple
phone number columns in a table and want to display a single column with a valid phone
number.
o
● The query does not show the entire table but only these two columns. It is assumed that
there are columns named "customer_name", "primary_phone", and "secondary_phone"
in the "customers" table. The query returns a result set that contains the customer
D
names and their phone numbers, with any null values replaced by the non-null value
from the other column.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Chapter 6 - Window Functions
SQL provides a set of functions that can be used to perform calculations across a set of rows
that are related to the current row. Window functions apply aggregate and ranking functions
over a particular window (set of rows). OVER clause is used with window functions to define that
window. These functions are known as window functions.
1. RANK()
2. DENSE_RANK()
y
3. ROW_NUMBER()
op
RANK() - As the name suggests, the rank function assigns rank to all the rows within every
partition. Rank is assigned such that rank 1 given to the first row and rows having the same
value are assigned the same rank. For the next rank after two same rank values, one rank value
will be skipped. tC
DENSE_RANK() - It assigns rank to each row within the partition. Just like the rank function, the
first row is assigned rank 1 and rows having the same value have the same rank. The difference
between RANK() and DENSE_RANK() is that in DENSE_RANK(), for the next rank after two
same rank, consecutive integers are used, no rank is skipped.
ROW_NUMBER() - Assigns a unique number to each row within a result set, based on the
no
order specified in the ORDER BY clause of the function.
There is a table for customers, containing name and account balance. Next we are going to list
down the customers as per their account balance. Maximum account balance will have rank as
1. We will see rank(), dense_rank() and row_number()
o
customer_name account_name
A 1000
D
B 1000
C 3000
D 4000
E 5000
F 500
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Using RANK Function
Output_table_Below.
E 5000 1
y
D 4000 2
op
C 3000 3
A 1000 4
B 1000 4
F 500 6
tC
Note: You can notice that the rank assigned is not in the continuous order.
Using Dense_RANK
no
SELECT customer_name, account_balance, DENSE_RANK() OVER (ORDER BY
account_balance DESC) as "D_Rank" FROM customers;
Output_Table_Below
E 5000 1
D
D 4000 2
C 3000 3
A 1000 4
B 1000 4
F 500 5
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Using Row_Num
Output_Table_below
y
E 5000 1
D 4000 2
op
C 3000 3
A 1000 4
B 1000 5
F
tC 500 6
Note: You can see the same account_balance customer has a different rank here.
no
o
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Chapter 7 - Joins in SQL
In SQL, JOINs are used to return a results set which combines data from multiple tables, based
on a common column which is featured in both of them.
Types of Joins
1. Inner Join
2. Left Join
3. Right Join
y
4. Full Join
op
tC
no
Inner Join: It returns records that have matching values in both tables.
SELECT column_name
FROM table1
o
Left Join: It returns all records from the left table and match records from the right table.
SELECT column_name
FROM table1
LEFT JOIN table2
On table1.column_name = table2.column_name;
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Right Join: It returns all records from the right table and the match records from the left table.
SELECT column_name
FROM table1
RIGHT JOIN table2
On table1.column_name = table2.column_name;
Full Join: It returns all records when there is a match in either the left table or right table.
y
SELECT column_name
op
FROM table1
FULL OUTER JOIN table2
On table1.column_name = table2.column_name
WHERE condition; tC
no
o
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Chapter 8 - KEYs in SQL
1. Primary key
2. Unique Key
3. Candidate Key
y
4. Super Key
5. Foreign Key
op
6. Alternate Key
7. Composite Key
Primary Key:
Employee
Employee_ID
no
Employee_name
Employee_address
Passport_number
License_number
o
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Unique Key:
● A unique key is a set of one or more fields/columns of a table that uniquely identify a
record in a database table.
● It is like a Primary key but it can accept only one null value and it can not have duplicate
values.
Candidate Key:
y
● A candidate key is an attribute or set of attributes that can uniquely identify a tuple.
● Except for the primary key, the remaining attributes are considered a candidate key. The
candidate keys are as strong as the primary key.
op
Super key:
A super key is a set of one or more than one key that can be used to identify a record uniquely
in a table.
tC
Example: Primary key, Unique key, Alternate key are a subset of Super Keys.
The super key in SQL can be defined as a set of one or more than one key that can be used to
identify a certain type of data in a table. This key includes only those fields which include a
unique value.
no
Foreign key:
Alternate key:
o
● An Alternate key is a key that can work as a primary key. Basically, it is a candidate key
D
The alternate key is a column or collection of columns in a table that can uniquely identify each
row in that table. Every table of the database table can have multiple options for a primary key
to be configured but out of them, only one column can be set as the primary key. All the keys
which are not primary keys are called the alternate keys of that table.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Composite Key:
● Whenever a primary key consists of more than one attribute, it is known as a composite
key. This key is also known as the Concatenated Key.
y
op
tC
no
o
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Chapter 9 - Sub-Queries in SQL
● Subqueries, also known as nested queries or inner queries, allow you to use the result of
one query (the inner query) as the input for another query (the outer query).
● Subqueries are often used to retrieve data that will be used for filtering, comparison, or
calculation within the context of a larger query.
● The outer query can contain the SELECT, INSERT, UPDATE, and DELETE statements.
We can use the subquery as a column expression, as a condition in SQL clauses, and
with operators like =, >, <, >=, <=, IN, BETWEEN, etc.
y
They are a way to break down complex tasks into smaller, manageable steps.
op
Following are the rules to be followed while writing subqueries −
● A subquery consists of all the clauses an ordinary SELECT clause can contain: GROUP
BY, WHERE, HAVING, DISTINCT, TOP/LIMIT, etc. However, an ORDER BY clause is
only used when a TOP clause is specified. It can't include COMPUTE or FOR BROWSE
no
clauses.
● A subquery can return a single value, a single row, a single column, or a whole table.
They are called scalar subqueries.
Syntax:
o
SELECT columns
FROM table
D
Syntax Explanation:
● Columns refers to the specific columns you want to retrieve from the outer query.
● Table is the name of the table you're querying.
● Column is the column you're applying the operator to in the outer query.
● OPERATOR is a comparison operator such as =, >, <, IN, NOT IN, etc.
● (SELECT column FROM table WHERE condition) is the subquery that provides the input
for the comparison.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Example:
Products_table
1 laptop 50000
y
2 mobile_phone 2000
3 headphones 2000
op
Orders_table
101
tC 1 2
102 3 1
For Example:
no
Retrieve the product names and quantities for orders with a total cost greater than the average
price of all products.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Differences Between Subqueries and Joins:
Purpose Retrieve data for filtering, comparison, or Combine data from related
calculation within the context of a larger tables based on specified
query. conditions.
y
Data Source Result of one query used as input for Data from multiple related
another query. tables.
op
Combining Rows Not used for combining rows; used to Combines rows from different
filter or evaluate data. tables based on specified join
conditions.
Performance Subqueries can be slower and less Joins can be more efficient
Considerations efficient, especially when dealing with for combining data from
large datasets. multiple tables
for simple tasks or smaller datasets. but are more suited for
handling large-scale data
retrieval and combination
tasks.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Chapter 10 - View in SQL
A view is essentially a SQL results set that gets stored in the database under a label, so you
can return to it later, without having to rerun the query.
These are especially useful when you have a costly SQL query which may be needed a number
of times, so instead of running it over and over to generate the same results set, you can just do
it once and save it as a view.
y
Create a View
op
CREATE VIEW priority_users AS
SELECT * FROM users
WHERE country = “Germany”;
tC
Then in feature, if you need to access the stored result set, you can do so like this:
Replacing Views
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
FREQUENTLY ASKED INTERVIEW QUESTIONS
● The DELETE command is used to remove rows from the table, and the WHERE clause
can be used for a conditional set of parameters. Commit and Rollback can be performed
after the delete statement.
y
● TRUNCATE removes all rows from the table. Truncate operation cannot be rolled back.
op
2. What are local and global variables?
● Local variables are the variables which can be used or exist inside the function. They are
not known to the other functions and those variables cannot be referred to or used.
Variables can be created whenever that function is called.
●
tC
Global variables are the variables which can be used or exist throughout the program.
Same variable declared in global cannot be used in functions. Global variables cannot
be created whenever that function is called.
In SQL, an index is a database object that is used to speed up the retrieval of data from a table.
An index is essentially a data structure that contains a copy of selected columns from a table or
view, along with pointers to the corresponding rows in the table.
When a query is executed that involves filtering, sorting, or joining data from a table, the
database engine can use the index to quickly locate the relevant rows, rather than scanning the
entire table. This can significantly improve the performance of queries, especially when dealing
o
Indexes are typically created on columns that are frequently used in queries and that contain a
large number of distinct values.
For example, if you have a table of customer orders and frequently query the data by customer
ID or order date, you might create indexes on the customer_id and order_date columns.
There are several types of indexes that can be used in SQL, including clustered indexes,
non-clustered indexes, and full-text indexes. The type of index used depends on the specific
requirements of the query and the structure of the underlying table.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Indexes can be created using the CREATE INDEX statement in SQL, and can be dropped using
the DROP INDEX statement. However, it's important to note that creating too many indexes on
a table can have a negative impact on performance, as the database engine must spend more
time updating the indexes whenever data is added, updated, or deleted from the table. As such,
it's important to carefully consider which columns to index and how many indexes to create on a
given table.
Constraint can be used to specify the limit on the data type of table. Constraint can be specified
y
while creating or altering the table statement.
op
Data Integrity defines the accuracy and consistency of data stored in a database. It can also
define integrity constraints to enforce business rules on the data when it is entered into the
application or database.
tC
6. What is auto increment?
Auto increment keyword allows the user to create a unique number to be generated when a new
record is inserted into the table. AUTO INCREMENT keyword can be used in Oracle and
IDENTITY keyword can be used in SQL SERVER.
no
Functions are methods used to perform data operations. SQL has many inbuilt functions used to
perform string concatenations, mathematical calculations etc. SQL functions are categorized
into the following two categories: Aggregate Functions and Scalar Functions.
The Aggregate Functions in SQL perform calculations on a group of values and then return a
o
single value.
D
1. Count()
2. Sum()
3. Avg()
4. Min()
5. Max()
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
8. What is an alias in SQL?
SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are
often used to make column names more readable. An alias only exists for the duration of that
query. An alias is created with the AS keyword.
OLAP
Online Analytical Processing (OLAP) consists of a type of software tool that is used for data
y
analysis for business decisions. OLAP provides an environment to get insights from the
database retrieved from multiple database systems at one time.
op
The primary objective is data analysis and not data processing.
OLTP
The primary objective is data processing and not data analysis. Unlike OLAP systems, the goal
of OLTP systems is serving real-time transactions.
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Order Table
y
op
10. How would you select all columns from the orders table but only the rows where
the quantity is greater than 1?
Answer: - tC
SELECT * FROM orders WHERE quantity > 1;
11. How would you select the product, quantity, and order_date columns from the orders
table and order the results by the order_date in ascending order?
no
Answer: -
12. How would you insert a new order into the orders table with order_id 5, customer_id
o
Answer: -
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
13. How would you find the most frequently ordered product in the orders table?
Answer: -
y
We will start off by giving the keywords ALTER TABLE, then we will follow it up by giving the
original name of the table, after that, we will give in the keywords RENAME TO and finally, we
op
will give the new table name.
For example
If we want to change the “employee” table to “employee_information”, this will be the command:
tC
ALTER TABLE employee RENAME TO employee_information;
16. What is the difference between CHAR and VARCHAR2 data types in SQL?
char stores only fixed-length character string data types whereas varchar stores variable-length
string where an upper limit of length is specified.
CHAR Datatype
The CHAR data type is used to store character string values. The maximum length of a CHAR
o
value is 256 characters in MySQL and 2000 bytes in the Oracle database. It is used to store
strings of alphanumeric and special characters.
D
VARCHAR Datatype
The VARCHAR data type is used to store variable-length character string values. The maximum
length of a VARCHAR value is 2000 bytes in the Oracle database. It is used to store strings of
alphanumeric and special characters.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
17. What is cross join?
A cross join, also known as a Cartesian product, is a type of join operation in SQL that produces
a result set that is the combination of every row from two or more tables. In other words, a cross
join returns the Cartesian product of the tables involved in the join.
Syntax
SELECT column_name(s)
FROM table1
y
CROSS JOIN table2;
op
Example:
UNION operator is used to combine the results of two tables, and it eliminates duplicate rows
from the tables.
no
MINUS operator is used to return rows from the first query but not from the second query.
Matching records of the first and second query and other rows from the first query will be
displayed as a result set.
19. What is the difference between a PRIMARY Key and UNIQUE Key?
D
Primary key and unique are Entity integrity constraints. Primary key allows each row in a table to
be uniquely identified and ensures that no duplicate rows exist and no null values are entered.
Unique key constraint is used to prevent the duplication of key values within the rows of a table
and allow null values. (In oracle, one null is not equal to another null).
1) Unique keys in a table can be null, at-least one but primary key can’t be null in any table in
relation to databases like MySQL , Oracle etc.
2) Primary keys can be a combination of more than one unique key in the same table.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
3) There can be only one primary key per table in relation to databases e.g. MySQL, Oracle or
Sybase but there can be more than one unique key per table.
4) Unique key is represented using a unique constraint while primary key is created using
primary key constraint in any table and it automatically gets unique constraint.
5) Many database engines automatically put a clustered index on the primary key and since you
can only have one clustered index per table, it’s not available to any other unique key at the
same time.
y
20. Difference Between DELETE, TRUNCATE, DROP command in SQL
DELETE
op
● Delete is a DML Command as it is just used to manipulate/modify the table data. It does
not change any property of a table.
● The DELETE command is used to remove rows from a table. A WHERE clause can be
used to only remove some rows. If no WHERE condition is specified, all rows will be
removed.
tC
● After performing a DELETE operation, you need to COMMIT or ROLLBACK the
transaction to make the change permanent or to undo it.
● It removes rows row-by-row one at a time and records an entry in the Transaction logs,
no
● Every deleted row is locked, thus it requires more locks and database resources. This
operation will cause all DELETE triggers on the table to fire.
TRUNCATE
● TRUNCATE is a DDL Command as it resets IDENTITY columns, de-allocates Data
o
Pages and empty them for use of other objects in the database.
D
● TRUNCATE removes all rows from a table. Does not require a WHERE clause , so you
cannot filter rows while Truncating.
● The operation cannot be rolled back and no triggers will be fired because it does not
operate on individual rows.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
DROP
● Drop is a DDL command
● All the tables' rows, indexes and privileges will also be removed.
● Some objects like Views, Stored Procedures that references the dropped table are not
dropped and must be explicitly dropped
y
● Cannot drop a table that is referenced by any Foreign Key constraint.
op
● The operation cannot be rolled back.
2. UNION ALL: The UNION ALL command is equal to the UNION command, except that
no
The difference between Union and Union all is that Union all will not eliminate duplicate rows,
instead it just pulls all rows from all tables fitting your query specifics and combines them into a
table.
o
DECODE: Decode are a function in sql.It's a way of converting a written code into
understandable language.
CASE: Case are the statement in sql.It's a way of responding to the occurrence of a value or
what action to be performed when a particular value occurs.
DECODE CASE
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
DECODE is a function CASE is a statement
DECODE is not use in the WHERE clause CASE is used in the WHERE clause.
DECODE can be used only in SQL CASE can be used both SQL and PL/SQL
DECODE works with equality check(=) CASE works with other relational operators
like (>, <, >=, <=) as well equality check (=).
DECODE works with different data types. CASE does not work with different data types.
Except datatype consistency.
DECODE can work with only scalar values. CASE can work with logical operators,
y
predicates and searchable subqueries.
op
Syntax of CASE Statement
CASE [expression]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
ELSE result
tC
WHEN condition_n THEN result_n
END case_name
22. How to change column datatype in SQL database without losing data?
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Answer:
A super key is a set of attributes of a relation schema upon which all attributes of the schema
are functionally dependent. No two rows can have the same value of super key attributes.
A Candidate key is minimal super key, i.e., no proper subset of Candidate key attributes can be
a super key.
A Primary Key is one of the candidate keys. One of the candidate keys is selected as most
important and becomes the primary key. There cannot be more than one primary keys in a
table.
y
Foreign key is a field (or collection of fields) in one table that uniquely identifies a row of
another table.
op
23. What is database normalization?
Answer:
It is a process of analyzing the given relation schemas based on their functional dependencies
and primary keys to achieve the following desirable properties:
tC
1)Minimizing Redundancy
2) Minimizing the Insertion, Deletion, And Update Anomalies Relation schemas that do not meet
the properties are decomposed into smaller relation schemas that could meet desirable
properties.
no
Answer: Yes, a correlated subquery is a type of subquery in SQL where the inner query
references a column from the outer query. The inner query is executed for each row of the outer
query, and the result is used to filter or aggregate the outer query.
o
Suppose we have two tables, 'employees' and 'salaries', where 'employees' contains information
about each employee and 'salaries' contains their salary history.
employee_table
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
id name
1 shivan
2 rahul
3 shubham
Salary table
y
id salary emp_id
1 50000 1
op
2 55000 1
3 75000 2
4 80000 2
5
tC 85000 3
We want to find the names of all employees whose latest salary is greater than or equal
to 7500.
no
Here's how we can use a correlated subquery to accomplish this:
SELECT name
FROM employees e
WHERE (SELECT MAX(salary)
FROM salaries
o
In this example, the correlated subquery (SELECT MAX(salary) FROM salaries WHERE
D
emp_id = e.id) is executed for each row of the 'employees' table. It returns the maximum salary
for the current employee, and this value is compared to 75000 in the outer query's WHERE
clause to filter the results.
Note that the subquery references the 'emp_id' column from the outer query's 'employees' table.
This creates a dependency between the inner and outer queries, and the subquery cannot be
executed independently of the outer query.
25. When we should use Union, can you explain any such scenario you have faced?
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Answer: The UNION operator in SQL is used to combine the result sets of two or more
SELECT statements into a single result set.
Here's an example scenario where UNION can be used: Suppose you have two tables with
similar structures, and you want to combine the data from both tables into a single result set.
For example, you may have a customers table and a vendors table, both of which have a name
and email column.
You want to combine the data from both tables into a single result set that contains all of the
y
unique names and email addresses.
op
SELECT name, email
FROM customers
UNION
SELECT name, email
FROM vendors;
tC
In this example, the UNION operator is used to combine the results of two SELECT statements,
one that selects the name and email columns from the customers table, and another that
selects the same columns from the vendors table.
no
The UNION operator removes any duplicate rows from the combined result set, so you end up
with a result set that contains all of the unique names and email addresses from both tables.
Answer: An index in SQL is a data structure that provides a quick way to look up data in a table
o
based on the values in certain columns. It's like an ordered list of pointers to the rows in a table,
sorted by the values in one or more columns. Indexes are used to speed up the retrieval of rows
from a table by providing a fast path to the data based on the values in the indexed columns.
D
● Improved Query Performance: Indexes allow the database engine to quickly locate rows
that match a certain condition in a query's WHERE clause. Without indexes, the
database would have to scan the entire table to find matching rows, which can be slow,
especially for large tables.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
● Faster Sorting and Grouping: When you use ORDER BY or GROUP BY clauses in your
queries, indexes can speed up the sorting and grouping operations by providing an
ordered view of the data based on the indexed columns.
● Efficient Joins: Indexes can also improve the performance of join operations by allowing
the database engine to quickly find matching rows between tables based on the join
conditions.
y
27. When you use the BETWEEN clause, are both numbers inclusive or exclusive?
op
When you use the BETWEEN clause in SQL, both numbers are inclusive. This means that the
range specified by BETWEEN includes both the lower and upper bounds.
SELECT
tC
FROM products WHERE price BETWEEN 10 AND 20;
This query will retrieve all rows from the products table where the price column falls within the
range of 10 to 20, including both 10 and 20. If you want to exclude either the lower or upper
bound, you would need to use comparison operators such as < or > instead of BETWEEN.
no
28. How can we find any table name using a column name?
Answer: To find a table name using a column name in SQL, you can query the system catalog
or information schema views that are available in most SQL database management systems
(DBMS). These views store metadata about the database objects, including tables and
columns. Here's an example of how you might do this using the information_schema.columns
o
view, which is a standard part of the SQL specification and is supported by many DBMS:
D
SELECT table_name
FROM information_schema.columns
WHERE column_name = 'your_column_name';
Note: Replace 'your_column_name' with the actual name of the column you are interested in.
This query will return the names of all tables in the database where a column with the specified
name is found.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
29. How to find any table when we do not remember the exact name of the table?
Answer: If you don't remember the exact name of a table but you know part of the name or
some pattern that the table names follow, you can use wildcard characters in your SQL query to
search for tables that match your criteria. In SQL, the common wildcard characters are:
Here's an example of how you might use wildcard characters to find tables based on a partial
name or pattern:
y
op
SELECT table_name
FROM information_schema.tables
WHERE table_name LIKE '%sales%';
UPDATE SET
T.column1 = S.column1,
T.column2 = S.column2
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
3. ON T.common_key = S.common_key: Defines the join condition between the target and
source tables based on the common key.
4. WHEN MATCHED THEN UPDATE: Specifies the action to take when a match is found
between the source and target tables. In this case, it updates the columns in the target
table with the values from the source table.
5. WHEN NOT MATCHED THEN INSERT: Specifies the action to take when no match is
found between the source and target tables. In this case, it inserts a new row into the
target table using the values from the source table.
y
This MERGE statement combines the functionality of UPDATE and INSERT statements into a
single operation, making it a powerful tool for synchronizing data between tables in SQL.
op
31. What is the difference between the CEIL, FLOOR and ROUND functions?
Answer:
ROUND - Rounds a positive or negative value to a specific length.
tC
Select ROUND(5.476,2) from dual;
Output: 5.45
CEILING - Evaluates the value on the right side of the decimal and returns the smallest integer
greater than, or equal to, the specified numeric expression.
no
Output: 4
FLOOR - Evaluates the value on the right side of the decimal and returns the largest integer
less than or equal to the specified numeric expression.
o
Output: 9
32. What is the Difference Between IN and EXISTS Operators and how they can be used
for different purposes?
Answer: The IN and EXISTS operators in SQL are used to filter rows based on certain
conditions, but they have different purposes and behaviors.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
● The IN operator is used to specify multiple values in a WHERE clause. It checks whether
a value matches any value in a list of values or a subquery.
● The EXISTS operator is used to check the existence of rows in a subquery. It returns
true if the subquery returns at least one row; otherwise, it returns false. Here's an
example of how the EXISTS
y
Checks if a value matches any value in Checks if a subquery returns
op
Purpose
a list of values or a subquery. any rows.
Returns true if the value matches any Returns true if the subquery
Result value in the list or subquery; otherwise, returns at least one row;
no
subquery.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Checking for the existence of
Common Use Filtering rows based on specific values
related rows in another table
Cases or a small list of values.
based on a condition.
33. What is the difference between a Local and a Global temporary table?
Answer:
● A local temporary table exists only for the duration of a connection or, if defined inside a
y
compound statement, for the duration of the compound statement.
op
● A global temporary table remains in the database permanently, but the rows exist only
within a given connection. When connection is closed, the data in the global temporary
table disappears. However, the table definition remains with the database for access
when the database is opened next time.
2. Types of Sub-Query
35. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
Answer: They specify a search condition for a group or an aggregate. HAVING is typically used
in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE
clause. Having Clause is basically used only with the GROUP BY function in a query whereas
WHERE Clause is applied to each row before they are part of the GROUP BY function in a
query.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
36. What are different Types of Join?
Answer:
1. Cross Join: A cross join that does not have a WHERE clause produces the Cartesian
product of the tables involved in the join. The size of a Cartesian product result set is the
number of rows in the first table multiplied by the number of rows in the second table. The
common example is when a company wants to combine each product with a pricing table to
analyze each product at each price.
2. Inner Join: A join that displays only the rows that have a match in both joined tables is
known as inner Join. This is the default type of join in the Query and View Designer.
y
3. Outer Join: A join that includes rows even if they do not have related rows in the joined table,
is an Outer Join. You can create three different outer join to specify the unmatched rows to be
op
included:
● Left Outer Join: In Left Outer Join all rows in the first-named table i.e. "left"
table, which appears leftmost in the JOIN clause are included. Unmatched rows
in the right table do not appear.
tC
● Right Outer Join: In Right Outer Join all rows in the second-named table i.e.
"right" table, which appears rightmost in the JOIN clause are included.
Unmatched rows in the left table are not included.
● Full Outer Join: In Full Outer Join all rows in all joined tables are included,
no
4. Self-Join: This is a particular case when one table joins to itself, with one or two aliases to
avoid confusion. A self-join can be of any type, if the joined tables are the same. A self-join is
rather unique in that it involves a relationship with only one table. The common example is when
a company has a hierarchical reporting structure whereby one member of staff reports to
another. Self-Join can be Outer Join or Inner Join.
o
Answer: A view is a virtual table based on the result-set of an SQL statement. We can create
using create view syntax.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
38. What are the uses of view?
Answer: In SQL, a view is a virtual table derived from one or more underlying tables or other
views. It does not store data itself but rather retrieves data from its underlying tables or views
when queried. Views are a powerful feature of SQL databases and can be used for various
purposes.
1. Simplifying Complex Queries: Views can encapsulate complex SQL queries into a
single, easy-to-use virtual table. This can simplify the querying process for end-users
and developers by abstracting away the complexity of the underlying data model.
y
2. Providing Data Security: Views can be used to restrict access to certain columns or
rows of a table. By creating views that expose only the necessary data to specific users
op
or roles, you can enforce security policies and prevent unauthorized access to sensitive
information.
3. Data Abstraction and Hiding Complexity: Views can hide the underlying complexity of
the database schema by providing a simplified interface to the users. This is particularly
tC
useful when the database schema is subject to change, as the views can shield the
users from the impact of these changes.
4. Reusing Queries: Views allow you to reuse complex queries across multiple parts of an
application. Instead of writing the same query logic in multiple places, you can define a
view once and then use it wherever the data it represents is needed.
no
Answer: In SQL, a trigger is a set of SQL statements that are automatically executed
("triggered") in response to certain events on a table or view. These events can include INSERT,
D
UPDATE, DELETE, or a combination of these operations. Triggers are often used to enforce
complex business rules, maintain data integrity, or automate repetitive tasks that involve
database operations.
1. Event-Based Execution: Triggers are associated with specific events (e.g., INSERT,
UPDATE, DELETE) on a table or view. When the specified event occurs, the trigger is
automatically executed.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
2. Timing: Triggers can be defined to execute either before or after the triggering event.
"Before" triggers can be used to validate or modify data before it is inserted, updated, or
deleted, while "after" triggers can be used to perform actions after the data modification
has taken place.
3. Granularity: Triggers can be defined to fire for each row affected by the triggering event
(row-level triggers) or once for the entire statement that caused the trigger to fire
(statement-level triggers).
4. Use Cases: Triggers are commonly used for enforcing complex business rules that
cannot be expressed using constraints, auditing changes to data, maintaining
denormalized data structures, and implementing cascading actions (e.g., updating
y
related records when a record is deleted).
5. Syntax: The syntax for creating a trigger varies slightly between different SQL database
op
systems, but generally involves specifying the triggering event (e.g., INSERT, UPDATE,
DELETE), the timing (BEFORE or AFTER), the affected table or view, and the SQL
statements to be executed when the trigger fires.
Example
tC
CREATE TRIGGER my_trigger
AFTER INSERT ON my_table
FOR EACH ROW
BEGIN
-- Trigger logic goes here
no
Answer: A stored procedure is like a function that contains a set of operations compiled
o
together. It contains a set of operations that are commonly used in an application to do some
common database tasks.
D
Answer: Triggers are automatically invoked in response to specific database events (e.g.,
INSERT, UPDATE, DELETE) on tables or views and are used for enforcing rules, maintaining
data integrity, and automating tasks.
Stored procedures are named sets of SQL statements that are stored in the database and can
be explicitly called to perform specific tasks or operations. They are commonly used for
encapsulating business logic, providing a standardized interface, and reusing SQL logic.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
42. What are constraints? Explain different types of constraints
In SQL, constraints are rules or conditions that are enforced on data in a table. They define the
limitations and requirements for the data that can be stored in a table, ensuring data integrity
and consistency. Constraints are used to enforce business rules, prevent invalid data from being
inserted or updated, and maintain the quality of the database.
1. Primary Key Constraint: A primary key constraint uniquely identifies each record in a
y
table. It ensures that the values in the specified column(s) are unique and not null. A
table can have only one primary key constraint.
op
2. Unique Constraint: A unique constraint ensures that the values in the specified
column(s) are unique, but unlike a primary key constraint, it allows null values. A table
can have multiple unique constraints.
4. Check Constraint: A check constraint specifies a condition that must be true for every
row in the table. It is used to enforce domain integrity by restricting the values that can
no
be stored in a column.
5. Not Null Constraint: A not null constraint ensures that a column does not contain null
values. It requires that every row in the table has a value for the specified column.
Note: Each type of constraint serves a specific purpose in defining the structure and behavior of
a database table, and they work together to ensure data integrity and enforce business rules.
o
43. . What is the difference between Cluster and Non cluster Index?
D
A clustered index reorders the way records in the table are physically stored. There can be
only one clustered index per table. It makes data retrieval faster.
A non-clustered index does not alter the way it was stored but creates a completely separate
object within the table. As a result insert and update commands will be faster.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
44. What are the advantages of a stored procedure?
y
code is executed on the database server, it can be optimized for efficient execution,
reducing network traffic and improving overall performance.
op
3. Security and Access Control: Stored procedures can be used to enforce security and
access control policies. By granting users access to specific stored procedures rather
than directly to tables, you can control what operations they can perform and ensure that
sensitive data is protected.
tC
4. Reduced Network Traffic: Since the entire SQL logic is executed on the database
server, only the results of the stored procedure need to be transmitted over the network,
reducing network traffic and improving scalability.
7. Code Reusability: Stored procedures promote code reusability by allowing the same
logic to be reused across different parts of an application or across different applications
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
45. What are the different types of normalization?
In database design , we start with one single table, with all possible columns. Lot of redundant
data would be present since it’s a single table. The process of removing the redundant data,
by splitting up the table in a well defined fashion is called normalization.
1. First Normal Form (1NF) A relation is said to be in first normal form if and only if all
underlying domains contain atomic values only. After 1NF, we can still have redundant data
2. Second Normal Form (2NF) A relation is said to be in 2NF if and only if it is in 1NF and
every non key attribute is fully dependent on the primary key. After 2NF, we can still have
y
redundant data
3. Third Normal Form (3NF) A relation is said to be in 3NF, if and only if it is in 2NF and every
op
non key attribute is non transitively dependent on the primary key
tC
no
o
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
MOST FREQUENTLY ASKED SQL QUERIES
Answer: There are many ways to find the second highest salary of Employee in SQL. You can
either use SQL Join or Subquery to solve this problem.
y
WHERE salary < (SELECT MAX(salary) FROM employees);
op
OR
SELECT MAX(Salary)
FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee);
tC
2. Write an SQL Query to find employees whose Salary is equal or greater than
10000.
no
SELECT *
FROM employees
WHERE salary >= 10000;
FROM emp
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
5. To fetch ALTERNATE records from a table. (EVEN NUMBERED)
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY some_column) AS row_num
FROM your_table
) AS numbered_rows
WHERE row_num % 2 = 0;
y
SELECT *
FROM (
op
SELECT *, ROW_NUMBER() OVER (ORDER BY some_column) AS row_num
FROM your_table
) AS numbered_rows
WHERE row_num % 2 <> 0;
SELECT *
FROM Employees
WHERE EmpName like 'S%';
o
SELECT * FROM emp minus SELECT * FROM emp WHERE rownum <=
(SELECT COUNT(*) - &n FROM emp);
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
11. Display employee names for employees whose name ends with the alphabet “n”.
SELECT employee_name
FROM employees
WHERE employee_name LIKE '%n';
12. Display the names of employees whose name starts with alphabet ”S”.
SELECT employee_name
FROM employees
y
WHERE employee_name LIKE 'S%';
13. How can I retrive all records of emp1 those should not present in emp2?
op
SELECT emp1.*
FROM emp1
LEFT JOIN emp2 ON emp1.id = emp2.id
WHERE emp2.id IS NULL;
tC
14. Display the names of employees who are working in the company for the past 5
years.
SELECT employee_name
no
FROM employees
WHERE start_date <= DATE_SUB(CURRENT_DATE(), INTERVAL 5 YEAR);
SELECT employee_name
FROM employees
WHERE department_number IN (10, 20, 30)
D
SELECT *
FROM emp
WHERE sal BETWEEN 50000 AND 65000;
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
17. Find employees with salaries more than their manager's salary.
18. This question tests you on your ability to aggregate data across multiple dimensions. It
could require a simple GROUP BY clause or a complicated RANK function.
y
Find the employees with the top 3 highest salaries in each department.
op
SELECT
d.name AS Department,
e.name AS Employee,
e.salary AS Salary
FROM (
SELECT
e.*,
tC
DENSE_RANK() OVER(PARTITION BY departmentId ORDER BY salary DESC)
AS rnk
FROM employee e
) e
JOIN department d
ON d.id = e.departmentId
no
19. Display the names of employees who are working in the company for the past 5 years.
SELECT employee_name
FROM employees
o
20. Select all records where ename starts with ‘S’ and its length is 6 char.
SELECT *
FROM your_table
WHERE ename LIKE 'S_____' ESCAPE '|';
21. Select all records from emp where job not in data_scientist or data_analyst.
SELECT * FROM emp WHERE job NOT IN ('SALESMAN', 'CLERK');
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
22. List dept no., Dept name for all the departments in which there are no employees in the
department.
23. Find the top 3 max salaries employees from our table.
y
SELECT DISTINCT sal
op
FROM emp a
WHERE 3 >= (
SELECT COUNT(DISTINCT sal)
FROM emp b
WHERE a.sal <= b.sal
)
tC
ORDER BY a.sal DESC;
WHERE :n = (
SELECT COUNT(DISTINCT sal)
FROM emp b
WHERE a.sal <= b.sal
);
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
26. Display the list of employees who have joined the company before 01st Jan 2023
or after 01st Jan 2024.
SELECT *
FROM employees
WHERE hire_date < '2023-01-01' OR hire_date > '2024-01-01';
27. Display the names of employees who are working in the company for the past 3
years.
y
SELECT employee_name
op
FROM employees
WHERE start_date <= DATE_SUB(CURRENT_DATE(), INTERVAL 3 YEAR);
28. Select all the employee grouped by deptno and sal in descending order.
tC
SELECT *
FROM employees
ORDER BY deptno, sal DESC;
29. Write a query to retrieve the EmpFname and EmpLname in a single column as
no
“FullName''. The first name and the last name must be separated with space.
30. Write a query to fetch the number of employees working in the department
“data_analyst”.
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
31. Write a query to fetch all employees who also hold the data science position
SELECT e.*
FROM employees e
JOIN positions p ON e.position_id = p.position_id
WHERE p.position_name = 'data science';
y
FROM your_table
GROUP BY column_name
HAVING COUNT(*) > 1;
op
33. Write a query to display the first and the last record from the EmployeeInfo table.
SELECT *
FROM EmployeeInfo
ORDER BY id
LIMIT 1
tC
UNION ALL
SELECT *
FROM EmployeeInfo
no
ORDER BY id DESC
LIMIT 1;
34. Write a query to retrieve EmpPostion along with total salaries paid for each of
them.
o
35. Write an SQL query to fetch only odd rows from the table.
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY column_name) AS rn
FROM your_table
) AS numbered_rows
WHERE rn % 2 <> 0;
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
36. Write a query to find all employee names whose name:
● Begin with A
● Ends with S and contains 3 alphabets
● Staying in the state Telangana
SELECT EmployeeName
FROM Employees
WHERE EmployeeName LIKE 'A%S' AND LENGTH(EmployeeName) = 5
AND State = 'Telangana';
y
37. Write a SQL query to fetch details of all department excluding department with
name “HR” and “Sales”.
op
SELECT *
FROM departments
WHERE department_name NOT IN ('HR', 'Sales');
tC
38. Write an SQL query to print details of the employee whose FIRST_NAME ends with
‘h’ and contains six alphabets.
SELECT *
FROM employee
WHERE LENGTH(FIRST_NAME) = 6 AND RIGHT(FIRST_NAME, 1) = 'h';
no
39. Write an SQL query to print details of the employee who joined in April 2022
SELECT *
FROM employees
WHERE MONTH(join_date) = 4 AND YEAR(join_date) = 2022;
o
40. Write an SQL query to print the names of employees having the highest salary in
each department.
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
41. Write an SQL query to show all departments along with the number of people in
there.
42. Write an SQL query to fetch the departments that have less than five people in
them.
y
SELECT department_id, department_name, COUNT(employee_id) AS num_employees
FROM employees
op
GROUP BY department_id, department_name
HAVING COUNT(employee_id) < 5;
43. Write an SQL query to fetch the first 50% of records from a table.
tC
SELECT *
FROM your_table
LIMIT (SELECT COUNT(*) * 0.5 FROM your_table);
44. Write an SQL query to determine the 5th highest salary without using the TOP or
limit method.
no
SELECT salary
FROM (
SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees
) ranked_salaries
o
WHERE salary_rank = 5;
D
45. Write a query to obtain relevant records from the EmployeeInfo table ordered by
Department in ascending order and EmpLname in descending order.
SELECT *
FROM EmployeeInfo
ORDER BY Department ASC, EmpLname DESC;
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
46. Write a query to print a comma separated list of student names in a grade.
47. Query to find all Employee whose name contains the word "Shivan" ignore case.
SELECT *
y
FROM employees
WHERE LOWER(employee_name) LIKE '%shivan%';
op
48. Write an SQL Query to print the name of the distinct employee whose DOB is
between 01/01/1965 to 31/12/1995.
49. Write a SQL query to find the names of employees who have a higher salary than
their managers.
no
SELECT e1.employee_name AS EmployeeName
FROM employees e1
JOIN employees e2 ON e1.manager_id = e2.employee_id
WHERE e1.salary > e2.salary;
50. Write a query to retrieve the EmpFname, EmpLname, and EmpSalary from the
EmployeeInfo table where EmpDept is not 'data_science'.
o
FROM EmployeeInfo
WHERE EmpDept <> 'data_science';
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
INTERVIEW QUESTIONS FROM TOP MNC
Question 1: Write a query to find the number of prime and non-prime items that can be stored
in the 500,000 square feet warehouse.
y
column_name type
item_id integer
op
item_type string
item_category string
square_footage decimal
tC
SELECT item_type,
CASE
WHEN item_type = 'prime_eligible' THEN FLOOR(500000 /
total_area)*num_items
no
GROUP BY item_type) q1
ORDER BY item_type DESC
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Scenario 2
Purchase History Table
Column_name type
user_id integer
purchase_date date
product_id integer
y
Question 1: Given the users purchase history, write a query to print users who have done
purchase on more than 1 day and products purchased on a given day are never repeated on any
other day.
op
SELECT user_id
FROM (
SELECT user_id, purchase_date, COUNT(DISTINCT product_id) AS
unique_products_count
tC
FROM purchase_history
GROUP BY user_id, purchase_date
) AS user_purchase_counts
GROUP BY user_id
HAVING COUNT(*) > 1
AND MAX(unique_products_count) = COUNT(DISTINCT product_id);
no
Question 3: Identify users who have made purchases on a consistent basis (e.g., at least once
a week for the past month).
D
SELECT user_id
FROM (
SELECT user_id, YEARWEEK(purchase_date) AS purchase_week
FROM purchase_history
GROUP BY user_id, purchase_week
) AS user_purchase_weeks
GROUP BY user_id
HAVING COUNT(DISTINCT purchase_week) >= 4;
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Interview Question Facebook like company
column_name type
page_id integer
page_name varchar
y
Page_likes table
op
column_name type
user_id integer
page_id integer
liked_date
tC datetime
Question 1: Write a query to return the IDs of the Facebook pages that have zero likes.
The output should be sorted in ascending order based on the page IDs.
no
select pa.page_id
from pages pa
LEFT JOIN page_likes pl on pa.page_id = pl.page_id
where pl.page_id is NULL
order by pa.page_id
o
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Question 3: Find the Facebook pages with the most number of likes.
Question 4: Calculate the total number of likes for each Facebook page.
y
SELECT p.page_id, p.page_name, COUNT(l.user_id) AS total_likes
FROM pages p
op
LEFT JOIN page_likes l ON p.page_id = l.page_id
GROUP BY p.page_id, p.page_name;
Question 5: Return the IDs of Facebook pages that have zero likes, sorted in
ascending order based on the page IDs.
tC
SELECT page_id, page_name
FROM pages
WHERE page_id NOT IN (SELECT DISTINCT page_id FROM page_likes)
ORDER BY page_id ASC;
no
monthly_card_issued table
o
column_name type
issue_month integer
D
issues_year integer
card_name string
issued_amount integer
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Question 1: Write a query that outputs the name of each credit card and the difference
in the number of issued cards between the month with the highest issuance cards and
the lowest issuance. Arrange the results based on the largest disparity.
SELECT
card_name,
MAX(issued_amount) - MIN(issued_amount) AS card_disparity
FROM monthly_cards_issued
GROUP BY card_name
ORDER BY card_disparity DESC;
y
Question 2: Calculate the total number of cards issued for each year.
op
SELECT
issue_year,
SUM(issued_amount) AS total_cards_issued
FROM monthly_cards_issued
GROUP BY issue_year
tC
ORDER BY issue_year;
Question 3: Find the months with the highest and lowest card issuance for each year.
SELECT
no
issue_year,
MAX(issued_amount) AS max_cards_issued,
MIN(issued_amount) AS min_cards_issued
FROM monthly_cards_issued
GROUP BY issue_year;
o
Customer_contracts table:
D
column_name type
customer_id integer
product_id integer
amount integer
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Products_table:
column_name type
product_id integer
product_category string
product_name string
Question 1: Write a query that effectively identifies the company ID of such Supercloud
y
customers.
op
SELECT customer_id
FROM customer_contracts c
FULL OUTER JOIN products p
on c.product_id = p.product_id
WHERE product_category IN ('Analytics','Containers','Compute')
GROUP BY customer_id
tC
having count(DISTINCT product_category) =3
SELECT
p.product_category,
no
COUNT(c.customer_id) AS contract_count
FROM products p
LEFT JOIN customer_contracts c ON p.product_id = c.product_id
GROUP BY p.product_category;
Question 3: Calculate the total contract amount for each product category.
o
SELECT
p.product_category,
D
SUM(c.amount) AS total_contract_amount
FROM products p
LEFT JOIN customer_contracts c ON p.product_id = c.product_id
GROUP BY p.product_category;
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Question 4: Find customers who have contracts in multiple product categories.
SELECT
c.customer_id
FROM customer_contracts c
INNER JOIN products p ON c.product_id = p.product_id
GROUP BY c.customer_id
HAVING COUNT(DISTINCT p.product_category) > 1;
y
Transactions_table
op
column_name type
user_id integer
spend
tC decimal
transaction_date timestamp
Question 1: Write a query to obtain the third transaction of every user. Output the user
no
transaction_date,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY transaction_date)
AS rn
D
FROM transactions
) t
WHERE rn = 3;
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Question 2: Calculate the total spend for each month across all users.
SELECT
DATE_TRUNC('month', transaction_date) AS month,
SUM(spend) AS total_spend
FROM transactions
GROUP BY DATE_TRUNC('month', transaction_date)
ORDER BY month;
Question 3: Find users whose spend has been increasing over time.
y
SELECT user_id
FROM (
op
SELECT
user_id,
spend,
LAG(spend) OVER (PARTITION BY user_id ORDER BY transaction_date) AS
prev_spend
FROM transactions
) t
tC
WHERE spend > prev_spend;
column_name type
user_id integer
name varchar
o
status varchar
D
country varchar
Question 1: Return the share of monthly active users in India. Active users are the
ones with the "open" status in the table Active_user.
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
SELECT
COUNT(CASE WHEN country = 'India' THEN user_id END) AS active_users_us,
COUNT(user_id) AS total_active_users,
ROUND(COUNT(CASE WHEN country = 'India' THEN user_id END) * 100.0 /
COUNT(user_id), 2) AS percentage_usa
FROM active_user
WHERE status = 'open'
AND EXTRACT(MONTH FROM registration_date) = EXTRACT(MONTH FROM
CURRENT_DATE)
AND EXTRACT(YEAR FROM registration_date) = EXTRACT(YEAR FROM CURRENT_DATE);
y
Question 2: Calculate the retention rate of users from one month to the next.
op
SELECT
COUNT(DISTINCT a2.user_id) AS retained_users,
COUNT(DISTINCT a1.user_id) AS total_users,
ROUND(COUNT(DISTINCT a2.user_id) * 100.0 / COUNT(DISTINCT a1.user_id),
2) AS retention_rate
FROM active_user a1
tC
LEFT JOIN active_user a2 ON a1.user_id = a2.user_id
WHERE EXTRACT(MONTH FROM a1.registration_date) = 1
AND EXTRACT(YEAR FROM a1.registration_date) = 2023
AND EXTRACT(MONTH FROM a2.registration_date) = 2
AND EXTRACT(YEAR FROM a2.registration_date) = 2023;
no
Question 3: Calculate Monthly Active Users Over Time.
SELECT
EXTRACT(YEAR_MONTH FROM registration_date) AS year_month,
COUNT(user_id) AS active_users
FROM active_user
WHERE status = 'open'
o
GROUP BY year_month
ORDER BY year_month;
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Interview Question from Tik-Tok like Company
Emails_table
column_name type
email_id integer
user_id integer
signup_date datetime
y
texts_table
column_name type
op
text_id integer
email_id integer
signup_action varchar
tC
Question 1: As a Data Analyst your work is to Write a query to find the activation rate based
upon the above table.
SELECT
ROUND(1.00
no
* SUM(CASE WHEN signup_action = 'Confirmed' THEN 1 END)
/ COUNT(DISTINCT e.email_id)
, 2) AS confirm_rate
FROM emails AS e
LEFT JOIN texts AS t
ON e.email_id = t.email_id
o
SELECT
e.user_id
FROM emails e
LEFT JOIN texts t ON e.email_id = t.email_id
WHERE t.text_id IS NULL;
All Right reserved by shivan_kumar Copying and publish the content is punishable offense
y
op
tC
no
o
D
All Right reserved by shivan_kumar Copying and publish the content is punishable offense