SQL Tutorial (Chap8)
SQL Tutorial (Chap8)
o Table-name is the name of the table from which the information is retrieved.
o Col1, col2, coln means one or more columns of table from which data is retrieved.
FROM emp;
Output:-
‘SELECT’ clause in the query specifies columns that we wanted to select.
‘FROM’ clause in the query specifies data sources. If we have multiple data sources then we
should specify joins between them.
Selecting ALL COLUMNS:-
It is not necessary that we should always fetch all records from the table. Using where clause we
can restrict the data by using conditions.
Example:- If we wanted to display whose salary is equal to 2000, below is the query.
SQL> SELECT *FROM emp WHERE sal =2000;
‘ORDER BY’ clause is used to arrange the select statement output in ASCENDING or DESCENDING
order.
‘ORDER BY’ clause Supports with all types of data.
By default oracle will use ascending order. If we want to sort in descending order then specify “ desc “
SQL> SELECT *
FROM emp
ORDER BY sal;
We can as well order the result using a column sequence.
Here 2 represents second column. So, data will be displayed with ename in ascending order.
When SQL statement is run, data fetched from the database is grouped first based on deptno and then sum()
In this example we are trying to group the records using two columns deptno and job
SQL> SELECT deptno,job, SUM(sal)
FROM emp
GROUP BY deptno,job;
Suppose if we try to apply summary function on a column along displaying other columns and not using group by clause
will result in error.
SQL> SELECT empno, ename, deptno, MAX (sal) FROM emp;
Output:
ERROR at line 1:
ORA-00937: NOT single-GROUP groups FUNCTION
Even if we specify only one column in group by then system will raise an error
SQL> SELECT empno, ename, deptno, MAX (sal) FROM emp GROUP BY deptno;
Output:
ERROR at line 1:
ORA-00979: NOT a GROUP BY expression
Rules:-
The columns specified in the group by clause should be specified in select clause.
If not in Group by then that column in select should be applies with summary functions.
Summary columns and column aliases are not allowed in group by clause.
In the below example we are trying to fetch all deptno and job records whose aggregated salary
of its
Having clause gets executed after the records are fetched and grouped.
SQL>SELECT deptno,job, SUM(sal) tsal
FROM emp
GROUP BY deptno,job
HAVING SUM(sal) > 3000;
In this example, after applying the having clause we are trying to order the records by DEPTNO.
SQL> SELECT deptno,job,SUM(sal) tsal
FROM emp
GROUP BY deptno,job
HAVING SUM(sal) > 3000
ORDER BY deptno;
In the below example, ‘where condition’ is applied first and after that HAVING clause is applied.
SQL> SELECT deptno, COUNT (*)
FROM emp
WHERE job='CLERK'
GROUP BY deptno
HAVING COUNT (*)>=2;