0% found this document useful (0 votes)
23 views70 pages

SQL MASTER SHEET 2024 Updated

Sql master sheet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views70 pages

SQL MASTER SHEET 2024 Updated

Sql master sheet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

y

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:

SQL stands for Structured Query Language, and it is used to


communicate with the Database. This is a standard language used to
perform tasks such as retrieval, updates, insertion and deletion of
data from a database.
no

Importance of SQL in data management

SQL (Structured Query Language) is a programming language used to


manage and manipulate relational databases.
o

Here are some reasons why SQL is important:


D

Data storage and retrieval:


SQL is used to create and modify database structures, as well as insert, update, and retrieve
data from tables. It is an efficient and reliable way to store and manage large amounts of data.

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.

Standardization: SQL is a standardized language used by most relational database


management systems (RDBMS). This means that knowledge of SQL is transferable between
different database platforms and companies, making it a valuable skill for developers and data
analysts.

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.

Chapter 2 - Understanding Data and Tables


What is data?
tC
Data refers to any information that can be collected, stored, and analyzed. In the context of
databases, data usually refers to structured information that is stored in tables, such as
customer information, sales transactions, or inventory data.
no

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

feedback or product reviews.

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

We can also use SQL to manipulate the structure of an existing table,


such as adding or dropping columns, changing data types, or creating
indexes for faster querying.
Overall, understanding how to create and manipulate tables is a

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)

3. DML (Data Manipulation Language): Used to modify the database. (INSERT,


UPDATE, DELETE)

4. DCL (Data Control Language): Used to grant & revoke permissions. (GRANT,
no

REVOKE)

5. TCL (Transaction Control Language): Used to manage transactions. (COMMIT,


ROLLBACK, START TRANSACTIONS, SAVEPOINT)

DATA Types in SQL


o

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.

CREATE TABLE users (


id int,
first_name varchar(15).
Last_name varchar(15),

All Right reserved by shivan_kumar Copying and publish the content is punishable offense
department(15));

String Data Types SQL

Data Types Description

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

BINARY(size) Similar to CHAR() but stores binary byte strings.

VARBINARY(size) Similar to VARCHAR() but for binary byte strings.

TINYBLOB Hold Binary Large Objects (BOLBs) with a max length of 255
tC bytes.

TINYTEXT Holds a string with a maximum length of characters. Use


VARCHAR() instead, as it fetches much faster.

TEXT(size) Holds a string with a maximum length of 65535 bytes. Again


better to use VARCHAR()
no

BLOB(size) Hold Binary large Objects (BOLBs) with a max length of 65535
bytes.

MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters.

MEDIUMBLOB Holds Binary Large Objects (BOLBs) with a max length of


16,777,215 bytes.
o

LONGTEXT Holds a string with a maximum length of 4,294,967,295


characters
D

LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295


bytes of data

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

Data Types Description

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)

INT(size) A medium integer. Signed range is from -2147483648 to


2147483647. Unsigned range is from 0 to 4294967295. The size
no
parameter specifies the maximum display width (which is 255)

INTEGER(size) Same as INT.

BIGINT(size) A large integer. Signed range is from -9223372036854775808 to


9223372036854775807. Unsigned range is from 0 to
18446744073709551615. The size parameter specifies the
maximum display width (which is 255)
o

FLOAT(p) A floating point number value. If the precision (p) parameter is


between 0 to 24, then the data type is set to FLOAT().
D

All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Date / Time Data Types SQL

Data Type Description

DATE A date. Format: YYYY-MM-DD with a supported range is from


'1000-01-01' to '9999-12-31'

DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss.


The supported range is from '1000-01-01 00:00:00' to
'9999-12-31 23:59:59'. Adding DEFAULT and ON UPDATE in the
column definition to get automatic initialization and updating to the

y
current date and time

TIMESTAMP(fsp) A timestamp. TIMESTAMP values are stored as the number of

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.

Automatic initialization and updating to the current date and time


can be specified using DEFAULT CURRENT_TIMESTAMP and
tC ON UPDATE CURRENT_TIMESTAMP in the column definition

TIME(fsp) A time in hh:mm:ss. The supported range is from '-838:59:59' to


'838:59:59'

YEAR A year in four-digit format. Values allowed in four-digit format:


1901 to 2155, and 0000. MySQL 8.0 does not support year in
no

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 AND

| Bitwise OR

^ Bitwise Exclusive OR
no

^= Bitwise Exclusive OR Assignment

~ Bitwise NOT

Comparison Operators
o

Operator Description
D

= Equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

<> Not 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

ASCII Return the equivalent ASCII value for a specific character.

CHAR Returns the character based on the ASCII code

CHAR_LENGTH Return the character length of a string

y
CHARACTER_LENGT Same as CHAR_LENGTH
H

op
CONCAT Adds two or more strings together

CONCAT_WS Adds two or more strings together with a separator

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.

FORMAT Formats a value with the specified format

LEFT Extracts a number of characters from a string (starting from left)


no
LEN Returns the length of a string

LENGTH Return the length of a string but in bytes.

LOCATE Returns the first occurrence of one string within another

LCASE Convert a string into lowercase

LOWER Same as LCASE


o

LPAD Left pad one string with another to a specific length


D

LTRIM Remove any leading spaces from the given string.

REPEAT Allow you to repeat a string

REPLACE Allow you to replace any instance of a substring within a string,


with a new substring.

REVERSE Reverse the string.

RIGHT Extracts a number of characters from a string (starting from right)

All Right reserved by shivan_kumar Copying and publish the content is punishable offense
RPAD Removes any spaces from the given string.

RTRIM 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.

SUBSTRING Same as SUBSTR

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

Q1. Find out the total number of order:

SELECT COUNT(*) FROM orders;

Q2. Find out the total qty for each order:


o

SELECT SUM(qty) FROM Orders group by order_no;


D

Q3. Find out the average of qty ordered:

SELECT AVG(qty) FROM Orders;

Q4. Find out the first order date:

SELECT MIN(date_of_order) FROM orders;

All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Q5: Find out the latest order date:

SELECT MAX(date_of_order) FROM orders;

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

Date and Time 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 −

● NOW() - Returns the current date and time


● CURRENT_DATE() - Returns the current date
● CURRENT_TIME() - Returns the current time
● YEAR() - Returns the year of a date

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:

SELECT LTRIM(‘ Sanju’) from Customer;

Output: Sanju→ here space at beginning will be removed


o

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 −

● LENGTH() - Returns the number of characters in a string


● UPPER() - Converts a string to uppercase
● LOWER() - Converts a string to lowercase
● CONCAT() - Concatenates two or more strings together
● ROUND() - Rounds a number to a specified number of decimal places

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

SELECT customer_name, COALESCE(primary_phone, secondary_phone) as "Phone


no
Number" FROM customers;

● 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.

Some examples of window functions in SQL include −

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

SELECT customer_name, account_balance, RANK() OVER (ORDER BY


account_balance DESC) as "Rank" FROM customers;

Output_table_Below.

customer_name account_name Rank

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

customer_name account_name D_RANK


o

E 5000 1
D

D 4000 2

C 3000 3

A 1000 4

B 1000 4

F 500 5

Note: You can notice that the rank assigned is continuous.

All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Using Row_Num

SELECT customer_name, account_balance, ROW_NUMBER() OVER (ORDER BY


account_balance DESC) as "Rownum" FROM customers;

Output_Table_below

customer_name account_name Rownum

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.

They also keep our database normalized.

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

INNER JOIN table2


On table1.column_name = table2.column_name;
D

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

A key is a single or combination of multiple fields in a table. It is used to fetch or retrieve


records/data rows from the data table according to the condition/requirement. Keys are also
used to create a relationship among different database tables or views.

Types of SQL Keys

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:

● It is a unique value that is used to identify a row in a table.



tC
Primary keys must contain UNIQUE values, and cannot contain NULL values.
● A table can have only ONE primary key.

Employee

Employee_ID
no

Employee_name

Employee_address

Passport_number

License_number
o

Note: Employee_ID is a primary Key in the above table.


D

CREATE TABLE Employee(


Employee_ID int NOT NULL,
Employee_name varchar(255) NOT NULL,
Employee_address varchar(255),
Passport_number int,
License_number int,
PRIMARY KEY (ID)
);

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:

● It is a key which is used to link two tables together.


● Foreign Key can have multiple null values

Alternate key:
o

● An Alternate key is a key that can work as a primary key. Basically, it is a candidate key
D

that currently is not a primary key.

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 −

● Subqueries must be enclosed within parentheses.

● Subqueries can be nested within another subquery.


tC
● A subquery must contain the SELECT query and the FROM clause always.

● 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

WHERE column OPERATOR (SELECT column FROM table WHERE condition);

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:

Let’s Create a two table: Products & Orders

Products_table

product_id product_name price

1 laptop 50000

y
2 mobile_phone 2000

3 headphones 2000

op
Orders_table

order_id product_id quantity

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.

SELECT product_name, quantity FROM Products WHERE price * quantity >


(SELECT AVG(price) FROM Products );
o
D

All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Differences Between Subqueries and Joins:

Aspect Subqueries 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.

Result Set Subqueries return scalar values, Joins return multi-column


Structure single-column results, or small result result sets.
tC sets.

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

Complexity Subqueries can be easier to understand Joins can become complex,


no

for simple tasks or smaller datasets. but are more suited for
handling large-scale data
retrieval and combination
tasks.

Versatility Subqueries can be used in various Joins are primarily used in


clauses: WHERE, FROM, HAVING, etc. the FROM clause for
combining tables.
o
D

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:

SELECT * FROM [priority_users ];


no

Replacing Views

> With the CREATE OR REPLACE command, a view can be updated.

CREATE OR REPLACE VIEW [] AS


SELECT * FROM users
o

WHERE country = “Germany” or country = “India”;


D

All Right reserved by shivan_kumar Copying and publish the content is punishable offense
FREQUENTLY ASKED INTERVIEW QUESTIONS

1. Differentiate between the DELETE and TRUNCATE commands.

● 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.

3. What is index and why is it used in SQL?


no

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

with large datasets.


D

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.

4. What are constraints?

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.

5. What is data integrity?

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

7. What are aggregate and scalar functions?

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

There are 5 types of SQL aggregate functions:

1. Count()
2. Sum()
3. Avg()
4. Min()
5. Max()

Scalar SQL Functions


The Scalar Functions in SQL are used to return a single value from the given input value.

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.

9. What is the difference between OLTP and OLAP?

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.

Benefits of OLAP Services


● OLAP services help in keeping consistency and calculation.
● We can store planning, analysis, and budgeting for business analytics within one
platform.
tC
● OLAP services help in handling large volumes of data, which helps in enterprise-level
business applications.
● OLAP services help in applying security restrictions for data protection.
● OLAP services provide a multidimensional view of data, which helps in applying
operations on data in various ways.
no

OLTP

Online transaction processing, shortly known as OLTP, supports transaction oriented


applications in a 3 tier architecture. OLTP administers day to day transactions of an
organization.
o

The primary objective is data processing and not data analysis. Unlike OLAP systems, the goal
of OLTP systems is serving real-time transactions.
D

Benefits of OLTP Services


● OLTP services allow users to read, write and delete data operations quickly.
● OLTP services help in increasing users and transactions which helps in real-time access
to data.
● OLTP services help to provide better security by applying multiple security features.
● OLTP services help in making better decision making by providing accurate data or
current data.
● OLTP Services provide Data Integrity, Consistency, and High Availability to the data.

All Right reserved by shivan_kumar Copying and publish the content is punishable offense
Order Table

order_id customer_id product quantity order_date

1 101 Phone 2 2024-01-01

2 102 Laptop 1 2024-02-01

3 103 Mouse 2 2024-03-01

4 104 Headphone 3 2024-04-01

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: -

SELECT product, quantity, order_date FROM orders


ORDER BY order_date;

12. How would you insert a new order into the orders table with order_id 5, customer_id
o

104, product 'Keyboard', quantity 3, and order_date '2020-05-01'?

Answer: -
D

INSERT INTO orders (order_id, customer_id, product, quantity,


order_date)
VALUES (5, 104, 'Keyboard', 3, '2020-05-01');

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: -

SELECT product, COUNT(product) FROM orders


GROUP BY product
ORDER BY COUNT(product) DESC
LIMIT 1;

15. How can we change a table name in SQL?

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?

The basic difference between Char and Varchar is that:


no

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:

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
CROSS JOIN Orders
tC
WHERE Customers.CustomerID=Orders.CustomerID;

18. Explain UNION, MINUS and INTERSECT commands?

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.

INTERSECT operator is used to return rows returned by both the queries.


o

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

thus is slower than TRUNCATE.

● 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.

● TRUNCATE does not return the number of deleted rows.

● The operation cannot be rolled back and no triggers will be fired because it does not
operate on individual rows.

● TRUNCATE is faster and doesn't use as much undo space as a DELETE.


● You cannot use conditions in case of truncate.

All Right reserved by shivan_kumar Copying and publish the content is punishable offense
DROP
● Drop is a DDL command

● The DROP command removes a table from the database.

● 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.

● No DML triggers will be fired.

op
● The operation cannot be rolled back.

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


tC
1. UNION: The UNION command is used to select related information from two tables,
much like the JOIN command. However, when using the UNION command all selected
columns need to be of the same data type. With UNION, only distinct values are
selected.

2. UNION ALL: The UNION ALL command is equal to the UNION command, except that
no

UNION ALL selects all values.

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

21. WHAT IS DIFFERENCE BETWEEN DECODE AND CASE?


D

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

Syntax of DECODE Statement


no
SELECT employee_name,
DECODE(employee_id, 10000, 'Permanent',
10001, 'Permanent',
10002, 'Permanent',
'Contract') Employee_type
FROM employee;
o

22. How to change column datatype in SQL database without losing data?

Answer: You can do it very easily with simple commands.


D

Command to change column datatype in SQL database:

ALTER TABLE table_name MODIFY column_name column_type;

23. What are super, primary, candidate and foreign keys?

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

24. Have you heard of correlated subquery ? Explain with examples.

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

Here's an example to illustrate how a correlated subquery works:


D

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

WHERE emp_id = e.id >= 75000;

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.

Here's an example of how to use UNION to accomplish this:

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.

26. What is index and why is it used in SQL?

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

Here's why indexes are used in SQL:

● 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.

● Constraints Enforcement: In addition to improving query performance, indexes can be


used to enforce constraints such as uniqueness or primary key constraints, ensuring
data integrity.

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.

For example, if you use the following query:

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:

● %: Matches any sequence of characters (including zero characters).


● _: Matches any single character.

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%';

30. What is the need for a MERGE statement?


tC
Answer: The MERGE statement compares the data in a source table with the data in a target
table based on a specified condition, and then performs an action (INSERT, UPDATE, or
DELETE) on the target table based on the results of the comparison. The condition can be any
valid SQL expression that evaluates to a Boolean value, and can involve one or more columns
from the source and target tables.
no

Example of a Merge Statement

MERGE INTO target_table AS T


USING source_table AS S
ON T.common_key = S.common_key
WHEN MATCHED THEN
o

UPDATE SET
T.column1 = S.column1,
T.column2 = S.column2
D

WHEN NOT MATCHED THEN


INSERT (common_key, column1, column2)
VALUES (S.common_key, S.column1, S.column2);

Here's how the MERGE statement works:

1. MERGE INTO target_table AS T: Specifies the target table and aliases it as T.

2. USING source_table AS S: Specifies the source table and aliases it as S.

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

Select CEIL(3.478) from dual;

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

Select FLOOR(9.467) from dual;


D

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

Difference Between IN and EXISTS Operators

Feature IN Operator EXISTS Operator

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.

Syntax tC value [NOT] IN (value1, value2, ...) EXISTS (subquery)

Can be used with a list of values or a Must be used with a


Subquery usage
subquery. subquery.

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

returns false. otherwise, returns false.

Often performs better than


IN, especially with large
For a large list of values, performance
datasets, as it typically stops
o

Performance may degrade as the number of values


evaluating once it finds a
increases.
matching row in the
D

subquery.

Often used with correlated


Correlated Can be used with or without correlated
subqueries to reference
Subqueries subqueries.
columns from the outer query.

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.

34. What are the properties and different Types of Sub-Queries?


tC
1. Properties of Sub-Query

● A sub-query must be enclosed in the parenthesis.


● A sub-query must be put in the right hand of the comparison operator.
● A sub-query cannot contain an ORDER-BY clause.
no

● A query can contain more than one sub-query

2. Types of Sub-Query

● Single-row sub-query, where the sub-query returns only one row.


● Multiple-row sub-query, where the sub-query returns multiple rows.
o

● Multiple column sub-query, where the sub-query returns multiple columns.


D

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

whether they are matched or not.

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

37. .What is a view in SQL? How to create one.


D

Answer: A view is a virtual table based on the result-set of an SQL statement. We can create
using create view syntax.

CREATE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition

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

5. Performance Optimization: In some cases, views can improve query performance by


precomputing joins or aggregations, especially when dealing with complex queries
involving multiple tables.

39. What is a Trigger?


o

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.

Here are some key points about triggers:

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

INSERT INTO audit_table (event_type, event_timestamp) VALUES ('INSERT',


NOW());
END;

40. What is a stored procedure?

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

41. What is the difference between Trigger and Stored Procedure?

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.

Here are the different types of constraints commonly used in SQL:

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.

3. Foreign Key Constraint: A foreign key constraint establishes a relationship between


tC
two tables by enforcing referential integrity. It ensures that the values in the specified
column(s) of the referencing table match the values in the specified column(s) of the
referenced table.

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?

Stored procedures offer several advantages in a database environment:

1. Modularity and Encapsulation: Stored procedures allow you to encapsulate complex


SQL queries and business logic into a single unit, which can be called and reused from
multiple parts of an application. This promotes modularity and makes it easier to
maintain and update the database logic.

2. Improved Performance: Stored procedures can improve performance by reducing the


amount of data transferred between the database and the application. Since the SQL

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.

5. Ease of Maintenance: Stored procedures can be updated centrally on the database


server, making it easier to maintain and update the logic without having to update
no

multiple applications. This can be particularly useful in environments with multiple


applications accessing the same database.

6. Transaction Management: Stored procedures can be used to encapsulate complex


transactions, ensuring that multiple database operations are performed atomically (i.e.,
either all succeed or none succeed). This helps maintain data consistency and integrity.
o

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

that access the same database.

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

1. SQL Query to find the second highest salary of an Employee?.

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.

Here is SQL query using Subquery:

SELECT MAX(salary) AS second_highest_salary


FROM employees

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;

3. Find the 3rd MAX salary in the emp table.

SELECT DISTINCT salary


o

FROM emp
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
D

4. Find the 3rd MIN salary in the emp table.

SELECT DISTINCT sal


FROM emp e1 where 3 = (select
COUNT(DISTINCT sal)
FROM emp e2 where e1.sal >= e2.sal);

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;

6. To select ALTERNATE records from a table. (ODD NUMBERED)

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;

7. SQL Query to find Max Salary from each department.


tC
SELECT DeptID, MAX(Salary)
FROM Employee
GROUP BY DeptID.
no
8. Write an SQL Query to find the name of an employee whose name Start with ‘S’.

SELECT *
FROM Employees
WHERE EmpName like 'S%';
o

9. Select FIRST n records from a table.

SELECT * FROM emp WHERE rownum <= &n;


D

10. Select LAST n records from a table.

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);

15. Display the names of employees working in department number 10 or 20 or 40 or


employees working as data_scientist, machine_learning or data_analyst.
o

SELECT employee_name
FROM employees
WHERE department_number IN (10, 20, 30)
D

OR job_title IN ('data_scientist', 'machine_learning', 'data_analyst');

16. How to retrive record where sal between 50000 to 65000?

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.

SELECT e.employee_name, e.salary AS employee_salary, m.salary AS


manager_salary
FROM employees e
JOIN employees m ON e.manager_id = m.employee_id
WHERE e.salary > m.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

WHERE e.rnk <= 3

19. Display the names of employees who are working in the company for the past 5 years.

SELECT employee_name
FROM employees
o

WHERE start_date <= DATE_SUB(CURRENT_DATE(), INTERVAL 5 YEAR);


D

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.

SELECT d.deptno, d.dname


FROM dept d
LEFT JOIN emp e ON d.deptno = e.deptno
WHERE e.empno IS NULL;

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;

24. Find the 3 min salaries employees from our table.

SELECT empno, ename, sal


no
FROM (
SELECT empno, ename, sal, ROW_NUMBER() OVER (ORDER BY sal) AS rn
FROM emp
) AS ranked_employees
WHERE rn <= 3;

25. How to get nth max salaries?


o

SELECT DISTINCT hiredate


FROM emp a
D

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.

SELECT CONCAT(EmpFname, ' ', EmpLname) AS FullName


FROM your_table;
o

30. Write a query to fetch the number of employees working in the department
“data_analyst”.
D

SELECT COUNT(*) AS NumberOfEmployees


FROM employees
WHERE department = 'data_analyst';

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';

32. Write a query to retrieve duplicate records from a table.

SELECT column_name, COUNT(*)

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

SELECT EmpPosition, SUM(Salary) AS TotalSalariesPaid


FROM EmployeeSalaries
GROUP BY EmpPosition;
D

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

SELECT department_id, employee_name, salary


FROM (
SELECT department_id, employee_name, salary,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary
DESC) AS rank
FROM employees
) ranked_employees
WHERE rank = 1;

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.

SELECT department_id, department_name, COUNT(employee_id) AS num_employees


FROM employees
GROUP BY department_id, department_name;

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.

SELECT Grade, GROUP_CONCAT(StudentName ORDER BY StudentName


SEPARATOR ', ') AS StudentList
FROM Students
GROUP BY 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.

SELECT DISTINCT employee_name


FROM employees
tC
WHERE DOB BETWEEN '1965-01-01' AND '1995-12-31';

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

SELECT EmpFname, EmpLname, EmpSalary


D

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

Interview Question Amazon like company


Scenario 1

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.

inventory data_type table:

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

ELSE FLOOR(MOD(500000,LEAD(total_area, 1) OVER(ORDER BY item_type) ) /


total_area)*num_items
END As item_count
FROM (SELECT item_type,
SUM(square_footage) As total_area,
COUNT(*) as num_items
from inventory
o

GROUP BY item_type) q1
ORDER BY item_type DESC
D

Question 2: Identify Prime and Non-Prime Items

SELECT item_id, item_type,


CASE WHEN item_type = 'prime_eligible' THEN 'Prime' ELSE 'not_prime'
END AS item_category
FROM inventory ;

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 2: Find users with the most number of purchases.


SELECT user_id, COUNT(DISTINCT purchase_date) AS num_purchase_days
FROM purchase_history
GROUP BY user_id
ORDER BY num_purchase_days DESC
LIMIT 10;
o

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

Pages data_type table:

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

Question 2: Identify Facebook pages with zero likes.


D

SELECT page_id, page_name


FROM pages
WHERE page_id NOT IN (SELECT DISTINCT page_id FROM page_likes);

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.

SELECT p.page_id, p.page_name, COUNT(l.user_id) AS total_likes


FROM pages p
LEFT JOIN page_likes l ON p.page_id = l.page_id
GROUP BY p.page_id, p.page_name
ORDER BY total_likes DESC
LIMIT 10;

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

Interview Question JPMorgan Chase like Company

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

Interview Question Microsoft like Company

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

Question 2: Count the number of contracts for each product category.

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;

Interview Question from UBER like Company

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

id, spend and transaction date.

SELECT user_id, spend, transaction_date


FROM (
SELECT
user_id,
spend,
o

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;

Interview Question from Hotstar like Company


no
Active_user table:

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

Question 2: Find users who have not confirmed their emails.


D

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy