Sunteți pe pagina 1din 3

DB2 interview questions

1. How to find number of rows in DB2 tables?


User must use SELECT COUNT (*) on DB2 query.

2. How can duplicate values be eliminated from DB2 SELECT?


To eliminate duplicate values in DB2 SELECT, the user must use SELECT DISTINCT in DB2 query.

3. What is meant by aggregate function?


‘Aggregate’ functions are built in mathematical tools that are used in DB2 SELECT clause.
E.g.,
AVG – calculates the average of a set of values.
COUNT – counts rows in a specified table or view.
MIN – gets the minimum value in a set of values.
MAX – gets the maximum value in a set of values.
SUM – calculates the sum of values.

A. SELECT COUNT(*) FROM products;

B. SELECT AVG(unitsinstock) FROM products;

C. To calculate units in stock by product category, you use the AVG function with
the GROUP BY clause as follows:
SELECT categoryid, AVG(unitsinstock)
FROM products
GROUP BY categoryid;

D. To calculate the sum of units in stock by product category, you use the SUM
function with the GROUP BY clause as the following query:
SELECT categoryid, SUM(unitsinstock)
FROM products
GROUP BY categoryid;
E. To get the maximum units in stock of products in the products table, you use the
MAX function as shown in the following query:
SELECT MAX(unitsinstock) FROM products;

F. To calculate the average of distinct unit prices of products, you can use the
DISTINCT modifier in the AVG() function as the following query:
SELECT AVG(DISTINCT unitprice) FROM products;

G. Suppose we have 2 tables CATEGORY and PRODUCTS as shown below:


SELECT categoryname, AVG(unitprice) FROM products
INNER JOIN categories ON categories.categoryid = products.categoryid
GROUP BY categoryname;

The INNER JOIN clause is used to get the category name from the categories table.

H. SQL AVG function with HAVING clause


To get the category that has an average unit price greater than $25, you use the AVG
function with GROUP BY and HAVING clauses as the following query:

SELECT categoryname, AVG(unitprice) FROM products


INNER JOIN categories ON categories.categoryid = products.categoryid
GROUP BY categoryname
HAVING AVG(unitprice) > 25;

I. Count function

COUNT() Function Count Duplicates Count NULL values


COUNT(*) Yes Yes
COUNT(DISTINCT column) No No
COUNT(ALL column) Yes No

S-ar putea să vă placă și