0% found this document useful (0 votes)
83 views13 pages

SQL Questions

The document discusses SQL functions and commands used to calculate running or cumulative totals. It provides examples of using the SUM() function with the OVER clause to calculate a running total by country in a registration table. Table functions are used to return results as tables, while stored procedures allow reusable logic and can update data. Windows functions perform calculations across related rows, and RANK() vs DENSE_RANK() assign ranks with and without gaps respectively.

Uploaded by

Karthik M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
83 views13 pages

SQL Questions

The document discusses SQL functions and commands used to calculate running or cumulative totals. It provides examples of using the SUM() function with the OVER clause to calculate a running total by country in a registration table. Table functions are used to return results as tables, while stored procedures allow reusable logic and can update data. Windows functions perform calculations across related rows, and RANK() vs DENSE_RANK() assign ranks with and without gaps respectively.

Uploaded by

Karthik M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 13

Q1. What is running total in SQL? OR .

How to Calculate the Cumulative Sum or Running Total in


SQL...?
ANS:
A running total refers to the sum of values in all cells of a column that precedes the next cell in that
particular column. ... In the SQL Server, the OVER clause can be used to calculate running totals.

Using Sum () Function with Over () Clause : This is the simplest method to calculate the cumulative
sum/running total in SQL Server. ...

Syntax:
SELECT country, registration_date,registred_users,
  SUM(registred_users)
  OVER (PARTITION BY country ORDER BY registration_date)
  AS total_users
FROM registration;

country registration_date registered_users total_users

England 2020-03-05 25 25

England 2020-03-06 12 37

England 2020-03-07 10 47

Poland 2020-03-05 32 32

Poland 2020-03-06 15 47

Poland 2020-03-07 6 53

Q2. Difference between table functions and stored procedure?

ANS: Table Functions are used to implement the solutions where we need to return the results
represented in a table. Mostly we will implement table functions to address the data modelling
requirements which cannot be achieved using graphical calculation views.

Key features of Table Functions:

▪ Replaces the Script based Calculation views

▪ Can be used as data sources in graphical calculation views

▪ Read-only – we cannot implement any logic that updates the data

▪ Accept multiple input parameters and return exactly one results table
Key Points:

▪ We can use the table functions as data source in calculation views

▪ We can call the table functions from stored procedures and other table functions

Stored procedures are the reusable processing blocks of logic, which can be used to implement solutions
as per specific business requirements.

Commonly we implement stored procedures to build the solutions for the

scenarios such as: 1) Persisting results in HANA database – example Snapshots, Reusable results of
HANA views – to avoid frequent execution of complex views.

2) Reusable solutions – Data conversions, Calculations etc.

▪ Procedures can be defined as Read only OR Read/ Write Procedures

▪ These are the typical ways of calling procedures:

▪ Calling stored procedures from another procedure or function

▪ Scheduling the procedure call from XS Job engine which is in-build in HANA

▪ Scheduling the procedure call from external ETL tools such as Business Objects Data Services
Procedures can be created as:

1. Catalog Procedures: These are not transportable, since they are created using the CREATE
PROCEDURE statement and they are not created under a package.

2. Repository Procedures: These are the procedures created using the HANA development perspective
(Extension .hdbprocedure). This is the recommended approach for creating stored procedures since they
can be transported, and version management is available
Q3.Windows functions in SQL?

ANS: Windows functions perform a calculation across a set of table rows that are somehow related to
the current row.

Q4. What is a stored procedure?


ANS: Stored Procedure is a function consists of many SQL statement to access the database system. Several
SQL statements are consolidated into a stored procedure and execute them whenever and wherever required.

Q5. What is the difference between the RANK() and DENSE_RANK() functions?

ANS: The RANK() function in the result set defines the rank of each row within your ordered partition. If both
rows have the same rank, the next number in the ranking will be the previous rank plus a number of duplicates.
If we have three records at rank 4, for example, the next level indicated is 7.

The DENSE_RANK() function assigns a distinct rank to each row within a partition based on the provided
column value, with no gaps. It always indicates a ranking in order of precedence. This function will assign the
same rank to the two rows if they have the same rank, with the next rank being the next consecutive number. If
we have three records at rank 4, for example, the next level indicated is 5.
Q6. What is SQL example?

ANS: SQL is a database query language that allows you to edit, remove, and request data from databases. The
following statements are a few examples of SQL statements:

 SELECT 
 INSERT 
 UPDATE
 DELETE
 CREATE DATABASE
 ALTER DATABASE

Q7. How to remove duplicate rows in SQL?

ANS:

 If the SQL table has duplicate rows, the duplicate rows must be removed.
 Let’s assume the following table as our dataset:
  

ID Name Age
1 A 21
2 B 23
2 B 23
4 D 22
5 E 25
6 G 26
5 E 25
 The following SQL query removes the duplicate ids from the  table:

DELETE FROM table WHERE ID IN (


SELECT 
ID, COUNT(ID) 
FROM   table
GROUP BY  ID
HAVING 
COUNT (ID) > 1); 

Q8. How to create a stored procedure using SQL Server?

ANS:

 A stored procedure is a piece of prepared SQL code that you can save and reuse again and over.
So, if you have a SQL query that you create frequently, save it as a stored procedure and then call it to
run it.
You may also supply parameters to a stored procedure so that it can act based on the value(s) of the
parameter(s) given.
 Stored Procedure Syntax

 CREATE PROCEDURE procedure_name

 AS

 sql_statement

 GO;

 Execute a Stored Procedure

 EXEC procedure_name;

OR

 A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over
again. So, if we have a SQL query that we create frequently, save it as a stored procedure and then call
it to run it.
We can use select, insert, update , delete etc in stored procedure.

 We can create a table and modify the table.

 We can load the data in table

 We can create a temporary table.

 We can use input and output parameters

 We can not use stored procedure in Graphical CV directly for that we need to convert as scripted
calculated column and use it.

 Scenarios: Use it to load in a Temporary table, to create hierarchies and inventory snapshot creation.

Stored Procedure Syntax

 CREATE PROCEDURE procedure_name

 AS

 sql_statement

 GO;

 Execute a Stored Procedure

 EXEC procedure_name;

Q9. What are joins in SQL?


ANS: A JOIN clause is used to combine rows from two or more tables, based on a related column between
them. It is used to merge two tables or retrieve data from there. There are 4 types of joins, as you can refer to
below:

 Inner join: Inner Join in SQL is the most common type of join. It is used to return all the rows from
multiple tables where the join condition is satisfied. 

 Left Join:  Left Join in SQL is used to return all the rows from the left table but only the matching rows
from the right table where the join condition is fulfilled.
 Right Join: Right Join in SQL is used to return all the rows from the right table but only the matching
rows from the left table where the join condition is fulfilled.
 Full Join: Full join returns all the records when there is a match in any of the tables. Therefore, it
returns all the rows from the left-hand side table and all the rows from the right-hand side table.

Q10. What is the difference between CHAR and VARCHAR2 datatype in SQL?

ANS: Both Char and Varchar2 are used for characters datatype but varchar2 is used for character strings of
variable length whereas Char is used for strings of fixed length. For example, char(10) can only store 10
characters and will not be able to store a string of any other length whereas varchar2(10) can store any length i.e
6,8,2 in this variable.

Q11. What is the difference between DELETE and TRUNCATE statements?

ANS:

DELETE vs TRUNCATE

DELETE TRUNCATE

Delete command is used to delete a row in a table. Truncate is used to delete all the rows from a table.

You can rollback data after using delete statement. You cannot rollback data.
It is slower than truncate statement. It is faster.

Q12. What is the difference between DROP and TRUNCATE commands?

ANS:

DROP command removes a table and it cannot be rolled back from the database whereas TRUNCATE
command removes all the rows from the table.

In SQL, the DROP command is used to remove the whole database or table indexes, data, and more. The
important part of this command is that it has the ability to permanently remove the table and its contents.

In SQL, the TRUNCATE command is used to remove all the rows from the table. However, the structure of
the table and columns remains the same. It is faster than the DROP command.

# We use Cascade command to delete the view of the Table.

Q13. How many Aggregate functions are available in SQL?

ANS: SQL aggregate functions provide information about a database’s data. AVG, for example, returns the
average of a database column’s values.

SQL provides seven (7) aggregate functions, which are given below:

AVG(): returns the average value from specified columns.


COUNT(): returns the number of table rows, including rows with null values.
MAX(): returns the largest value among the group.
MIN(): returns the smallest value among the group.
SUM(): returns the total summed values(non-null) of the specified column.
FIRST(): returns the first value of an expression.
LAST(): returns the last value of an expression.

Q14. Write a SQL query to find the names of employees that begin with ‘A’?

ANS: To display name of the employees that begin with ‘A’, type in the below command:

1 SELECT * FROM Table_name WHERE Column name like 'A%'

Q15. Write a SQL query to get the third-highest salary of an employee from employee_table?

ANS:

1 SELECT TOP 1 salary


2 FROM(
3 SELECT TOP 3 salary
4 FROM employee_table
5 ORDER BY salary DESC) AS emp
6 ORDER BY salary ASC;

Q16. DIFFERENCE B/W UNION ALL(UNION IN HANA) AND UNION?


 ANS: UNION ALL(union node in HANA) is the default union and the fastest to create. It combines two or
more SELECT statements or queries and includes duplicate rows. The UNION combines two or
more SELECT statements or queries. It takes longer to create it because it removes duplicate rows.

Q17. Why are SQL functions used?

ANS: SQL functions are used for the following purposes:

 To perform some calculations on the data


 To modify individual data items
 To manipulate the output
 To format dates and numbers
 To convert the data types

Q18. What is the need for MERGE statement?

ANS: This statement allows conditional update or insertion of data into a table. It performs an UPDATE if a
row exists, or an INSERT if the row does not exist.

Q19. What is the difference between ‘HAVING’ CLAUSE and a ‘WHERE’ CLAUSE?

ANS: HAVING clause can be used only with SELECT statement. It is usually used in a GROUP BY clause
and whenever GROUP BY is not used, HAVING behaves like a WHERE clause.
Having Clause is only used with the GROUP BY function in a query whereas WHERE Clause is applied to each
row before they are a part of the GROUP BY function in a query.

Q20. What is an ALIAS command?

ANS: ALIAS command in SQL is the name that can be given to any table or a column. This alias name can be
referred in WHERE clause to identify a particular table or a column.

For example-

Select emp.empID, dept.Result


from employee emp, department as dept where emp.empID=dept
Q21. How do you aggregate a string in SQL?
ANS: The STRING_AGG() is an aggregate function that concatenates rows of strings into a single string,
separated by a specified separator. It does not add the separator at the end of the result string. In this syntax:
input_string is any type that can be converted VARCHAR and NVARCHAR when concatenation.

Q22. How do you convert columns to rows in SQL?

ANS: To convert columns to rows in SQL we use String_agg command.

Select deptno, Empname from Emp;

Select deptno, String_agg(Empname, ‘/ /’ from Emp); Now all the columns will be changed to rows..

Q23. What is difference between scalar function and user-defined function in SQL?
ANS: User-defined Scalar Functions (SFs) return a single scalar data value of the type defined in the
RETURNS clause. User-defined table-valued functions (TVFs) return a table data type that can read from in
the same way as you would use a table:

Q24.What is the difference between scalar functions and aggregate functions?


ANS: Aggregate functions operate against a collection of values and return a single summarizing
value. Scalar functions return a single value based on scalar input arguments. Some scalar functions, such
as CURRENT_TIME, do not require any arguments.

Q25. What are scalar functions and aggregate functions?

ANS: Aggregate Functions

Aggregate Functions Scalar Functions

1. SUM() 1. LCASE()
2. COUNT()  2. UCASE() 
3. AVG()  3. LEN()
4. MIN() 4. MID() 
5. MAX() 5. ROUND() 
6. FIRST() 6. NOW()
7. LAST()  7. FORMAT()

Q26. What are the 5 different windowing functions?


ANS: There are five main families of window functions. Two families are unrelated to aggregation functions:
Ranking and ordering functions: 
row_number() , min_rank() , dense_rank() , cume_dist() , percent_rank() , and ntile() .
These functions all take a vector to order by, and return various types of ranks.

Q27. What are the currency conversion functionalities supported by SAP HANA?
ANS: To use the CONVERT_CURRENCY function, the currency conversion tables TCURV, TCURX,
TCURN, TCURR, and TCURF must be available in the SAP HANA database.

Q28.Table user defined functions?

ANS:
We can only use Select in table functions and also only input parameters.
We can use it as a table directly.

Scenarios: We can use for all window functions like Rank , Denserank, string agg .

Q29. Scalar SQL Functions?


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

We can not write sql statements in scalar functions. A new function will be created.

Following are a few of the most commonly used Aggregate Functions:

Function Description

Used to convert string column values to lowercase


LCASE()
This function is used to convert a string column values
UCASE() to Uppercase.

Returns the length of the text values in the column.


LEN()
Extracts substrings in SQL from column values having
MID() String data type.

Rounds off a numeric value to the nearest integer.


ROUND()
This function is used to return the current system date
NOW() and time.

Used to format how a field must be displayed.


FORMAT()

Q30. How do you convert columns into tables?


ANS: To convert columns to rows we use String Aggregation.

SELECT FirstName FROM [PersonTestTable] ORDER BY FirstName ASC

GO

SELECT STRING_AGG(FirstName,'-')  WITHIN GROUP ( ORDER BY FirstName ASC)  AS Result FROM

[Persontable]

Q31. How to find second highest salary?

ANS: Below is simple query to find the employee whose salary is highest. 
select *from employee where salary=(select Max(salary) from employee);

We can nest the above query to find the second largest salary. 
select *from employee
group by salary
order by salary desc limit 1,1;
SELECT Empname, MAX(salary) AS salary
FROM employee
WHERE salary < (SELECT MAX(salary)
FROM employee);

Q32. How to get first and last day of the month?

ANS:

Get the First and Last Day of a Month

See these two queries.

SELECT DATEADD(DD,-(DAY(GETDATE() -1)), GETDATE()) AS FirstDate


SELECT DATEADD(DD,-(DAY(GETDATE())), DATEADD(MM, 1, GETDATE())) AS LastDate

Executing the above queries will return the first and last day with date, month, year, time etc. For example, if its
any day in the month of feb 2021, the output will be …

FirstDate
2021-02-01 10:44:27.557
LastDate
2021-02-28 10:44:27.557
However, we want the First and Last day (in words). So, simply embed the two above queries inside
the DATENAME() function. Here it is.

SELECT DATENAME(WEEKDAY, DATEADD(DD,-(DAY(GETDATE() -1)), GETDATE())) AS FirstDay


SELECT DATENAME(WEEKDAY, DATEADD(DD,-(DAY(GETDATE())), DATEADD(MM, 1,
GETDATE()))) AS LastDay

Calculate SQL Running Average


You can modify the script in the last section to calculate a running average age of all the students in the
Students table. To do this, execute the following script:

USE School

SELECT Id, StudentName, StudentGender, StudentAge,

SUM (StudentAge) OVER (ORDER BY Id) AS RunningAgeTotal,

AVG (StudentAge) OVER (ORDER BY Id) AS RunningAgeAverage

FROM Students

As you can see, we use the AVG aggregate function to calculate the average age of all the students in the
StudentAge column. The output of the above script looks like this:

Take a look at the third row of the RunningAgeAverage column. It contains the average of values of the
1st to 3rd rows in the StudentAge column, i.e (14 + 12 + 13)/3 = 13.

You might also like