0% found this document useful (0 votes)
18 views

SQL Interview Qns-4

SQL

Uploaded by

Kiran Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

SQL Interview Qns-4

SQL

Uploaded by

Kiran Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

1) what is SQL ?

SQL (Structured Query Language) , that helps to manipulate and manage data in
relational databases.
SQL is used to communicate and connect with a database to create, modify,
retrieve, and delete data.

2) what is data ?
Data is a collection of information.
It can be used in a variety of forms like text, numbers, media, bytes, etc.

3) What is Data Integrity ?


To ensuring that each row of a table is uniquely identified ,
so that data can be retrieved separately.

4)what is database ?
A database is an organized collection of data, so that it can be easily
accessed and managed.

5) what is DBMS ?
In DBMS, data is generally stored in either a hierarchical form or a
navigational form.

6) what is RDBMS ?
In RDBMS, the tables have an unique identifier called primary key and the
data values are stored in the form of tables.

7) Difference between DBMS and RDBMS ?


DBMS
DBMS stores data as file.
Data is stored in hierarchical form.
Normalization not present.
No security to data manipulation.
No relation between the tables.
RDBMS
RDBMS stores data in tabular form.
Tables have a unique identifier called the primary key to identify tuples
uniquely.
Normalization present.
Defines integrity constraints for ACID properties.
Relationship between data values is stored as a table.

8) Typical ER model and types ?


Describes data as Entities,Attributes and Relationship

Entity : Real world thing. e.g Person,Car..etc


Attributes : Properties that describs the entity. e.g Name,
Address,Brand..etc
Relationship : A set of asssociation among entity. e.g Emp work for
department , car belongs to person.

Here, we can define relationships between tables using foreign


keys,
which links the primary key of one table to the foreign key of
another table.

9) Three types of Relatonship ?


One-to-One Relationship
Description of a product.
A female can marry to one male, and a male can marry to one female.
One-to-many relationship
A Class taught by only one teacher .
Many-to-many relationship
A Customers orders may contain more products.
Many-to-one relationship
Students enroll for only one course .

10) what is Normalisation ?


Normalization is the process of organizing the data in the database
Normalization is used to reduce the redundancy of data rows
Normalization is used to minimize the dependency of data column
Normalization divides the larger table into smaller and links them using
relationships

11) Types of Normalisation ?


1NF A relation is in 1NF if it contains an atomic value.
2NF A relation will be in 1NF and all non-key attributes are fully
functional dependent on the primary key.
3NF A relation will be in 2NF and no transition dependency exists.

12) Languages / Commandas / Subsets of SQL ?


There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

13) What is DDL/DML/DQL/DCL/TCL ?


DDL changes the structure of the table like creating a table, altering a
table, droping a table ,etc -- Create, Alter,Truncate,Drop
DML commands are used to modify the database. It is responsible for all form
of changes in the database. -- Insert, Update, Delete
DCL commands are used to grant and take back authority from any database
user. -- Grant, Revoke
TCL commands can only use with DML commands like INSERT, UPDATE and DELETE .
-- Commit, Rollback, SavePoint
DQL is used to fetch the data from the database. -- Select

14) What is Primary key ?


Set of columns which is uniquely identified the rows. -- e.g Student_id

15) What is Foreign Key ?


A FOREIGN KEY is a field in one table that refers to the PRIMARY KEY in
another table.
The table with the foreign key is called the child table,and the table with
the primary key is called the parent table.

16) PK = Unique + Not null ?


Unique -> There is No Duplicate Values, it's Shows Null values,if its
applicable -- e.g Pancard
Not null -> it's always have some values

17) What is Candiate Key ?


Eligible Primary Keys are Candidate Key.

18) What are constraints ?


Constrains are used to maintain the accuracy of the database.
Not null, Unique, Primary Key,Foreign Key, Check, default .

Not null -> it's always have some values


Unique -> There is No Duplicate Values, it's Shows Null values,if
its applicable -- e.g Pancard
Primary Key -> Set of columns which is uniquely identified the rows.
Foreign Key -> A FOREIGN KEY is a field in one table that refers to the
PRIMARY KEY in another table.
The table with the foreign key is called the child table,and
the table with the primary key is called the parent table.
Check -> The CHECK constraint is used to limit the value range that
can be placed in a column

19) Check Constraints ?


The CHECK constraint is used to limit the value range that can be placed in a
column

20) Differentiate Delete , Drop & Truncate ?


Delete -> Deletes Specific rows and whole records/database from a table ,
Size of a block will appear and we can rollback because this will
store another place.
Truncate -> Truncates all data from a existing table , the table structure
will appear and
Size of a block will appear and we can't rollback. Speed is high.
Drop -> Drop an entire table from a database and the table structure will
not appear and Size also not appear.

21) Sorting Querry ?


Sorting is used to sort the records, In SQL using ORDER BY Keyword.
The ORDER BY keyword is used to sort the result-set in ascending or
descending order.
The ORDER BY keyword sorts the records in ascending order by default.
To sort the records in descending order, use the DESC keyword after the
attributes.

22) Differentiate Where and having clause ?


In SQL, the WHERE clause is used to filter rows based on a condition of a
column,
while the HAVING clause is used to filter groups based on an aggregate
function.

23) Differentiate Group by & Order by ?


Group by statement is used to group the rows that have the same value.
Whereas Order by statement sort the result-set either in ascending or in
descending order.

24)What is joins and its types ?


The join function is used to combine the two or more tables in related to the
column,
which is used to represent the multiple tables in a single data set.

Natural Join -> Returns records that have matching values in both
tables without ON Clause
(Inner) Join -> Returns records that have matching values in both
tables with ON Clauese
Left (Outer) Join -> Returns all records from the left table, and the
matched records from the right table
Right (Outer) Join -> Returns all records from the right table, and the
matched records from the left table
Self Join -> A self join is a regular join, but the table is joined
with itself.
Full (Outer) Join -> Returns all records when there is a match in either
left or right table
Cross Join -> The CROSS JOIN returns all matching records from both
tables whether the other table matches or not.
Joins every row of the first table to every row of the
second table
e.g., So, if there are rows in "Customers" that do not have
matches in "Orders", or if there are rows in "Orders" that
do not have matches in "Customers", those rows will be listed as well.

25) what is sub query ?


A subquery is a query that is embedded within another query.
It retrieves data used in the main query as a condition.

26) Differentiate Correlated subquery vs Nested subquery ?


Correlated subquery -> Inner query uses values from Outer query.
Nested subquery -> Outer query is executed with result from Inner query

27) Pattern matching / Wildcards ?


A wildcard character is used to finding the one or more characters in a
string.
Wildcard characters are used with the LIKE operator.
The LIKE operator is used in a WHERE clause to search for a specified pattern
in a column.
E.g., a% - Starts with a , %a - ends with a , a%a - starts with a and ends
with a , %new% - if the word new will show,

28) What is Regular Expression ?


A regular expression is a powerful way of specifying a pattern for a complex
search.
where regexp_like '^[j|L]' (or) '[^j|^L] -> jack Lakshman ----- where
regexp_like '^s[e|a|h]' -> Starts with a after that e or a or h -> se,sa,sh
where regexp_like 'a$' -> Vegeta
where regexp_like 'a+' -> atleast one 'a'
where regexp_like 'a?' -> only one 'a'

29) Differentiate Char vs Varchar vs Varchar2 ?


Char -> The char data type is used to store the character values.
It is a fixed-length data type
i.e. once initialized we cannot change the size of the character at
execution time.
Hence, it is also called a Static datatype.

The main difference is that VARCHAR is ANSI Standard and VARCHAR2 is


Oracle standard.
VARCHAR2 is the same as VARCHAR in the oracle database.
It is a variable-length data type i.e. we can change the size of the
character at the time of the execution.
Hence, it is also called a Dynamic datatype.

30) What is Triggers ?


Trigger is a database object that is associated with a table and
automatically executes a set of SQL statements when a specific event
occurs on that table.
Uses -> Triggers are used to enforce business rules, maintain data integrity.

31) ACID properties ?


Atomicity -> The entire transaction takes place at once.
Consistency -> The database must be consistent before and after the
Transaction
Isolation -> Multiple transaction occurs independently without interference
Durability -> The changes of a Successful transaction occurs even if the
system failure occurs.
32) Why do we use CASE statement in SQL ?
The CASE expression goes through conditions and returns a value, when the
first condition is met (like an if-then-else statement).
So, once a condition is true, it will stop reading and return the result.
If no conditions are true, it returns the value in the ELSE clause.

If there is no ELSE part and no conditions are true, it returns NULL.

33) Differentiate Distinct vs Unique ?


Distinct -> When the DISTINCT keyword is used to fetch only unique records.
Distinct Keyword are used in the select Statement.
Unique -> There is No Duplicate Values, it's Shows Null values,if its
applicable
When we are creating a table , on that time we will use Unique
Constraints.

34) Aggregate Functions ?

It returns one value after calculating multiple values of a column.


Aggregate functions are used to GROUP BY and HAVING clauses of the SELECT
statement.

35) Set Operations ?

Uninon -> The UNION command combines the result set of two or more SELECT
statements. It will returns only distinct values.
Union all -> The UNION ALL command combines the result set of two or more
SELECT statements. It will allows duplicate values.

36) Number Functions, String Functions and Date Function ?


Number Functions -> In SQL Number functions are the predefined functions.

Abs,Sum,Avg,Count,Max,Min,Mod,Ceil/Ceiling,floor,round,Truncate,SQRT,POWER,.etc
String Functions -> In SQL String functions are the predefined functions that
allow the database users for string manipulation.

Insert,Concat,Mid,Substring,Substring_index,Mid,Len,Lower,Upper,Replace,Reverse,Lef
t,LTrim,Right,RTrim,Trim,.etc
Date Functions -> In SQL Date functions are the predefined functions
SELECT CURRENT_TIMESTAMP()/now();
select adddate("1998-05-21", interval 10000 day);
Datediff("1998-05-21", "2023-08-25")'
SELECT DAYNAME("2017-06-15");
SELECT Day/month/Year("2017-06-15");

37) Differentiate Truncate Vs Round ?


Truncate -> The TRUNC() function trims the fractional part. (47.62545,2)
-> 47.62
Round -> The ROUND() function rounds a number to a specified number of
decimal places.(47.62345,2) -> 47.62 , (47.62545,2) -> 47.63
Floor -> The floor() function returns whole value less than or equal
to given number. floor(7.2) -> 7 , floor(7.8) -> 7
Ceil/Ceiling -> The Ceil() function returns whole value greater than or equal
to given number. ceil (7.2) -> 8, ceil(7.8) -> 8

38) Differentiate Rank, Dense_Rank,Percentile


Rank -> RANK skips positions after equal rankings. 50,50,60,70,70,80 ->
1,1,3,4,4,6
Dense_Rank -> Dense_rank doesen't skip postion after equal rankings.
50,50,60,70,70,80 -> 1,1,2,3,3,4
Percentile -> Percentile function returns the relative rank for each value.
PERCENT_RANK is similar to the CUME_DIST function.

39) Cumulative Distribution ?


For a list of scores, PERCENT_RANK returns the percent of values less than
the current score.
CUME_DIST, returns the actual position of the score.

40) Cast Function ?


The CAST() function converts a value (of any type) into the specified
datatype. SELECT CAST("2017-08-29" AS DATE);
The CONVERT() function converts a value into the specified datatype or
character set. SELECT CONVERT("14:06:10", TIME);

41) coalesce Function ?


Provides first non-null values .

42) Lag and Lead ?


LAG() accesses a value stored in a row above
LEAD() accesses a value stored in a row below.

43) order of clause execution ?


From -> Where -> Group by -> Having -> Select -> Order By -> limit / offset

44) Substring , Substr, mid ( All 3 same )?


The SUBSTRING() function extracts a substring from a string (starting at any
position).
e.g, SELECT SUBSTRING(CustomerName, 2, 5) AS ExtractString FROM Customers ;
SELECT SUBSTRING("CustomerName", 2, 5) ; -> ustom
Extract a substring from the text in a column (start at position 2,
extract 5 characters)

45) What is the purpose of an index in SQL, and how does it work?
An index is used to improve the performance of queries by allowing for faster
data retrieval.
It creates a separate data structure that stores the values of one or more
columns .

46) List different Types of Index in SQL?


Clustered Index
Non-Clustered Index
Unique Index
Composite Index
Full-Text Index
Spatial Index

47) Difference between a clustered and a non-clustered index in SQL?


Clustered Index
Determines the physical order of the data.
Only one clustered index per table.
Faster data retrieval for large data sets.
Contains the actual data.

Non-Clustered Index
A separate structure that contains the index key and a pointer to the data.
Multiple non-clustered indexes per table are possible.
Slower data retrieval for large data sets.
Does not contain the actual data

48) What is the difference between a function and a stored procedure in SQL?
In SQL, a function returns a value,
while a stored procedure does not necessarily return a value and may execute
a series of operations or tasks.

49) what is view ?


In SQL, a view is a virtual table based on the result-set of an SQL
statement.

50) Differentiate SQL vs NoSQL ?


SQL
SQL databases are relational
SQL databases use structured query language (SQL) and have a predefined
schema.
SQL databases are vertically scalable
NoSQL
NoSQL databases are non-relational.
NoSQL databases have dynamic schemas for unstructured data.
NoSQL databases are horizontally scalable.

51) What are Tables and fields in SQL?


In SQL, tables and fields are fundamental components used to organize and
store data in a relational database.
Tables :-
Tables are the primary containers for organizing and storing data in a
relational database.
Fields :-
Fields, also known as columns, are the individual data elements within a table.

52) What is data cleaning ?


The process of identifying and correcting or removing errors,
inconsistencies, and inaccuracies in datasets.

53) Why is data cleaning important ?


Data cleaning is essential because poor data quality can lead to incorrect
insights, flawed analysis, and wrong business decisions.

54) Difference between count(*) and Count(column_name) ?


COUNT(*) provides a count of all rows, including those where some columns may
contain NULL values.
COUNT(column_name) provides a count of non-NULL values in a specific column.

55) CASE expression ?


The CASE expression goes through conditions and returns a value when the
first condition is met.
So, once a condition is true, it will stop reading and return the result.
If no conditions are true, it returns the value in the ELSE clause.

If there is no ELSE part and no conditions are true, it returns NULL.

56) Data Crunching ?


Data crunching is often an essential step in preparing large amounts of raw
data for analysis or processing by other applications.
Data crunching commonly involves stripping out unwanted information and formatting,
as well as cleaning and restructuring the data.
Automating the process can save companies time and money while making information
more quickly available for analysis.
Data crunching is needed to convert raw data into a form suitable for
analysis.
A company may need to convert information from external data feeds so it can
apply its existing business intelligence tools to the data.

Benefits :-
Converting raw data into a usable form can be extremely time-consuming ,
so it makes sense to automate data crunching as much as possible using
programming languages or other tools

3 Steps of Data Crunching

Read raw data:


This step pulls in data from the selected source. Raw data may be unformatted
Convert data:
Several distinct operations may be needed to convert data from its original
form to a format that can be used by analysis tools.
Output data in chosen format:
The final data now is ready for output to a file or database that will be
used for analysis.

Technical :-
Find 2nd Highest Salary ?
SELECT MAX(salary) as second_highest_salary FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees)

How can we convert text to date ?


How to fetch Yesterday date ?

Table Description:

Catalogue
Catalogue_Entry_id - Catalogue entry id
Parent_Catelogue_Entry_id - Parent catalogue id of sub items that are listed
Catalogue_Entry_Description - description of the entry

Sizes
Size_Code - size code
Size_Description - description of the size
Colors
Color_Code - color code
Color_Code_Description - description of the color
Products
Product_id - id of the product
Catalougue_Entry_id - entry id in the catalogue
Color_Code - color code of the product
Size_Code - size code of the product
Product_Price - price of the product
Product_Description - description of the product
1) On account of monsoon sale, the shop is giving a flat 5% discount for all the
Women Sportswear.
Get the list of all the products, old price and new price after applying the
discount.
(Use tables: - Catalogue, sizes, colors, products) (Marks - 2)

2) Get the list of all the catalogue descriptions where the average price of all
its products is greater than 1000.
(Use tables: - Catalogue, sizes, colors, products) (Marks - 2)

3) Find the number of products available in each ‘size’.


(Use tables: - Catalogue, sizes, colors, products) (Marks - 2)

4) Fetch the complete details about the products, Catalogue_Entry_Descriptions,


sizes,
and colors available for the products belonging to 'Adidas' brand.
(Use tables: - Catalogue, sizes, colors, products) (Marks -4)

You might also like