0% found this document useful (0 votes)
6 views15 pages

SQL Part I.docx

Uploaded by

royisha1509
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
6 views15 pages

SQL Part I.docx

Uploaded by

royisha1509
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

[Document title]

SQL

SQL is a standard language for storing, manipulating and retrieving data in databases.

What is SQL?

● SQL stands for Structured Query Language


● SQL lets you access and manipulate databases
● SQL became a standard of the American National Standards Institute (ANSI) in 1986,
and of the International Organization for Standardization (ISO) in 1987.

What Can SQL do?

● SQL can execute queries against a database


● SQL can retrieve data from a database
● SQL can insert records in a database
● SQL can update records in a database
● SQL can delete records from a database
● SQL can create new databases
● SQL can create new tables in a database
● SQL can create stored procedures in a database
● SQL can create views in a database
● SQL can set permissions on tables, procedures, and views

SQL is a Standard - BUT....

Although SQL is an ANSI/ISO standard, there are different versions of the SQL language.

However, to be compliant with the ANSI standard, they all support at least the major
commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.

Note: Most of the SQL database programs also have their own proprietary extensions in
addition to the SQL standard!

RDBMS

RDBMS stands for Relational Database Management System.

RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server,
IBM DB2, Oracle, MySQL and Microsoft Access.

The data in RDBMS is stored in database objects called tables. A table is a collection of
related data entries and it consists of columns and rows.

Features of SQL
1) It is an English like language.
2) It is non procedural.
3) It processes sets of records rather than a single record at a time.

1 | Page Dr. Anirban Goswami


[Document title]

4) It can be used by a range of users including DBA, application programmers,


and others.
5) It can perform a variety of tasks as:
a) Querying data.
b) Inserting, updating and deleting rows.
c) Creating, modifying and deleting database objects.
d) Guarantees database consistency.

Writing SQL commands

1. It can be written in one or more lines.


2. Clauses can be placed on separate lines.
3. Tabulation can be used.
4. Command words cannot be split across lines.
5. SQL commands are not case sensitive.
6. An SQL command is entered at the SQL prompt, and subsequent lines are numbered. This
is called SQL buffer.
7. Only one statement can be written in the buffer at a time. Place a semi colon at the end of
the last clause.

Basic Query block:


a) List all department numbers, employee names and manager numbers in the emp table:
Select deptno, ename, mgr from emp;
b) Select all columns: select * from emp;
c) Use of arithmetic expressions:
1) Select ename, sal*12, comm from emp;
2) Select ename, sal +250 *12 from emp; [250*12 will be evaluated first].
3) Select ename, (sal+250)*12 from emp;
d) Column Alias: Alias Headings will be forced to uppercase and cannot blank spaces
unless the alias is enclosed in double quotes:
1) Select ename, sal +250 *12 ANNSAL, comm from emp; [ANNSAL is the column
alias for sal+250 *12.
e) Concatenation Operator:
1) Select empno || Ename Employee from emp; [Employee is the column alias & || is
the concatenation operator].
f) Literals: It is any character, expression and number included on the select list which
is not a column name or alias. Date and character literals must be enclosed within
single quotes, number literals don’t require quotes.
1) Select empno || ‘-‘ || Ename Employee, ‘Works in Department’, deptno from emp;
g) Handling Null values:
1) If row lacks a data value for a particular column, that value is said to be null.
2) A null value is same as zero. It takes up one byte of internal storage.
Select ename, sal*12 + comm annual_sal from emp; [ But it will not show the result
for all the employees, because arithmetic expression cannot handle null values.]

2 | Page Dr. Anirban Goswami


[Document title]

To make an arithmetic expression handle null values we write:


Select ename, sal*12+ NVL(comm,0) annual_sal from emp; [we use NVL function to
convert null values to zero]. [NVL expects two arguments: an expression& a non null
value]
h) Select deptno from emp; [displays the values of deptno of all the rows, duplicate
values]
i) To eliminate duplicate values we use Distinct Clause:
1) Select distinct deptno from emp;
2) Select distinct deptno, job from emp;[Displays a list of all the different
combinations of jobs and department numbers].
j) Order by Clause: This is used to sort the rows. If used it will be the last clause in the
select statement.
Select ename, job, sal*12, deptno from emp order by ename; [Default order is
ascending].
To display the order in descending we use the word desc:
Select ename, job, hiredate from emp order by hiredate desc;

Order by many columns: Select deptno, job, ename from emp order by deptno, sal
desc; [To order by a column, it is not necessary to have Selected it]

k) Where Clause: [This is similar to Restriction Operator in Relational Algebra]. The


where clause expects 3 arguments: A column name, a comparison operator, constant
or list of values]
Comparison operators can be divided into Logical, SQL operators:

Logical Operators: [=, >, >=, <, <=]

1) To display the names, numbers, job and departments of all clerks: Select ename,
empno, job, deptno, from emp where job = ‘CLERK’;
2) To display all department names with department nos > 20: Select dname, deptno
from dept where deptno>20;
3) To display all employees whose commission is greater than salary: Select ename, sal,
comm from emp where comm > sal;

SQL Operators: [Between…And (Between two values), IN(List) (match any of a


list of values), LIKE(match a character pattern), IS NULL (is a null value)]

Between: Display those employees whose salary is between 1000 and 2000.
Select ename, sal from emp where sal between 1000 and 2000;

IN: To display all employees who have one of the three MGR numbers.
Select empno, ename, sal, mgr from emp where mgr in (7902, 7566, 7788);

Like: The character pattern matching operation may be referred to as a wild card
search.

3 | Page Dr. Anirban Goswami


[Document title]

(Wild Characters: %(for any sequence of zero or more characters), _ (any single
character))

To display all employees who name starts with an S:


Select ename from emp where ename like ‘S%’;

To display all employees who have a name of exactly 4 characters in length:


Select ename from emp where ename like ‘_ _ _ _’;

IS NULL: Specifically tests for values that are NULL.


To display all employees who have no manager:
Select ename, mgr from emp where mgr is NULL;

Negating Expressions:
1) Display all employees whose salary is not between a range:
Select ename, sal from emp where sal not between 1000 and 2000;
2) Display all employees whose job doesnot start with M:
Select ename, job from emp where job not like ‘M%’;
3) Display all employees who have a manager:
Select ename, mgr from emp where mgr is not null;

[N.B Comm != NULL is wrong because a Null value may not be either equal or unequal to
any other value, even another null]

Query data with multiple conditions (IMP)

1) To find all clerks who earn between 1000 and 2000:


Select empno, ename, job, sal from emp where sal between 1000 and 2000 and
job=’CLERK’;

2) To find all employees who are either clerks and/or all employees who earn between 1000
and 2000:
Select empno, ename, job, sal from emp where sal between 1000 and 2000 or
job=’CLERK’;

[N.B: in the where clause AND’s are performed first then all OR’s are performed, i.e.
AND has a higher precedence than OR]

3) To display all managers with salaries over 1500, and all salesman:
Select empno, ename, job, sal, deptno from emp where sal > 1500 and
job=’MANAGER’ or job=’SALESMAN’;

4) To display all managers and salesman with salaries over 1500;


Select empno, ename, job, sal, deptno from emp where sal > 1500 and (job=’MANAGER
or job=’SALESMAN’);

4 | Page Dr. Anirban Goswami


[Document title]

Exercise:
1) Select all information from the salgrade table.
2) Select all information from the emp table;
3) Display all different job types;
4) List all the details of the employees in department 10 and 20 in alphabetical order of
name.
5) List names and jobs of all clerks in department 20.
6) Display all employee names which have TH or LL in them.
7) List all the employees who have a manager.
8) Display all employees who were hired during 1983.

**************************

Variables in SQL

SQL * plus provides two variable types:


1) Bind variables: Use to store individual values which may be assigned and read at
run time.
2) Substitution variables: Used to store elements of command text and are edited into
commands before their execution.

Substitution variables

1) Single ampersand (&) – A single value is assigned to the variable.


Select empno, ename, sal from emp where deptno = &dno; [The user is prompted every time
for a dept. no. at run time].
N.B. The single ampersand allows to prompt the user every time the command is executed. A
character or date value need to be enclosed in single quotes at the prompt. To avoid the
quotes at run time, the variable can be enclosed in single quotes.
Select ename, deptno, sal * 12 from emp where job=’&jno’;
2) Double Ampersand(&&) – SQL * plus prompts for the value only once, stores it and
uses the value every time the command is executed.
Select empno, ename, sal from emp where deptno = &&dno; [The user is prompted only once
for a dept. no. at run time].

Substitution data as command text


select * from salgrade where &condition; [enter losal > 2000 as the condition at command
prompt].

5 | Page Dr. Anirban Goswami


[Document title]

Define Command
SQL> Define Rem = ‘sal *12 +nvl(comm,0)’
SQL> Select ename, job, &rem from emp order by &rem;
SQL> undefine rem;

Functions in SQL
Oracle provides single row functions to manipulate the data values. The single row functions
operate on single rows and return only one result per row. In general, the functions take one
or more inputs as arguments and return a single value as output. The arguments can be a
user-supplied constant, variable, column name and an expression.

The features of single row functions are:


● Act on each row returned in the query.
● Perform calculations on data.
● Modify the data items.
● Manipulate the output for groups of rows.
● Format numbers and dates.
● Converts column data types.
● Returns one result per row.
● Used in SELECT, WHERE and ORDER BY clauses.
● Single row functions can be nested.

The single row functions are categorized into


● Character Functions: Character functions accept character inputs and can return
either character or number values as output.
● Number Functions: Number functions accepts numeric inputs and returns only
numeric values as output.
● Date Functions: Date functions operate on date data type and returns a date value or
numeric value.
● Conversions Functions: Converts from one data type to another data type.
● General Functions

Let see each function with an example:

Character Functions Example

1. LOWER: The Lower function converts the character values into lowercase letters.

SELECT lower('ORACLE') FROM DUAL;

2. UPPER: The Upper function converts the character values into uppercase letters.

SELECT upper('oracle') FROM DUAL;

6 | Page Dr. Anirban Goswami


[Document title]

3. INITCAP: The Initcap function converts the first character of each word into uppercase
and the remaining characters into lowercase.

SELECT initcap('LEARN ORACLE') FROM DUAL;

4. CONCAT: The Concat function coverts the first string with the second string.

SELECT concat('Oracle-', ‘Backup’) FROM DUAL;

5. SUBSTR: The Substr function returns specified characters from character value starting at
position m and n characters long. If you omit n, all characters starting from position m to the
end are returned.

Syntax: substr(string [,m,n])


SELECT substr('ORACLE DATA RECOVERY',8,4) FROM DUAL;
SELECT substr('ORACLE DATA PUMP',8) FROM DUAL;

You can specify m value as negative. In this case the count starts from the end of the string.

SELECT substr('ORACLE BACKUP',-6) FROM DUAL;

6. LENGTH: The Length function is used to find the number of characters in a string.

SELECT length('Oracle Data Guard') FROM DUAL;

7. INSTR: The Instr function is used to find the position of a string in another string.
Optionally you can provide position m to start searching for the string and the occurrence n of
the string. By default m and n are 1 which means to start the search at the beginning of the
search and the first occurrence.

Syntax: instr('Main String', 'substring', [m], [n])


SELECT instr('oracle apps','app') FROM DUAL;
SELECT instr('oracle apps is a great application','app',1,2) FROM DUAL;

8. LPAD: The Lpad function pads the character value right-justified to a total width of n
character positions.

Syntax: lpad(column, n, 'string');


SELECT lpad('100',5,'x') FROM DUAL;

9. RPAD: The Rpad function pads the character value left-justified to a total width of n
character positions.

Syntax: rpad(column, n, 'string');


SELECT rpad('100',5,'x') FROM DUAL;

10. TRIM: The Trim function removes the leading or trailing or both the characters from a
string. This can be RTRIM and LTRIM both.

7 | Page Dr. Anirban Goswami


[Document title]

Syntax: trim(leading|trailing|both, trim_char from trim_source)


SELECT trim('O' FROM 'ORACLE') FROM DUAL;
SELECT LTRIM('2254Opal Kole', '2254') "LTRIM" FROM DUAL;
SELECT RTRIM('Opal Kole2254', '2254') "RTRIM" FROM DUAL;

11. REPLACE: The Replace function is used to replace a character with another character in
a string.

Syntax: replace(column, old_char,new_char)


SELECT replace('ORACLE DATA BACKUP', 'DATA','DATABASE') FROM DUAL;

Number Functions Example

1. ROUND: The Round function rounds the value to the n decimal values. If n is not
specified, there won't be any decimal places. If n is negative, numbers to the left of the
decimal point are rounded.

Syntax: round(number,n)
SELECT round(123.67,1) FROM DUAL;
SELECT round(123.67) FROM DUAL;
SELECT round(123.67,-1) FROM DUAL;

2. TRUNC: The Trunc function truncates the value to the n decimal places. If n is omitted,
then n defaults to zero.

Syntax: trunc(number,n)
SELECT trunc(123.67,1) FROM DUAL;
SELECT trunc(123.67) FROM DUAL;

3. MOD: The Mod function returns the remainder of m divided by n.

Syntax: mod(m,n)
SELECT mod(10,5) FROM DUAL;

Date Functions Example

1. SYSDATE: The Sysdate function returns the current oracle database server date and time.

SELECT sysdate FROM DUAL;

2. Arithmetic with Dates: You can add or subtract the number of days or hours to the dates.
You can also subtract the dates

SELECT sysdate+2 "add_days" FROM DUAL;


SELECT sysdate-3 "sub_days" FROM DUAL;
SELECT sysdate+3/24 "add_hours" FROM DUAL;
SELECT sysdate-2/24 "sub_hours" FROM DUAL;

8 | Page Dr. Anirban Goswami


[Document title]

SELECT sysdate-hire_date "sub_dates" FROM EMPLOYEES; -- returns number of days


between the two dates.

3. MONTHS_BETWEEN: The Months_Between function returns the number of months


between the two given dates.

Syntax: months_between(date1,date2)
SELECT months_between(sysdate,hire_date) FROM EMPLOYEES:
SELECT months_between('01-JUL-2000', '23-JAN-2000') FROM DUAL;

4. ADD_MONTHS: The Add_Months is used to add or subtract the number of calendar


months to the given date.

Syntax: add_months(date,n)
SELECT add_months(sysdate,3) FROM DUAL;
SELECT add_months(sysdate,-3) FROM DUAL;
SELECT add_months('01-JUL-2000', 3) FROM DUAL;

5. NEXT_DAY: The Next_Day function finds the date of the next specified day of the week.
The syntax is

NEXT_DAY(date,'char')

The char can be a character string or a number representing the day.

SELECT next_day(sysdate,'FRIDAY') FROM DUAL;


SELECT next_day(sysdate,5) FROM DUAL;
SELECT next_day('01-JUL-2000', 'FRIDAY') FROM DUAL;

6. LAST_DAY: The Last_Day function returns the last day of the month.

SELECT last_day(sysdate) FROM DUAL;


SELECT last_day('01-JUL-2000') FROM DUAL;

7. ROUND: The Round function returns the date rounded to the specified format. The Syntax
is
Round(date [,'fmt'])

SELECT round(sysdate,'MONTH') FROM DUAL;


SELECT round(sysdate,'YEAR') FROM DUAL;
SELECT round('30-OCT-85','YEAR') FROM DUAL;

8. TRUNC: The Trunc function returns the date truncated to the specified format. The Syntax
is
Trunc(date [,'fmt'])

SELECT trunc(sysdate,'MONTH') FROM DUAL;


SELECT trunc(sysdate,'YEAR') FROM DUAL;
SELECT trunc('01-MAR-85','YEAR') FROM DUAL;

9 | Page Dr. Anirban Goswami


[Document title]

Conversions functions are used to convert one data type to another type

Top of Form
Bottom of Form
Conversions functions are used to convert one data type to another type. In some cases oracle
server automatically converts the data to the required type. This is called implicit conversion.
Explicit conversions are done by using the conversion functions. You have to take care of
explicit conversions.

Oracle Explicit Data Type Conversion

Oracle provides three functions to covert from one data type to another.

1. To_CHAR ( number | date, [fmt], [nlsparams] )

The TO_CHAR function converts the number or date to VARCHAR2 data type in the
specified format (fmt). The nlsparams parameter is used for number conversions. The
nlsparams specifies the following number format elements:

● Decimal character
● Group separator
● Local currency symbol
● International currency symbol

If the parameters are omitted, then it uses the default formats specified in the session.

Converting Dates to Character Type Examples

The Date format models are:

● YYYY: Four digit representation of year


● YEAR: Year spelled out
● MM: Two digit value of month
● MONTH: Full name of month
● MON: Three letter representation of month
● DY: Three letter representation of the day of the week
● DAY: Full name of the day
● DD: Numeric day of the month
● fm: used to remove any padded blanks or leading zeros.

SELECT TO_CHAR(hire_date, 'DD-MON-YYYY') FROM EMPLOYEES;


SELECT TO_CHAR(hire_date, 'fmYYYY') FROM EMPLOYEES;
SELECT TO_CHAR(hire_date, 'MON') FROM EMPLOYEES;

10 | Page Dr. Anirban Goswami


[Document title]

SELECT TO_CHAR(hire_date, 'YYYY/MM/DD') FROM EMPLOYEES;

Converting Numbers to Character type Examples

The Number format models are:

● 9: Specifies numeric position. The number of 9's determine the display width.
● 0: Specifies leading zeros.
● $: Floating dollar sign
● .: Decimal position
● ,: Comma position in the number

SELECT TO_CHAR(price, '$99,999') FROM SALES;


SELECT TO_CHAR(price, '99.99') FROM SALES;
SELECT TO_CHAR(price, '99,00') FROM SALES;

2. TO_NUMBER( char, ['fmt'] )

The TO_NUMBER function converts the characters to a number format.

SELECT TO_NUMBER('1028','9999') FROM DUAL;


SELECT TO_NUMBER('12,345','99,999') FROM DUAL;

3. TO_DATE( char, ['fmt'] )

The TO_DATE function converts the characters to a date data type.

SELECT TO_DATE('01-JAN-1985','DD-MON-YYYY') FROM DUAL;


SELECT TO_DATE('01-03-85','DD-MM-RR') FROM DUAL;

Group Functions
SQL has numerous predefined aggregate functions that can be used to write queries to
produce exactly this kind of information. The GROUP BY clause specifies how to group
rows from a data table when aggregating information, while the HAVING clause filters out
rows that do not belong in specified groups.
Aggregate functions perform a variety of actions such as counting all the rows in a table,
averaging a column's data, and summing numeric data. Aggregates can also search a table to
find the highest "MAX" or lowest "MIN" values in a column. As with other types of queries,
you can restrict, or filter out the rows these functions act on with the WHERE clause. For
example, if a manager needs to know how many employees work in an organization, the
aggregate function named COUNT(*) can be used to produce this information. The
COUNT(*) function shown in the below SELECT statement counts all rows in a table.
SELECT COUNT(*) total
FROM emp;

COUNT(*)

11 | Page Dr. Anirban Goswami


[Document title]

----------
24
The result table for the COUNT(*) function is a single column from a single row known as a
scalar result or value. Notice that the result table has a column heading that corresponds to
the name of the aggregate function specified in the SELECT clause.
Some of the commonly used aggregate functions are as below -
SUM( [ALL | DISTINCT] expression )

AVG( [ALL | DISTINCT] expression )

COUNT( [ALL | DISTINCT] expression )

COUNT(*)

MAX(expression)

MIN(expression)
The ALL and DISTINCT keywords are optional, and perform as they do with the SELECT
clauses that you have learned to write. The ALL keyword is the default where the option is
allowed. The expression listed in the syntax can be a constant, a function, or any combination
of column names, constants, and functions connected by arithmetic operators. However,
aggregate functions are most often used with a column name. Except COUNT function, all
the aggregate functions do not consider NULL values.
There are two rules that you must understand and follow when using aggregates:
● Aggregate functions can be used in both the SELECT and HAVING clauses (the
HAVING clause is covered later in this chapter).
● Aggregate functions cannot be used in a WHERE clause. Its violation will produce
the Oracle ORA-00934 group function is not allowed here error message.
Examples:
The below SELECT query counts the number of employees in the organization.
SELECT COUNT(*) Count FROM emp;

COUNT
-----
24
The below SELECT query returns the average of the salaries of employees in the
organization.
SELECT AVG(Salary) average_sal FROM emp;

AVERAGE_SAL
-----------
15694
The below SELECT query returns the sum of the salaries of employees in the organization.
SELECT SUM(Salary) total_sal FROM emp;

12 | Page Dr. Anirban Goswami


[Document title]

TOTAL_SAL
---------
87472
The below SELECT query returns the oldest and latest hired dates of employees in the
organization.
SELECT MIN (hire_date) oldest, MAX (hire_date) latest FROM emp;

OLDEST LATEST
--------- -----------
16-JAN-83 01-JUL-2012
GROUP BY
Aggregate functions are normally used in conjunction with a GROUP BY clause. The
GROUP BY clause enables you to use aggregate functions to answer more complex
managerial questions such as:
What is the average salary of employees in each department?
How many employees work in each department?
How many employees are working on a particular project?
Group by function establishes data groups based on columns and aggregates the information
within a group only. The grouping criterion is defined by the columns specified in GROUP
BY clause. Following this hierarchy, data is first organized in the groups and then WHERE
clause restricts the rows in each group.
Guidelines of using GROUP BY clause (IMP)
(1) All the dependent columns or columns used in GROUP BY function must form the basis
of grouping, hence must be included in GROUP BY clause also.
SELECT deptno, SUM(SAL) FROM emp;

deptno,
*
ERROR at line 2:
ORA-00937: not a single-group function
(2) GROUP BY clause does not support the use of column alias, but the actual names.
(3) GROUP BY clause can only be used with aggregate functions like SUM, AVG, COUNT,
MAX, and MIN. If it is used with single row functions, Oracle throws an exception as
"ORA-00979: not a GROUP BY expression".
(4) Aggregate functions cannot be used in a GROUP BY clause. Oracle will return the
"ORA-00934: group function not allowed" here error message.
Below query lists the count of employees working in each department.
SELECT deptno, COUNT (*) FROM emp GROUP BY deptno;
Similarly, below query to find sum of salaries for respective job ids in each department. Note
the group is established based on Department and Job id. So they appear in GROUP BY
clause.

13 | Page Dr. Anirban Goswami


[Document title]

SELECT DEPARTMENT_ID, JOB_ID, SUM (SAL)


FROM employees
GROUP BY DEPARTMENT_ID, JOB_ID;
The below query also produces the same result. Please note that grouping is based on the
department id and job id columns but not used for display purpose.
SELECT SUM (SALARY)
FROM employees
GROUP BY DEPARTMENT_ID, JOB_ID;
Use of DISTINCT, ALL keywords with Aggregate functions
By specifying DISTINCT keyword with the input parameter, group by function considers
only the unique value of the column for aggregation. By specifying ALL keyword with the
input parameter, group by function considers all the values of the column for aggregation,
including nulls and duplicates. ALL is the default specification.
The HAVING clause
The HAVING clause is used for aggregate functions in the same way that a WHERE clause is
used for column names and expressions. Essentially, the HAVING and WHERE clauses do
the same thing, that is filter rows from inclusion in a result table based on a condition. While
it may appear that a HAVING clause filters out groups, it does not. Rather, a HAVING clause
filters rows.
When all rows for a group are eliminated so is the group. To summarize, the important
differences between the WHERE and HAVING clauses are:
A WHERE clause is used to filter rows BEFORE the GROUPING action (i.e., before the
calculation of the aggregate functions).
A HAVING clause filters rows AFTER the GROUPING action (i.e., after the calculation of
the aggregate functions).
SELECT JOB_ID, SUM (SALARY)
FROM employees
GROUP BY JOB_ID
HAVING SUM (SALARY) > 5000;
The HAVING clause is a conditional option that is directly related to the GROUP BY clause
option because a HAVING clause eliminates rows from a result table based on the result of a
GROUP BY clause.
SELECT department_id, AVG(Salary)
FROM employees
HAVING AVG(Salary) > 33000;
ERROR at line 1: ORA-00937: not a single-group function

Extra Queries:
1) Select avg(sal) from emp;
2) Select min(sal) from emp where job=’CLERK’;
3) Select count(*) from emp where deptno=20;
4) Select job, avg(sal) from emp group by job; [Calculate the average salary for each
different job].

14 | Page Dr. Anirban Goswami


[Document title]

5) Select job, avg(sal) from emp where job != ‘MANAGER’ group by job; [Rows may be
pre-excluded with a where clause before dividing them into groups- Show the average
salary for each job excluding managers]
6) Select deptno, job, avg(sal) from emp group by deptno, job; [ use of group by clause to
provide results for groups within groups – display the average monthly salary bill for each
job type within a department].
7) Select job, max(sal) from emp;
8) Select job, max(sal) from emp group by job;
● If we include group functions in a select command, we may not select individual
results as well unless the individual column appears in the group by clause.
● In other words, group functions cannot be retrieved with individual items that
are not included in the group by clause.
Ex: Select deptno, min(sal) from emp; is illegal and produces the error in deptno.
● The command is invalid because deptno has a value for each row in the table,
while min(sal) has a single value for the whole table.
● To correct the error we must group the individual items.
Ex: select deptno, min(sal) from emp group by deptno;
● If more than one column with individual values is entered on the select line, we
must group by all the individual columns.
● Any column or expression in the select list which is not an aggregate function
must be in the group by clause.

9) The order of clauses in the select statement


Syntax: select column from table where row condition group by column having group of
rows condition order by column;

Exercise:
1) Find the minimum salary of all employees.
2) Find the minimum, maximum and average salary of all the employees;
3) Find the minimum and maximum salary for each job type.
4) Find out how many mangers there are without listing them.
5) Find the average salary and average total remuneration for each job type.
6) Find out the difference between the highest and lowest salaries.
7) Find out all departments which have more than 3 employees.
8) Check whether all employee numbers are indeed unique.
9) List the lowest paid employees working for each manager.

***************************************

15 | Page Dr. Anirban Goswami

You might also like