1. What Is a SELECT Query Statement?
The SELECT statement is also called the query statement. It is the most frequently used SQL statement in any database application. A SELECT statement allows you to retrieve data from one or more tables, or views, with different selection criteria, grouping criteria and sorting orders.
2. How To Select All Columns of All Rows from a Table?
The simplest query statement is the one that selects all columns of all rows from a table: "SELECT * FROM table_name;". The (*) in the SELECT clause tells the query to return all columns. The tutorial exercise below gives you a good example:
SQL> SELECT * FROM departments;
DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID
------------- -------------------- ---------- -----------
10 Administration 200 1700
20 Marketing 201 1800
30 Purchasing 114 1700
40 Human Resources 203 2400
50 Shipping 121 1500
60 IT 103 1400
70 Public Relations 204 2700
80 Sales 145 2500
90 Executive 100 1700
......
3. How To Select Some Columns from a Table?
If you want explicitly tell the query to some columns, you can specify the column names in SELECT clause. The following select statement returns only two columns from the table "departments":
SQL> SELECT location_id, department_name FROM DEPARTMENTS;
LOCATION_ID DEPARTMENT_NAME
----------- ------------------------------
1700 Administration
1800 Marketing
1700 Purchasing
2400 Human Resources
1500 Shipping
1400 IT
2700 Public Relations
2500 Sales
1700 Executive
......
4. How To Select Some Rows from a Table?
If you don't want select all rows from a table, you can specify a WHERE clause to tell the query to return only the rows that meets the condition defined in the WHERE clause. The following select statement only returns rows that has department name starts with the letter "C":
SQL> SELECT * FROM departments
2 WHERE department_name LIKE 'C%';
DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID
------------- -------------------- ---------- -----------
130 Corporate Tax 1700
140 Control And Credit 1700
180 Construction 1700
190 Contracting 1700
......
5. How To Sort the Query Output?
If you want the returning rows to be sorted, you can specify a sorting expression in the ORDER BY clause. The following select statement returns rows sorted by the values in the "manager_id" column:
SQL> SELECT * FROM departments ORDER BY manager_id;
DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID
------------- -------------------- ------------- --------------
90 Executive 100 1700
60 IT 103 1400
100 Finance 108 1700
30 Purchasing 114 1700
50 Shipping 121 1500
80 Sales 145 2500
10 Administration 200 1700
20 Marketing 201 1800
......
6. Can the Query Output Be Sorted by Multiple Columns?
You can specifying multiple columns in the ORDER BY clause as shown in the following example statement, which returns employees' salaries sorted by department and salary value:
SQL> SELECT department_id, first_name, last_name, salary
FROM employees ORDER BY department_id, salary;
DEPARTMENT_ID FIRST_NAME LAST_NAME SALARY
------------- --------------- --------------- ----------
10 Jennifer Whalen 4400
20 Pat Fay 6000
20 Michael Hartstein 13000
30 Karen Colmenares 2500
30 Guy Himuro 2600
30 Sigal Tobias 2800
30 Shelli Baida 2900
30 Alexander Khoo 3100
30 Den Raphaely 11000
40 Susan Mavris 6500
50 TJ Olson 2100
......
7. How To Sort Query Output in Descending Order?
If you want to sort a column in descending order, you can specify the DESC keyword in the ORDER BY clause. The following SELECT statement first sorts the department in descending order, then sorts the salary in ascending order:
SQL> SELECT department_id, first_name, last_name, salary
FROM employees ORDER BY department_id DESC, salary;
DEPARTMENT FIRST_NAME LAST_NAME SALARY
_ID
------------- --------------- --------------- ----------
Kimberely Grant 7000
110 William Gietz 8300
110 Shelley Higgins 12000
100 Luis Popp 6900
100 Ismael Sciarra 7700
100 Jose Manuel Urman 7800
100 John Chen 8200
100 Daniel Faviet 9000
......
8. How To Use SELECT Statement to Count the Number of Rows?
If you want to count the number of rows, you can use the COUNT(*) function in the SELECT clause. The following select statement returns the number of rows in the "department" table:
SQL> SELECT COUNT(*) FROM departments;
COUNT(*)
----------
27
So there are 27 rows in the "departments" table.
9. Can SELECT Statements Be Used on Views?
Select (query) statements can used on views in the same way as tables. The following tutorial exercise helps you creating a view and running a query statement on the view:
SQL> CREATE VIEW managed_dept AS
SELECT * FROM departments WHERE manager_id IS NOT NULL;
View created.
SQL> SELECT * FROM managed_dept WHERE location_id = 1700;
DEPARTMENT DEPARTMENT_NAME MANAGER_ID LOCATION_ID
_ID
------------- -------------------- ---------- -----------
10 Administration 200 1700
30 Purchasing 114 1700
90 Executive 100 1700
100 Finance 108 1700
110 Accounting 205 1700
10. How To Filter Out Duplications in Returning Rows?
If there are duplications in the returning rows, and you want to remove the duplications, you can use the keyword DISTINCT or UNIQUE in the SELECT clause. The tutorial exercise below shows you that DISTINCT works on selected columns only:
SQL> CREATE TABLE fyi_team AS
SELECT first_name, last_name FROM employees
WHERE first_name = 'John';
Table created.
SQL> INSERT INTO fyi_team VALUES ('John', 'Chen');
SQL> INSERT INTO fyi_team VALUES ('James', 'Chen');
SQL> INSERT INTO fyi_team VALUES ('Peter', 'Chen');
SQL> INSERT INTO fyi_team VALUES ('John', 'Chen');
SQL> SELECT * FROM fyi_team;
FIRST_NAME LAST_NAME
----------------- ------------------------
John Chen
John Russell
John Seo
John Chen
James Chen
Peter Chen
John Chen
SQL> SELECT DISTINCT * FROM fyi_team;
FIRST_NAME LAST_NAME
----------------- ----------------------
Peter Chen
John Chen
James Chen
John Seo
John Russell
SQL> SELECT DISTINCT last_name FROM fyi_team;
LAST_NAME
-------------------------
Chen
Russell
Seo
11. What Are Group Functions?
Group functions are functions applied to a group of rows. Examples of group functions are:
◉ COUNT(*) - Returns the number of rows in the group.
◉ MIN(exp) - Returns the minimum value of the expression evaluated on each row of the group.
◉ MAX(exp) - Returns the maximum value of the expression evaluated on each row of the group.
◉ AVG(exp) - Returns the average value of the expression evaluated on each row of the group.
12. How To Use Group Functions in the SELECT Clause?
If group functions are used in the SELECT clause, they will be used on the rows that meet the query selection criteria, the output of group functions will be returned as output of the query. The following select statement returns 4 values calculate by 4 group functions on all rows of the "departments" table:
SQL> SELECT COUNT(*), MIN(department_id),
2 MAX(department_id) FROM departments;
COUNT(*) MIN(DEPARTMENT_ID) MAX(DEPARTMENT_ID)
---------- ------------------ ------------------
27 10 270
13. Can Group Functions Be Mixed with Non-group Selection Fields?
If a group function is used in the SELECT clause, all other selection fields must be group level fields. Non-group fields can not be mixed with group fields in the SELECT clause. The script below gives you an example of invalid SELECT statements with group and non-gorup selection fields:
SQL> SELECT COUNT(*), department_id FROM departments;
ORA-00937: not a single-group group function
In this example, COUNT(*) is a group field and department_id is a non-group field.
14. How To Divide Query Output into Groups?
You can divide query output into multiple groups with the GROUP BY clause. It allows you specify a column as the grouping criteria, so that rows with the same value in the column will be considered as a single group. When the GROUP BY clause is specified, the select statement can only be used to return group level information. The following script gives you a good GROUP BY example:
SQL> SELECT department_id, MIN(salary), MAX(salary),
2 AVG(salary) FROM employees GROUP BY department_id;
DEPARTMENT_ID MIN(SALARY) MAX(SALARY) AVG(SALARY)
------------- ----------- ----------- -----------
100 6900 12000 8600
30 2500 11000 4150
7000 7000 7000
90 17000 24000 19333.3333
20 6000 13000 9500
70 10000 10000 10000
110 8300 12000 10150
50 2100 8200 3475.55556
......
15. How To Apply Filtering Criteria at Group Level?
If you want to return only specific groups from the query, you can apply filtering criteria at the group level by using the HAVING clause inside the GROUP BY clause. The following script gives you a good HAVING example:
SQL> SELECT department_id, MIN(salary), MAX(salary),
2 AVG(salary) FROM employees GROUP BY department_id
3 HAVING AVG(salary) < 5000;
DEPARTMENT_ID MIN(SALARY) MAX(SALARY) AVG(SALARY)
------------- ----------- ----------- -----------
30 2500 11000 4150
50 2100 8200 3475.55556
10 4400 4400 4400
16. How To Count Duplicated Values in a Column?
If you have a column with duplicated values, and you want to know what are those duplicated values are and how many duplicates are there for each of those values, you can use the GROUP BY ... HAVING clause as shown in the following example. It returns how many duplicated first names in the employees table:
SQL> SELECT first_name, COUNT(*) FROM employees
GROUP BY first_name HAVING COUNT(*) > 1;
FIRST_NAME COUNT(*)
-------------------- ----------
Peter 3
Michael 2
Steven 2
John 3
Julia 2
William 2
Karen 2
Kevin 2
......
17. Can Multiple Columns Be Used in GROUP BY?
You can use multiple columns in the GROUP BY clause as shown in the following example. It returns how many employees are having the same salary in each department:
SQL> SELECT department_id, salary, count(*)
2 FROM employees GROUP BY department_id,
3 salary HAVING count(*) > 1;
DEPARTMENT SALARY COUNT(*)
_ID
------------- ---------- ----------
90 17000 2
50 3200 4
50 2200 2
50 3600 2
80 10500 2
80 9000 2
50 2700 2
......
18. Can Group Functions Be Used in the ORDER BY Clause?
If the query output is aggregated as groups, you can sort the groups by using group functions in the ORDER BY clause. The following statement returns how many employees are having the same salary in each department. The group output is sorted by the count in each group in descending order:
SQL> SELECT department_id, salary, count(*)
2 FROM employees GROUP BY department_id,
3 salary HAVING count(*) > 1
ORDER BY COUNT(*) DESC;
DEPARTMENT SALARY COUNT(*)
_ID
------------- ---------- ----------
50 2500 5
50 3200 4
50 2800 3
80 10000 3
80 9500 3
50 3100 3
50 2600 3
.....
19. How To Join Two Tables in a Single Query?
Two tables can be joined together in a query in 4 ways:
◉ Inner Join: Returns only rows from both tables that satisfy the join condition.
◉ Left Outer Join: Returns rows from both tables that satisfy the join condition, and the rest of rows from the first (left) table.
◉ Right Outer Join: Returns rows from both tables that satisfy the join condition, and the rest of rows from the second (right) table.
◉ Full Outer Join: Returns rows from both tables that satisfy the join condition, the rest of rows from the first (left) table, and the rest of rows from the second (right) table.
20. How To Write a Query with an Inner Join?
If you want to query from two tables with an inner join, you can use the INNER JOIN ... ON clause in the FROM clause. The following query returns output with an inner join from two tables: employees and departments. The join condition is that the department ID in the employees table equals to the department ID in the departments table:
SQL> SELECT employees.first_name, employees.last_name,
2 departments.department_name
3 FROM employees INNER JOIN departments
4 ON employees.department_id=departments.department_id;
FIRST_NAME LAST_NAME DEPARTMENT_NAME
-------------------- -------------------- ---------------
Steven King Executive
Neena Kochhar Executive
Lex De Haan Executive
Alexander Hunold IT
Bruce Ernst IT
David Austin IT
Valli Pataballa IT
......
Note that when multiple tables are used in a query, column names need to be prefixed with table names in case the same column name is used in both tables.
21. How To Define and Use Table Alias Names?
When column names need to be prefixed with table names, you can define table alias name and use them to prefix column names as shown in the following select statement:
SQL> SELECT e.first_name, e.last_name, d.department_name
FROM employees e INNER JOIN departments d
ON e.department_id=d.department_id;
FIRST_NAME LAST_NAME DEPARTMENT_NAME
-------------------- -------------------- ---------------
Steven King Executive
Neena Kochhar Executive
Lex De Haan Executive
Alexander Hunold IT
Bruce Ernst IT
David Austin IT
Valli Pataballa IT
......
22. How To Write a Query with a Left Outer Join?
If you want to query from two tables with a left outer join, you can use the LEFT OUTER JOIN ... ON clause in the FROM clause. The following query returns output with a left outer join from two tables: departments and employees. The join condition is that the manager ID in the departments table equals to the employee ID in the employees table:
SQL> set NULL 'NULL'
SQL> SELECT d.department_name, e.first_name, e.last_name
2 FROM departments d LEFT OUTER JOIN employees e
3 ON d.manager_id = e.employee_id;
DEPARTMENT_NAME FIRST_NAME LAST_NAME
-------------------- -------------------- --------------
Administration Jennifer Whalen
Marketing Michael Hartstein
Purchasing Den Raphaely
Human Resources Susan Mavris
Shipping Adam Fripp
IT Alexander Hunold
......
Treasury NULL NULL
Corporate Tax NULL NULL
Control And Credit NULL NULL
Shareholder Services NULL NULL
Benefits NULL NULL
Manufacturing NULL NULL
Construction NULL NULL
......
Note that a left outer join may return extra rows from the first (left) table that do not satisfy the join condition. In those extra rows, columns from the second (right) table will be given null values.
The extra rows returned from the left outer join in this example represents departments that have no manager IDs.
23. How To Write a Query with a Right Outer Join?
If you want to query from two tables with a right outer join, you can use the RIGHT OUTER JOIN ... ON clause in the FROM clause. The following query returns output with a right outer join from two tables: departments and employees. The join condition is that the manager ID in the departments table equals to the employee ID in the employees table:
SQL> set NULL 'NULL'
SQL> SELECT d.department_name, e.first_name, e.last_name
2 FROM departments d RIGHT OUTER JOIN employees e
3 ON d.manager_id = e.employee_id;
DEPARTMENT_NAME FIRST_NAME LAST_NAME
-------------------- -------------------- ---------------
Administration Jennifer Whalen
Marketing Michael Hartstein
Purchasing Den Raphaely
Human Resources Susan Mavris
Shipping Adam Fripp
IT Alexander Hunold
......
NULL Clara Vishney
NULL Jason Mallin
NULL Hazel Philtanker
NULL Nanette Cambrault
NULL Alana Walsh
NULL Karen Partners
NULL Bruce Ernst
......
Note that a right outer join may return extra rows from the second (right) table that do not satisfy the join condition. In those extra rows, columns from the first (left) table will be given null values.
The extra rows returned from the right outer join in this example represents employees that are not assigned as managers in the departments table
24. How To Write a Query with a Full Outer Join?
If you want to query from two tables with a full outer join, you can use the FULL OUTER JOIN ... ON clause in the FROM clause. The following query returns output with a full outer join from two tables: departments and employees. The join condition is that the manager ID in the departments table equals to the employee ID in the employees table:
SQL> set NULL 'NULL'
SQL> SELECT d.department_name, e.first_name, e.last_name
2 FROM departments d FULL OUTER JOIN employees e
3 ON d.manager_id = e.employee_id;
DEPARTMENT_NAME FIRST_NAME LAST_NAME
-------------------- -------------------- --------------
Administration Jennifer Whalen
Marketing Michael Hartstein
Purchasing Den Raphaely
Human Resources Susan Mavris
Shipping Adam Fripp
IT Alexander Hunold
......
Treasury NULL NULL
Corporate Tax NULL NULL
Control And Credit NULL NULL
Shareholder Services NULL NULL
Benefits NULL NULL
Manufacturing NULL NULL
Construction NULL NULL
......
NULL Clara Vishney
NULL Jason Mallin
NULL Hazel Philtanker
NULL Nanette Cambrault
NULL Alana Walsh
NULL Karen Partners
NULL Bruce Ernst
......
Note that a right outer join may return two sets of extra rows: one set from the first (left) table that do not satisfy the join condition, and the other set from the second (right) table that do not satisfy the join condition.
25. How To Write an Inner Join with the WHERE Clause?
If you don't want to use the INNER JOIN ... ON clause to write an inner join, you can put the join condition in the WHERE clause as shown in the following query example:
SQL> SELECT d.department_name, e.first_name, e.last_name
2 FROM departments d, employees e
3 WHERE d.manager_id = e.employee_id;
DEPARTMENT_NAME FIRST_NAME LAST_NAME
-------------------- -------------------- --------------
Administration Jennifer Whalen
Marketing Michael Hartstein
Purchasing Den Raphaely
Human Resources Susan Mavris
Shipping Adam Fripp
IT Alexander Hunold
......
26. How To Write a Left Outer Join with the WHERE Clause?
If you don't want to use the LEFT OUTER JOIN ... ON clause to write a left outer join, you can use a special criteria in the WHERE clause as "left_table.column = right_table.column(+)". The select statement below is an example of a left outer join written with the WHERE clause:
SQL> set NULL 'NULL'
SQL> SELECT d.department_name, e.first_name, e.last_name
2 FROM departments d, employees e
3 WHERE d.manager_id = e.employee_id(+);
DEPARTMENT_NAME FIRST_NAME LAST_NAME
-------------------- -------------------- --------------
Administration Jennifer Whalen
Marketing Michael Hartstein
Purchasing Den Raphaely
Human Resources Susan Mavris
Shipping Adam Fripp
IT Alexander Hunold
......
Treasury NULL NULL
Corporate Tax NULL NULL
Control And Credit NULL NULL
Shareholder Services NULL NULL
Benefits NULL NULL
Manufacturing NULL NULL
......
Note that a left outer join may return extra rows from the first (left) table that do not satisfy the join condition. In those extra rows, columns from the second (right) table will be given null values.
The extra rows returned from the left outer join in this example represents departments that have no manager IDs.
27. How To Name Query Output Columns?
Each column in the query output has a default name. If you don't like the default name, you can specify a new name for any column in the query output by using the AS clause. The following statement shows you a good example:
SQL> SELECT department_id AS ID, MIN(salary) AS Low,
2 MAX(salary) AS High, AVG(salary) AS Average
3 FROM employees GROUP BY department_id
4 HAVING AVG(salary) < 5000;
ID LOW HIGH AVERAGE
---------- ---------- ---------- ----------
30 2500 11000 4150
50 2100 8200 3475.55556
10 4400 4400 4400
28. What Is a Subquery?
A subquery is a SELECT statement used as part of the selection criteria of the main SELECT statement. The subquery specified in the WHERE clause will be evaluated repeated on each row of the selection base table. The output of the subquery will be used in the final evaluation of the criteria. Usually, subqueries are used in the following boolean operations:
"expression IN (subquery)"
"expression NOT IN (subquery)"
"EXISTS (subquery)"
"NOT EXISTS (subquery)"
29. How To Use Subqueries with the IN Operator?
A subquery can be used with the IN operator as "expression IN (subquery)". The subquery should return a single column with one or more rows to form a list of values to be used by the IN operation. The following tutorial exercise shows you how to use a subquery with the IN operator:
SQL> SELECT first_name, last_name FROM employees
2 WHERE department_id IN (
3 SELECT department_id FROM departments
4 WHERE location_id = 1700
5 );
FIRST_NAME LAST_NAME
-------------------- ----------------------
Steven King
Neena Kochhar
Lex De Haan
Nancy Greenberg
Daniel Faviet
John Chen
Ismael Sciarra
30. How To Use Subqueries with the EXISTS Operator?
A subquery can be used with the EXISTS operator as "EXISTS (subquery)", which returns true if the subquery returns one or more rows. The following statement is a good example of "EXISTS (subquery)". It returns rows from employees table that there are rows existing in the departments table linked to the employees table with location_id = 1700.
SQL> SELECT first_name, last_name FROM employees e
2 WHERE EXISTS (
3 SELECT * FROM departments d
4 WHERE e.department_id = d.department_id
5 AND d.location_id = 1700
6 );
FIRST_NAME LAST_NAME
-------------------- -------------------------
Steven King
Neena Kochhar
Lex De Haan
Nancy Greenberg
Daniel Faviet
John Chen
Ismael Sciarra
......
31. How To Use Subqueries in the FROM Clause?
If you have a query returning many rows of data, and you want to perform another query on those rows, you can put the first query as a subquery in the FROM clause of the second query. The following statement shows you how to use a subquery as base table for the main query:
SQL> SELECT * FROM (
2 SELECT first_name, last_name, department_name
3 FROM employees e, departments d
4 WHERE e.department_id = d.department_id
5 ) WHERE department_name LIKE 'S%' ORDER BY last_name;
FIRST_NAME LAST_NAME DEPARTMENT_NAME
----------------- ---------------------- ---------------
Ellen Abel Sales
Sundar Ande Sales
Mozhe Atkinson Shipping
Amit Banda Sales
Elizabeth Bates Sales
Sarah Bell Shipping
......
32. How To Count Groups Returned with the GROUP BY Clause?
If you use the COUNT(*) function on groups returned with the GROUP BY clause, it will count the number of rows within each group, not the number of groups. If you want to count the number of groups, you can put the GROUP BY query into a subquery and apply the COUNT(*) function on the main query as shown in the following tutorial exercise:
SQL> SELECT first_name, COUNT(*) FROM employees
GROUP BY first_name HAVING COUNT(*) > 1;
FIRST_NAME COUNT(*)
-------------------- ----------
Peter 3
Michael 2
Steven 2
John 3
Julia 2
William 2
Karen 2
Kevin 2
......
SQL> SELECT COUNT(*) FROM (
SELECT first_name, COUNT(*) FROM employees
GROUP BY first_name HAVING COUNT(*) > 1
);
COUNT(*)
----------
13
33. How To Return Top 5 Rows?
If you want the query to return only the first 5 rows, you can use the pseudo column called ROWNUM in the WHERE clause. ROWNUM contains the row number of each returning row from the query. The following statement returns the first 5 rows from the employees table:
SQL> SELECT employee_id, first_name, last_name
FROM employees WHERE ROWNUM <= 5;
EMPLOYEE_ID FIRST_NAME LAST_NAME
----------- -------------------- -------------
100 Steven King
101 Neena Kochhar
102 Lex De Haan
103 Alexander Hunold
104 Bruce Ernst
The SELECT statement is also called the query statement. It is the most frequently used SQL statement in any database application. A SELECT statement allows you to retrieve data from one or more tables, or views, with different selection criteria, grouping criteria and sorting orders.
2. How To Select All Columns of All Rows from a Table?
The simplest query statement is the one that selects all columns of all rows from a table: "SELECT * FROM table_name;". The (*) in the SELECT clause tells the query to return all columns. The tutorial exercise below gives you a good example:
SQL> SELECT * FROM departments;
DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID
------------- -------------------- ---------- -----------
10 Administration 200 1700
20 Marketing 201 1800
30 Purchasing 114 1700
40 Human Resources 203 2400
50 Shipping 121 1500
60 IT 103 1400
70 Public Relations 204 2700
80 Sales 145 2500
90 Executive 100 1700
......
3. How To Select Some Columns from a Table?
If you want explicitly tell the query to some columns, you can specify the column names in SELECT clause. The following select statement returns only two columns from the table "departments":
SQL> SELECT location_id, department_name FROM DEPARTMENTS;
LOCATION_ID DEPARTMENT_NAME
----------- ------------------------------
1700 Administration
1800 Marketing
1700 Purchasing
2400 Human Resources
1500 Shipping
1400 IT
2700 Public Relations
2500 Sales
1700 Executive
......
4. How To Select Some Rows from a Table?
If you don't want select all rows from a table, you can specify a WHERE clause to tell the query to return only the rows that meets the condition defined in the WHERE clause. The following select statement only returns rows that has department name starts with the letter "C":
SQL> SELECT * FROM departments
2 WHERE department_name LIKE 'C%';
DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID
------------- -------------------- ---------- -----------
130 Corporate Tax 1700
140 Control And Credit 1700
180 Construction 1700
190 Contracting 1700
......
5. How To Sort the Query Output?
If you want the returning rows to be sorted, you can specify a sorting expression in the ORDER BY clause. The following select statement returns rows sorted by the values in the "manager_id" column:
SQL> SELECT * FROM departments ORDER BY manager_id;
DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID
------------- -------------------- ------------- --------------
90 Executive 100 1700
60 IT 103 1400
100 Finance 108 1700
30 Purchasing 114 1700
50 Shipping 121 1500
80 Sales 145 2500
10 Administration 200 1700
20 Marketing 201 1800
......
6. Can the Query Output Be Sorted by Multiple Columns?
You can specifying multiple columns in the ORDER BY clause as shown in the following example statement, which returns employees' salaries sorted by department and salary value:
SQL> SELECT department_id, first_name, last_name, salary
FROM employees ORDER BY department_id, salary;
DEPARTMENT_ID FIRST_NAME LAST_NAME SALARY
------------- --------------- --------------- ----------
10 Jennifer Whalen 4400
20 Pat Fay 6000
20 Michael Hartstein 13000
30 Karen Colmenares 2500
30 Guy Himuro 2600
30 Sigal Tobias 2800
30 Shelli Baida 2900
30 Alexander Khoo 3100
30 Den Raphaely 11000
40 Susan Mavris 6500
50 TJ Olson 2100
......
7. How To Sort Query Output in Descending Order?
If you want to sort a column in descending order, you can specify the DESC keyword in the ORDER BY clause. The following SELECT statement first sorts the department in descending order, then sorts the salary in ascending order:
SQL> SELECT department_id, first_name, last_name, salary
FROM employees ORDER BY department_id DESC, salary;
DEPARTMENT FIRST_NAME LAST_NAME SALARY
_ID
------------- --------------- --------------- ----------
Kimberely Grant 7000
110 William Gietz 8300
110 Shelley Higgins 12000
100 Luis Popp 6900
100 Ismael Sciarra 7700
100 Jose Manuel Urman 7800
100 John Chen 8200
100 Daniel Faviet 9000
......
8. How To Use SELECT Statement to Count the Number of Rows?
If you want to count the number of rows, you can use the COUNT(*) function in the SELECT clause. The following select statement returns the number of rows in the "department" table:
SQL> SELECT COUNT(*) FROM departments;
COUNT(*)
----------
27
So there are 27 rows in the "departments" table.
9. Can SELECT Statements Be Used on Views?
Select (query) statements can used on views in the same way as tables. The following tutorial exercise helps you creating a view and running a query statement on the view:
SQL> CREATE VIEW managed_dept AS
SELECT * FROM departments WHERE manager_id IS NOT NULL;
View created.
SQL> SELECT * FROM managed_dept WHERE location_id = 1700;
DEPARTMENT DEPARTMENT_NAME MANAGER_ID LOCATION_ID
_ID
------------- -------------------- ---------- -----------
10 Administration 200 1700
30 Purchasing 114 1700
90 Executive 100 1700
100 Finance 108 1700
110 Accounting 205 1700
10. How To Filter Out Duplications in Returning Rows?
If there are duplications in the returning rows, and you want to remove the duplications, you can use the keyword DISTINCT or UNIQUE in the SELECT clause. The tutorial exercise below shows you that DISTINCT works on selected columns only:
SQL> CREATE TABLE fyi_team AS
SELECT first_name, last_name FROM employees
WHERE first_name = 'John';
Table created.
SQL> INSERT INTO fyi_team VALUES ('John', 'Chen');
SQL> INSERT INTO fyi_team VALUES ('James', 'Chen');
SQL> INSERT INTO fyi_team VALUES ('Peter', 'Chen');
SQL> INSERT INTO fyi_team VALUES ('John', 'Chen');
SQL> SELECT * FROM fyi_team;
FIRST_NAME LAST_NAME
----------------- ------------------------
John Chen
John Russell
John Seo
John Chen
James Chen
Peter Chen
John Chen
SQL> SELECT DISTINCT * FROM fyi_team;
FIRST_NAME LAST_NAME
----------------- ----------------------
Peter Chen
John Chen
James Chen
John Seo
John Russell
SQL> SELECT DISTINCT last_name FROM fyi_team;
LAST_NAME
-------------------------
Chen
Russell
Seo
11. What Are Group Functions?
Group functions are functions applied to a group of rows. Examples of group functions are:
◉ COUNT(*) - Returns the number of rows in the group.
◉ MIN(exp) - Returns the minimum value of the expression evaluated on each row of the group.
◉ MAX(exp) - Returns the maximum value of the expression evaluated on each row of the group.
◉ AVG(exp) - Returns the average value of the expression evaluated on each row of the group.
12. How To Use Group Functions in the SELECT Clause?
If group functions are used in the SELECT clause, they will be used on the rows that meet the query selection criteria, the output of group functions will be returned as output of the query. The following select statement returns 4 values calculate by 4 group functions on all rows of the "departments" table:
SQL> SELECT COUNT(*), MIN(department_id),
2 MAX(department_id) FROM departments;
COUNT(*) MIN(DEPARTMENT_ID) MAX(DEPARTMENT_ID)
---------- ------------------ ------------------
27 10 270
13. Can Group Functions Be Mixed with Non-group Selection Fields?
If a group function is used in the SELECT clause, all other selection fields must be group level fields. Non-group fields can not be mixed with group fields in the SELECT clause. The script below gives you an example of invalid SELECT statements with group and non-gorup selection fields:
SQL> SELECT COUNT(*), department_id FROM departments;
ORA-00937: not a single-group group function
In this example, COUNT(*) is a group field and department_id is a non-group field.
14. How To Divide Query Output into Groups?
You can divide query output into multiple groups with the GROUP BY clause. It allows you specify a column as the grouping criteria, so that rows with the same value in the column will be considered as a single group. When the GROUP BY clause is specified, the select statement can only be used to return group level information. The following script gives you a good GROUP BY example:
SQL> SELECT department_id, MIN(salary), MAX(salary),
2 AVG(salary) FROM employees GROUP BY department_id;
DEPARTMENT_ID MIN(SALARY) MAX(SALARY) AVG(SALARY)
------------- ----------- ----------- -----------
100 6900 12000 8600
30 2500 11000 4150
7000 7000 7000
90 17000 24000 19333.3333
20 6000 13000 9500
70 10000 10000 10000
110 8300 12000 10150
50 2100 8200 3475.55556
......
15. How To Apply Filtering Criteria at Group Level?
If you want to return only specific groups from the query, you can apply filtering criteria at the group level by using the HAVING clause inside the GROUP BY clause. The following script gives you a good HAVING example:
SQL> SELECT department_id, MIN(salary), MAX(salary),
2 AVG(salary) FROM employees GROUP BY department_id
3 HAVING AVG(salary) < 5000;
DEPARTMENT_ID MIN(SALARY) MAX(SALARY) AVG(SALARY)
------------- ----------- ----------- -----------
30 2500 11000 4150
50 2100 8200 3475.55556
10 4400 4400 4400
16. How To Count Duplicated Values in a Column?
If you have a column with duplicated values, and you want to know what are those duplicated values are and how many duplicates are there for each of those values, you can use the GROUP BY ... HAVING clause as shown in the following example. It returns how many duplicated first names in the employees table:
SQL> SELECT first_name, COUNT(*) FROM employees
GROUP BY first_name HAVING COUNT(*) > 1;
FIRST_NAME COUNT(*)
-------------------- ----------
Peter 3
Michael 2
Steven 2
John 3
Julia 2
William 2
Karen 2
Kevin 2
......
17. Can Multiple Columns Be Used in GROUP BY?
You can use multiple columns in the GROUP BY clause as shown in the following example. It returns how many employees are having the same salary in each department:
SQL> SELECT department_id, salary, count(*)
2 FROM employees GROUP BY department_id,
3 salary HAVING count(*) > 1;
DEPARTMENT SALARY COUNT(*)
_ID
------------- ---------- ----------
90 17000 2
50 3200 4
50 2200 2
50 3600 2
80 10500 2
80 9000 2
50 2700 2
......
18. Can Group Functions Be Used in the ORDER BY Clause?
If the query output is aggregated as groups, you can sort the groups by using group functions in the ORDER BY clause. The following statement returns how many employees are having the same salary in each department. The group output is sorted by the count in each group in descending order:
SQL> SELECT department_id, salary, count(*)
2 FROM employees GROUP BY department_id,
3 salary HAVING count(*) > 1
ORDER BY COUNT(*) DESC;
DEPARTMENT SALARY COUNT(*)
_ID
------------- ---------- ----------
50 2500 5
50 3200 4
50 2800 3
80 10000 3
80 9500 3
50 3100 3
50 2600 3
.....
19. How To Join Two Tables in a Single Query?
Two tables can be joined together in a query in 4 ways:
◉ Inner Join: Returns only rows from both tables that satisfy the join condition.
◉ Left Outer Join: Returns rows from both tables that satisfy the join condition, and the rest of rows from the first (left) table.
◉ Right Outer Join: Returns rows from both tables that satisfy the join condition, and the rest of rows from the second (right) table.
◉ Full Outer Join: Returns rows from both tables that satisfy the join condition, the rest of rows from the first (left) table, and the rest of rows from the second (right) table.
20. How To Write a Query with an Inner Join?
If you want to query from two tables with an inner join, you can use the INNER JOIN ... ON clause in the FROM clause. The following query returns output with an inner join from two tables: employees and departments. The join condition is that the department ID in the employees table equals to the department ID in the departments table:
SQL> SELECT employees.first_name, employees.last_name,
2 departments.department_name
3 FROM employees INNER JOIN departments
4 ON employees.department_id=departments.department_id;
FIRST_NAME LAST_NAME DEPARTMENT_NAME
-------------------- -------------------- ---------------
Steven King Executive
Neena Kochhar Executive
Lex De Haan Executive
Alexander Hunold IT
Bruce Ernst IT
David Austin IT
Valli Pataballa IT
......
Note that when multiple tables are used in a query, column names need to be prefixed with table names in case the same column name is used in both tables.
21. How To Define and Use Table Alias Names?
When column names need to be prefixed with table names, you can define table alias name and use them to prefix column names as shown in the following select statement:
SQL> SELECT e.first_name, e.last_name, d.department_name
FROM employees e INNER JOIN departments d
ON e.department_id=d.department_id;
FIRST_NAME LAST_NAME DEPARTMENT_NAME
-------------------- -------------------- ---------------
Steven King Executive
Neena Kochhar Executive
Lex De Haan Executive
Alexander Hunold IT
Bruce Ernst IT
David Austin IT
Valli Pataballa IT
......
22. How To Write a Query with a Left Outer Join?
If you want to query from two tables with a left outer join, you can use the LEFT OUTER JOIN ... ON clause in the FROM clause. The following query returns output with a left outer join from two tables: departments and employees. The join condition is that the manager ID in the departments table equals to the employee ID in the employees table:
SQL> set NULL 'NULL'
SQL> SELECT d.department_name, e.first_name, e.last_name
2 FROM departments d LEFT OUTER JOIN employees e
3 ON d.manager_id = e.employee_id;
DEPARTMENT_NAME FIRST_NAME LAST_NAME
-------------------- -------------------- --------------
Administration Jennifer Whalen
Marketing Michael Hartstein
Purchasing Den Raphaely
Human Resources Susan Mavris
Shipping Adam Fripp
IT Alexander Hunold
......
Treasury NULL NULL
Corporate Tax NULL NULL
Control And Credit NULL NULL
Shareholder Services NULL NULL
Benefits NULL NULL
Manufacturing NULL NULL
Construction NULL NULL
......
Note that a left outer join may return extra rows from the first (left) table that do not satisfy the join condition. In those extra rows, columns from the second (right) table will be given null values.
The extra rows returned from the left outer join in this example represents departments that have no manager IDs.
23. How To Write a Query with a Right Outer Join?
If you want to query from two tables with a right outer join, you can use the RIGHT OUTER JOIN ... ON clause in the FROM clause. The following query returns output with a right outer join from two tables: departments and employees. The join condition is that the manager ID in the departments table equals to the employee ID in the employees table:
SQL> set NULL 'NULL'
SQL> SELECT d.department_name, e.first_name, e.last_name
2 FROM departments d RIGHT OUTER JOIN employees e
3 ON d.manager_id = e.employee_id;
DEPARTMENT_NAME FIRST_NAME LAST_NAME
-------------------- -------------------- ---------------
Administration Jennifer Whalen
Marketing Michael Hartstein
Purchasing Den Raphaely
Human Resources Susan Mavris
Shipping Adam Fripp
IT Alexander Hunold
......
NULL Clara Vishney
NULL Jason Mallin
NULL Hazel Philtanker
NULL Nanette Cambrault
NULL Alana Walsh
NULL Karen Partners
NULL Bruce Ernst
......
Note that a right outer join may return extra rows from the second (right) table that do not satisfy the join condition. In those extra rows, columns from the first (left) table will be given null values.
The extra rows returned from the right outer join in this example represents employees that are not assigned as managers in the departments table
24. How To Write a Query with a Full Outer Join?
If you want to query from two tables with a full outer join, you can use the FULL OUTER JOIN ... ON clause in the FROM clause. The following query returns output with a full outer join from two tables: departments and employees. The join condition is that the manager ID in the departments table equals to the employee ID in the employees table:
SQL> set NULL 'NULL'
SQL> SELECT d.department_name, e.first_name, e.last_name
2 FROM departments d FULL OUTER JOIN employees e
3 ON d.manager_id = e.employee_id;
DEPARTMENT_NAME FIRST_NAME LAST_NAME
-------------------- -------------------- --------------
Administration Jennifer Whalen
Marketing Michael Hartstein
Purchasing Den Raphaely
Human Resources Susan Mavris
Shipping Adam Fripp
IT Alexander Hunold
......
Treasury NULL NULL
Corporate Tax NULL NULL
Control And Credit NULL NULL
Shareholder Services NULL NULL
Benefits NULL NULL
Manufacturing NULL NULL
Construction NULL NULL
......
NULL Clara Vishney
NULL Jason Mallin
NULL Hazel Philtanker
NULL Nanette Cambrault
NULL Alana Walsh
NULL Karen Partners
NULL Bruce Ernst
......
Note that a right outer join may return two sets of extra rows: one set from the first (left) table that do not satisfy the join condition, and the other set from the second (right) table that do not satisfy the join condition.
25. How To Write an Inner Join with the WHERE Clause?
If you don't want to use the INNER JOIN ... ON clause to write an inner join, you can put the join condition in the WHERE clause as shown in the following query example:
SQL> SELECT d.department_name, e.first_name, e.last_name
2 FROM departments d, employees e
3 WHERE d.manager_id = e.employee_id;
DEPARTMENT_NAME FIRST_NAME LAST_NAME
-------------------- -------------------- --------------
Administration Jennifer Whalen
Marketing Michael Hartstein
Purchasing Den Raphaely
Human Resources Susan Mavris
Shipping Adam Fripp
IT Alexander Hunold
......
If you don't want to use the LEFT OUTER JOIN ... ON clause to write a left outer join, you can use a special criteria in the WHERE clause as "left_table.column = right_table.column(+)". The select statement below is an example of a left outer join written with the WHERE clause:
SQL> set NULL 'NULL'
SQL> SELECT d.department_name, e.first_name, e.last_name
2 FROM departments d, employees e
3 WHERE d.manager_id = e.employee_id(+);
DEPARTMENT_NAME FIRST_NAME LAST_NAME
-------------------- -------------------- --------------
Administration Jennifer Whalen
Marketing Michael Hartstein
Purchasing Den Raphaely
Human Resources Susan Mavris
Shipping Adam Fripp
IT Alexander Hunold
......
Treasury NULL NULL
Corporate Tax NULL NULL
Control And Credit NULL NULL
Shareholder Services NULL NULL
Benefits NULL NULL
Manufacturing NULL NULL
......
Note that a left outer join may return extra rows from the first (left) table that do not satisfy the join condition. In those extra rows, columns from the second (right) table will be given null values.
The extra rows returned from the left outer join in this example represents departments that have no manager IDs.
27. How To Name Query Output Columns?
Each column in the query output has a default name. If you don't like the default name, you can specify a new name for any column in the query output by using the AS clause. The following statement shows you a good example:
SQL> SELECT department_id AS ID, MIN(salary) AS Low,
2 MAX(salary) AS High, AVG(salary) AS Average
3 FROM employees GROUP BY department_id
4 HAVING AVG(salary) < 5000;
ID LOW HIGH AVERAGE
---------- ---------- ---------- ----------
30 2500 11000 4150
50 2100 8200 3475.55556
10 4400 4400 4400
28. What Is a Subquery?
A subquery is a SELECT statement used as part of the selection criteria of the main SELECT statement. The subquery specified in the WHERE clause will be evaluated repeated on each row of the selection base table. The output of the subquery will be used in the final evaluation of the criteria. Usually, subqueries are used in the following boolean operations:
"expression IN (subquery)"
"expression NOT IN (subquery)"
"EXISTS (subquery)"
"NOT EXISTS (subquery)"
29. How To Use Subqueries with the IN Operator?
A subquery can be used with the IN operator as "expression IN (subquery)". The subquery should return a single column with one or more rows to form a list of values to be used by the IN operation. The following tutorial exercise shows you how to use a subquery with the IN operator:
SQL> SELECT first_name, last_name FROM employees
2 WHERE department_id IN (
3 SELECT department_id FROM departments
4 WHERE location_id = 1700
5 );
FIRST_NAME LAST_NAME
-------------------- ----------------------
Steven King
Neena Kochhar
Lex De Haan
Nancy Greenberg
Daniel Faviet
John Chen
Ismael Sciarra
30. How To Use Subqueries with the EXISTS Operator?
A subquery can be used with the EXISTS operator as "EXISTS (subquery)", which returns true if the subquery returns one or more rows. The following statement is a good example of "EXISTS (subquery)". It returns rows from employees table that there are rows existing in the departments table linked to the employees table with location_id = 1700.
SQL> SELECT first_name, last_name FROM employees e
2 WHERE EXISTS (
3 SELECT * FROM departments d
4 WHERE e.department_id = d.department_id
5 AND d.location_id = 1700
6 );
FIRST_NAME LAST_NAME
-------------------- -------------------------
Steven King
Neena Kochhar
Lex De Haan
Nancy Greenberg
Daniel Faviet
John Chen
Ismael Sciarra
......
31. How To Use Subqueries in the FROM Clause?
If you have a query returning many rows of data, and you want to perform another query on those rows, you can put the first query as a subquery in the FROM clause of the second query. The following statement shows you how to use a subquery as base table for the main query:
SQL> SELECT * FROM (
2 SELECT first_name, last_name, department_name
3 FROM employees e, departments d
4 WHERE e.department_id = d.department_id
5 ) WHERE department_name LIKE 'S%' ORDER BY last_name;
FIRST_NAME LAST_NAME DEPARTMENT_NAME
----------------- ---------------------- ---------------
Ellen Abel Sales
Sundar Ande Sales
Mozhe Atkinson Shipping
Amit Banda Sales
Elizabeth Bates Sales
Sarah Bell Shipping
......
32. How To Count Groups Returned with the GROUP BY Clause?
If you use the COUNT(*) function on groups returned with the GROUP BY clause, it will count the number of rows within each group, not the number of groups. If you want to count the number of groups, you can put the GROUP BY query into a subquery and apply the COUNT(*) function on the main query as shown in the following tutorial exercise:
SQL> SELECT first_name, COUNT(*) FROM employees
GROUP BY first_name HAVING COUNT(*) > 1;
FIRST_NAME COUNT(*)
-------------------- ----------
Peter 3
Michael 2
Steven 2
John 3
Julia 2
William 2
Karen 2
Kevin 2
......
SQL> SELECT COUNT(*) FROM (
SELECT first_name, COUNT(*) FROM employees
GROUP BY first_name HAVING COUNT(*) > 1
);
COUNT(*)
----------
13
33. How To Return Top 5 Rows?
If you want the query to return only the first 5 rows, you can use the pseudo column called ROWNUM in the WHERE clause. ROWNUM contains the row number of each returning row from the query. The following statement returns the first 5 rows from the employees table:
SQL> SELECT employee_id, first_name, last_name
FROM employees WHERE ROWNUM <= 5;
EMPLOYEE_ID FIRST_NAME LAST_NAME
----------- -------------------- -------------
100 Steven King
101 Neena Kochhar
102 Lex De Haan
103 Alexander Hunold
104 Bruce Ernst
0 comments:
Post a Comment