subquery - wordpress.comsubquery: it is also known as nested query. sub queries are queries nested...

19
Subquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner" queries within "outer" queries. Subquery or nested SELECT, allow to realize complex queries which would normally require several queries with storage of the intermediate results. They are characterized by an interrogation (SELECT clause) included in the WHERE clause, the HAVING clause or the SELECT clause of another query. There are basically three types of subqueries are: 1. Single Row Subquery 2. Multiple Row Subquery 3. Multiple Column Subquery 1. Single Row Subqueries : The single-row subquery returns one row. A special case is the scalar subquery, which returns a single row with one column. The single row query uses any operator in the query .i.e. (=, <=, >= <>, <, >). If any of the operators in the preceding table are used with a subquery that returns more than one row, the query will fail. Syntax: SELECT <column, ..> FROM <table> WHERE expression operator (SELECT <column, ...> FROM <table> WHERE <condition); Example: Emp( empid, name, designation, salary, address, city, doj, deptid) Department (deptid, dname)

Upload: others

Post on 17-Mar-2020

15 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

Subquery:

It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner" queries within "outer" queries. Subquery or nested SELECT, allow to realize complex queries which would normally require several queries with storage of the intermediate results. They are characterized by an interrogation (SELECT clause) included in the WHERE clause, the HAVING clause or the SELECT clause of another query.

There are basically three types of subqueries are:1. Single Row Subquery2. Multiple Row Subquery3. Multiple Column Subquery

1. Single Row Subqueries :The single-row subquery returns one row. A special case is the scalar subquery, which returns a single row with one column. The single row query uses any operator in the query .i.e. (=, <=, >= <>, <, >). If any of the operators in the preceding table are used with a subquery that returns more than one row, the query will fail.

Syntax: SELECT <column, ..> FROM <table> WHERE expression operator (SELECT <column, ...> FROM <table> WHERE <condition);

Example:Emp( empid, name, designation, salary, address, city, doj, deptid)Department (deptid, dname)

Page 2: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

Retrieve the name and oldest employee.

SELECT name, datediff("YYYY",doj,date()) as OLD_EMPFROM EmpWHERE datediff("YYYY", doj, date()) = (SELECT max(datediff("YYYY", doj, date())) FROM Emp);

Output:

Retrieve the details of the employee holding the highest salary.

SELECT * from Emp WHERE salary =(SELECT max(salary) FROM Emp);

Output:

- Select name of employee whose salary is greater than average salary.

SELECT name FROM Employeewhere salary >(SELECT avg(salary) FROM Employee);

Output:

Page 3: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

2. Multiple Row SubqueryMultiple-row subquery returns multiple rows. Some operators that can be used with multiple-row subqueries are (IN, ANY, ALL, EXISTS)

Predicates IN, ANY, ALL, EXISTS

A sub query can return a subset of zero to n values. According to the conditions which one wants to express, one can use the predicates IN, ANY, ALL or EXISTS.

Predicate Meaning

IN The comparison operator is the equality and the logical operation between values is OR.

ANY Allows to check if at least a value of the list satisfies condition.

ALL Allows to check if condition is realized for all the values of the list.

EXISTS If the subquery returns a result, the value returned is True otherwise the value returned is False.

IN- Use IN in a WHERE clause to verify that a value in the current row of the main query is part of the set that the subquery returns. You can also preface IN with NOT, to verify that a value in the current row of the main query is not part of the set that the subquery returns.

Display the name , designation, salary who are working in computer department.

SELECT name, designation, salary FROM empwhere deptid IN (select deptid from department where dname ='computer');

Output:

- List the Deptid and name of departments whose employee average salary is between 1000 and 5000.

Page 4: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

SELECT deptid, dname FROM department WHERE deptid IN (select deptid from Emp Group by deptid Having Avg(salary) BETWEEN 1000 AND 5000 );

Output:

EXISTS:

EXISTS simply tests whether the inner query returns any row. If it does, then the outer query proceeds. If not, the outer query does not execute, and the entire SQL statement returns nothing.

- Display the total salary of employees who are working on computer department

SELECT SUM(SALARY) FROM EMPWHERE EXISTS (SELECT * FROM DEPARTMENT WHERE DNAME='COMPUTER');

Output:

Page 5: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

Query Joins - Inner & Outer JoinsWhen you need to view information from two or more separate database tables. For this you will need to use query joins to accomplish the task.

Query JoinsA join is a temporary relationship that you can create between two tables in a database query that do not already have an established relationship or common field with the same fieldname or data type. Database tables that are joined in a query are related in that query only, and nowhere else. The type of join that you use indicates which records the query will select or perform the chosen actions on.Note: Creating a query join will not establish a permanent relationship between the tables. Permanent relationships can only be created in the Microsoft Access relationships window.

Inner JoinDefinition: An inner join is a join that selects only those records from both database tables that have matching values. Records with values in the joined field that do not appear in both of the database tables will be excluded from the query. One or more fields can serve as the join fields. The inner join is also known as an equi-join. The inner join is the default join type in Microsoft Access

The above shows a conceptual diagram of the inner join between Customer data and Order data.Analogy: Consider a business that employs both managers and engineers - and some employees that are both. An inner join is like a union of this set; it selects the set of people that are both managers and engineers and provides information about them in both roles.Outer JoinDefinition: An outer join selects all of the records from one database table and only those records in the second table that have matching values in the joined field. In

Page 6: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

a left outer join, the selected records will include all of the records in the first database table. In a right outer join, the selected records will include all records of the second database table. One or more fields can serve as the join fields.Left Outer Join example:

The above conceptual diagram details the Left Outer Join between Customer data and Order dataAnalogy: Consider again the business that employs both managers and engineers. A left outer join selects all of the managers, providing the information about them, but in the case of managers who are also engineers, it provides additional information about them.Right Outer Join example:

The above shows a conceptual diagram of a Right Outer Join between the Customer data and the Order data.Analogy: Consider again the business that employs both managers and engineers. A right outer join selects the set of all engineers, providing information about them, but in the case of engineers and also managers, if provides additional information about them.Changing the Query Join TypeThe Join Properties dialog box enables you to specify how two tables are to be joined in a Microsoft Access query. The three options that it includes describe which

Page 7: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

records you want the query to select. Option 1 in the dialog box is the inner join (the default in Microsoft Access).Options 2 and 3 represent outer joins. Read the table names carefully when selecting these joins: if the join line was drawn starting from the table on the left, the second option represents the left outer join and the third option will represent a right outer join.In a traditional database diagram, the "one" or "primary" table is usually drawn to the left of the "many" or "secondary" table.In this case, a left outer join includes all records from the table on the "left side", and the right outer join includes all records from the table on the "right side".

Page 8: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

SQL: HAVING CLAUSE

DESCRIPTION

The SQL HAVING Clause is used in combination with the GROUP BY Clause to restrict the groups of returned rows to only those the condition is TRUE.

SYNTAX

The syntax for the SQL HAVING Clause is:

SELECT expression1, expression2, ... expression_n,

aggregate_function (expression)

FROM tables

WHERE conditions

GROUP BY expression1, expression2, ... expression_n

HAVING condition;

Parameters or Arguments

Aggregate function can be a function such as SUM, COUNT, MIN, MAX, or AVG functions.

expression1, expression2, ... expression_n are expressions that are not encapsulated within an aggregate function and must be included in the GROUP BY Clause.

condition is the condition that is used to restrict the groups of returned rows. Only those groups whose condition evaluates to TRUE will be included in the result set.

EXAMPLE - USING SUM FUNCTION

SELECT department, SUM(sales) AS "Total sales"

FROM order_details

GROUP BY department

HAVING SUM(sales) > 1000;

Page 9: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

EXAMPLE - USING COUNT FUNCTION

You could use the SQL COUNT function to return the name of the department and the number of employees (in the associated department) that make over $25,000 / year. The SQL HAVING clause will filter the results so that only departments with more than 10 employees will be returned.

SELECT department, COUNT(*) AS "Number of employees"

FROM employees

WHERE salary > 25000

GROUP BY department

HAVING COUNT(*) > 10;

EXAMPLE - USING MIN FUNCTION

Let's next look at how we could use the HAVING clause with the SQL MIN function.

You could also use the SQL MIN function to return the name of each department and the minimum salary in the department. The SQL HAVING clause will return only those departments where the minimum salary is greater than $35,000.

SELECT department, MIN(salary) AS "Lowest salary"

FROM employees

GROUP BY department

HAVING MIN(salary) > 35000;

EXAMPLE - USING MAX FUNCTION

For example, you could also use the SQL MAX function to return the name of each department and the maximum salary in the department. The SQL HAVING clause will return only those departments whose maximum salary is less than $50,000.

SELECT department, MAX(salary) AS "Highest salary"

FROM employees

GROUP BY department

HAVING MAX (salary) < 50000;

Page 10: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

SQL: IN CONDITION

This SQL tutorial explains how to use the SQL IN condition with syntax and examples.

DESCRIPTION

The SQL IN condition is used to help reduce the need for multiple OR conditions in a SELECT, INSERT, UPDATE, or DELETE statement.

SYNTAX

The syntax for the SQL IN condition is:

expression IN (value1, value2, .... value_n);

Parameters or Arguments

expression is a value to test.

value1, value2..., or value_n are the values to test against expression.

NOTE

The SQL IN condition will return the records where expression is value1, value2..., or value_n.

The SQL IN condition is also called the SQL IN operator.

EXAMPLE - WITH CHARACTER

Let's look at an IN condition example using character values.

The following is a SQL SELECT statement that uses the IN condition to compare character values:

SELECT *

FROM suppliers

WHERE supplier_name IN ('IBM', 'Hewlett Packard', 'Microsoft');

This SQL IN condition example would return all rows where the supplier_name is either IBM, Hewlett Packard, or Microsoft. Because the * is used in the select, all fields from the suppliers table would appear in the result set.

Page 11: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

This IN condition example is equivalent to the following SQL statement:

SELECT *

FROM suppliers

WHERE supplier_name = 'IBM'

OR supplier_name = 'Hewlett Packard'

OR supplier_name = 'Microsoft';

As you can see, using the SQL IN condition makes the statement easier to read and more efficient.

EXAMPLE - WITH NUMERIC

Next, let's look at an IN condition example using numeric values.

For example:

SELECT *

FROM orders

WHERE order_id IN (10000, 10001, 10003, 10005);

This SQL IN condition example would return all orders where the order_id is either 10000, 10001, 10003, or 10005.

This IN condition example is equivalent to the following SQL statement:

SELECT *

FROM orders

WHERE order_id = 10000

OR order_id = 10001

OR order_id = 10003

OR order_id = 10005;

EXAMPLE - USING NOT OPERATOR

Finally, let's look at an IN condition example using the NOT operator.

Page 12: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

For example:

SELECT *

FROM suppliers

WHERE supplier_name NOT IN ( 'IBM', 'Hewlett Packard', 'Microsoft');

Page 13: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

DATE FUNCTIONS IN SQL:

Page 14: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"
Page 15: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"
Page 16: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"

STRING FUNCTIONS IN SQL:

Page 17: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"
Page 18: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"
Page 19: Subquery - WordPress.comSubquery: It is also known as Nested query. Sub queries are queries nested inside other queries, marked off with parentheses, and sometimes referred to as "inner"