+ All Categories

Download - SQL

Transcript
Page 1: SQL

SQL Introduction

SQL stands for Structured Query Language. and it is generally referred to as SEQUEL. SQL is simple language to learn. SQL is a Nonprocedural language, as compared to the procedural or third generation languages (3GLs) such as COBOL and C. SQL was developed by IBM in the 1970s.

The American National Standards Institute (ANSI) published its first SQL standard in 1986 and a second widely adopted standard in 1989. ANSI released updates in 1992, known as SQL92 and SQL2, and again in 1999, termed both SQL99 and SQL3. Each time, ANSI added new features and incorporated new commands and capabilities into the language.

SQL is a simple, yet powerful, language used to create, access, and manipulate data and structure in the database.

SQL Statements categories: DDL - Data Definition Language.

DDL is used to define, alter, or drop database objects and their privileges. DDL statements will implicitly perform a commit.

DDL Statements:

Create It is used to create objects(tables, views) in the database.

Alter It is used to alter the structure of the database objects.

Drop delete database objects (It will invalidate the dependent objects ,it also drops indexes, triggers and referential integrity constraints ).

Truncate remove all records from a table, including all spaces allocated for the records are removed (It is fast as compared to Delete and does not generate undo information as Delete does. It performs an implicit commit as it is a DDL. It resets the high water mark.)

Grant assigning privileges

DML - Data Manipulation Language.

DML is used to access, create, modify or delete data in the structures of the database.

DML Statements:

Select Select data from the database

Insert It is used to insert data into a table

Page 2: SQL

Update It is used to update existing data within a table

Delete It removes rows from the table.

DCL - Data Control Language

Following are the examples of Data control Statements.

DCL Statements:

Commit It will end the current transaction making the changes permanent and visible to all users..

Savepoint It will identify a point(named SAVEPOINT) in a transaction to which you can later roll back

Rollback It will undo all the changes made by the current transaction.

Set- Transaction

It is used to define the properties of a transaction.

SQL Syntax

On this page, you will find SQL syntax for some of the most important SQL commands . These below SQL Syntaxes will be suitable for quick reference.

SELECT [hint][DISTINCT] select_listFROM table_list

[WHERE conditions][GROUP BY group_by_list][HAVING search_conditions]

[ORDER BY order_list [ASC DESC] ][FOR UPDATE for_update_options]

SQL Select Statement

SELECT "column name" FROM "table name"

Example:Select salary from emp;

Page 3: SQL

SQL Where

SELECT "column name"FROM "table name"WHERE "condition"

Example:Select salary from empWhere salary > 2000

SQL Distinct

SELECT DISTINCT "column name"FROM "table name"

Example:Select DISTINCT name from emp;

SQL And/Or

SELECT "column name"FROM "table name"WHERE "condition"{[ANDOR] "condition"}+

Example:SELECT salaryFROM empWHERE Salary > 1000OR (Salary <> 275)

SQL Between

SELECT "column name"FROM "table name"WHERE "column name" BETWEEN 'value1' AND 'value2'

Example:SELECT *FROM empWHERE Date BETWEEN 'Jan-01-1999' AND 'Jan-15-1999'

SQL In

SELECT "column name"

Page 4: SQL

FROM "table name"WHERE "column name" IN ('value1', ‘value2’ ...)

Example:SELECT *FROM empWHERE last_name IN ('sharma', 'dhall')

SQL Like

SELECT "column name"FROM "table name"WHERE "column name" LIKE {PATTERN}

Example:SELECT *FROM empWHERE last_name LIKE '%EN%'

SQL Order By

SELECT "column name"FROM "table name"[WHERE "condition"]ORDER BY "column name" [ASC, DESC]

Example:SELECT name, SalaryFROM empORDER BY name DESC

SQL Count

SELECT COUNT ("column name")FROM "table name"

Example: SELECT COUNT (salary)FROM emp

SELECT * FROM Table;

In the above query, SELECT and FROM are SQL keywords, * is a wildcard which means “all columns”

According to wikipedia Commonly available SQL keywords related to SELECT include:

Page 5: SQL

1. FROM is used to indicate from which tables the data is to be taken, as well as how the tables JOIN to each other.

2. WHERE is used to identify which rows to be retrieved, or applied to GROUP BY. WHERE is evaluated before the GROUP BY.

3. GROUP BY is used to combine rows with related values into elements of a smaller set of rows.4. HAVING is used to identify which of the "combined rows" (combined rows are produced when

the query has a GROUP BY keyword or when the SELECT part contains aggregates), are to be retrieved. HAVING acts much like a WHERE, but it operates on the results of the GROUP BY and hence can use aggregate functions.

5. ORDER BY is used to identify which columns are used to sort the resulting data.

Returning a Single Column from a table

The syntax is as follows:SELECT Column FROM Table;

Oracle uses the ANSI standard concatenation operator, . Because this operator is reserved for string concatenation, the operands don't need to be cast to a string type—they'll be converted automatically:

SELECT FirstName ' ' LastName AS Name FROM EMP_Database;

Sorting with the ORDER BY Clause

The ORDER BY clause is always applied after all other clauses are applied, such as the WHERE and GROUP BY clauses. Without an ORDER BY clause in an SQL statement, rows will often be retrieved in the physical order in which they were added to the table. The default behavior is to sort rows in ascending order.

SELECT ColumnA, ColumnB FROM TableORDER BY ColumnA ASC;

Although this is the default behavior so you don't need to explicitly specify the ASC keyword, it's a better idea to include it to ensure that your queries are as easy to read as possible.

Also, you may want to sort your rows in descending order, in which case you use the DESC keyword:

SELECT ColumnA, ColumnB FROM TableORDER BY ColumnA DESC;

Filtering Data

DISTINCT always retrieves the first value from a repeating group. If there are multiple repeating groups

Page 6: SQL

DISTINCT will retrieve the first row from each group.

Hence, DISTINCT will always require a sort. DISTINCT can operate on a single or multiple columns.

SELECT DISTINCT ColumnA FROM Table;

In order to filter out duplicate rows, you use the DISTINCT keyword.

If you want to retrieve multiple columns, you can guarantee that every row you obtain contains unique data for the specified set of columns.For example, the following query will return only unique combinations of customer names and debit card details:

SELECT DISTINCT CustomerName, DebitCard FROM Customers;

This doesn't mean that you won't have duplicates in either column, only that each combination is unique. You could, for example, have several customers with the same name but with different debit card numbers.

Using WHERE Clause

We can use the WHERE clause to restrict the rows returned by a query.

SELECT ColumnA, ColumnB, ColumnC FROM TableWHERE Condition;

Condition is very flexible, allowing you to test for equalities and inequalities in column data, ranges of values to look for etc. You achieve all this using a simple syntax that includes various operators and keywords that, when combined, allow you to search for pretty much anything.

We can use following comparison operators with the WHERE clause:

Operator Meaning

= Equal

<>, !=, ^= Not Equal

> Greater Than

< Less Than

Page 7: SQL

>=Greater Than Or Equal

<= Less Than Or Equal

And many more for example BETWEEN ...AND..., LIKE, IS NULL etc.

Some examples of where

1)SELECT name FROM bedroomWHERE bedcolor = 'BLACK'OR ceilingcolor = 'GREEN'OR wallcolor = 'YELLOW'

2)SELECT zFROM tWHERE x = 6 AND y > 7 ;

3)Find the average price of Bud.

Sells (bar, beer, price)

SELECT AVG (price)FROM SellsWHERE beer = 'Bud';

SQL SELECT

SQL SELECT

The SELECT statement is used to select data from a database.

The result is stored in a result table, called the result-set.

Page 8: SQL

SQL SELECT Syntax

SELECT column_name(s)FROM table_name

[Source]

The SQL statement below shows a simple usage of the SQL SELECT command:

SELECT FirstName, LastName, DateOfBirthFROM Employees

The SELECT statement has many optional clauses:

WHERE specifies which rows to retrieve.GROUP BY groups rows sharing a property so that an aggregate function can be applied to each group.HAVING selects among the groups defined by the GROUP BY clause.ORDER BY specifies an order in which to return the rows.

SQL Insert

Inserting a new row into the dept tableinsert into dept (deptno, dname, loc)values (10,'Apple','Boston')

You can omit the column list in the insert statement but then you have to enter those in the same order as they appear in the table and you have o include all the columns in the values.

The following example illustrates the use of the "default" keyword while inserting the records.

insert into table_name values(default);

or

insert into table_name(column1,column2..) values(default)

How to create a new table having the same structure as some other table?create table new_tableasselect *from old_table

How to insert data into multiple tables?

There are two terms used INSERT ALL AND INSERT FIRST

Page 9: SQL

EXAMPLE:

Suppose there are three tables emp,emp_1 and emp_2 with the same sructure and columns.

insert allwhen sal in (800,1600) theninto emp (empno,ename,job) values (empno,ename,job)when sal = 3200 theninto emp_1 (empno,ename,job) values (empno,ename,job)elseinto emp_2 (empno,ename,job) values (empno,ename,job)select empno,ename,jobfrom emp

INSERT FIRST will breakout as soon as it sees a condition that evaluates to true.

INSERT ALL will evaluate al the conditions even if the previous condition evluates to true.

Insert Default Values

Some RDBMSs, including SQL Server, allow you to create a new row based on default values that are defined in the table specification using the DEFAULT VALUES method in place of the VALUES section. Suppose you have a table like this:

CREATE TABLE A (A_ID int IDENTITY PRIMARY KEY,Name varchar(100) DEFAULT 'Anonymous',Dates varchar(20) DEFAULT 'Unknown);

and you want to insert a new row with just the default values for each column and the auto-generated ID field. Youcan't do it using the standard INSERT...VALUES syntax, so instead you'd use this:

INSERT INTO A DEFAULT VALUES;

And that does the trick. Using DEFAULT VALUES instead of the standard VALUES clause inserts the default value for every column (or an auto-generated value for identity columns). If there isn't a default value for a non-identity column, the value is treated as NULL. If any column in the table is NOT NULL, isn't an identity column, and doesn't have a default value, then an error will be raised.

Performing a Multi-Row INSERTINSERT INTO S_Backup SELECT EveryName, EveryCost FROM S;

Page 10: SQL

Alternatively, you can easily reshape data and rename columns of rows using a statement such as this:

INSERT INTO S_1 (TheName, TheCost)SELECT EveryName, EveryCost FROM S;

SQL Update

Update Statement is used to change existing values in a table or a view's base table.

Example 1 :update emp set sal = sal*2.25 where deptno = 30

Example 2 :update emp set sal = sal*2.25 where empno in ( select empno from emp_1 )

QC-541) C, 42) E, 43) A, 44) B, 45) A, 46) B, 47) A, 48) C, 49) B, 50) B

SQL Delete

How to delete all records from a table?

Delete from dept;

How to delete specific records from a table?

Delete from emp where empno=20;

How to delete duplicate records from the table?

Suppose we have a table t1(id integer, name varchar(10))

select * from t1;

id name

Page 11: SQL

1 aaa

2 bbb

3 bbb

4 ccc

5 ccc

6 ddd

delete from t1

where id not in ( select min(id)

from t1

group by name )

Few Examples on SQL Delete:

BOTH THE BELOW EXAMPLES OF UPDATE AND DELETE USE CORRELATED SUBQUERIES:

We need to update sal of all the employees in the emp table to the maximum salary in the corresponding dept.

UPDATE emp e1

SET sal = (SELECT MAX(sal)FROM emp e2

            WHERE e1.deptno = e2.deptno);

We need To delete the records of all the employees in the emp table whose sal is below the average sal in the department

DELETE FROM emp e

WHERE sal < (SELECT AVG(sal) FROM emp

                     WHERE deptno = e.deptno);

Page 12: SQL

SQL Joins

You will get vast amount of data/ information on this page regarding Oracle SQL JOINS like

1. SQL Inner Join 2. SQL Outer Join 3. SQL Self Join 4. SQL Cross Join 5. SQL Equijoin 6. Join using MULTIPLE TABLES

SQL Inner Join

SQL Inner Join

Inner joins (the typical join operation, which uses some comparison operator like = or <>). These include equi-joins and natural joins.

Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table. For example, retrieving all rows where the student identification number is the same in both the students and courses tables. [Source]

SQL Inner Joins Example:

The "Consumers" table:

P_Id LastName FirstName Address City

1 Kumar Ram Delhi AAA

2 Singh Laxman Chandigarh AAA

3 Sharma Sameer Ambala BBB

The "Orders" table:

O_Id OrderNo P_Id

1 12355 3

2 12356 3

3 12357 1

Page 13: SQL

4 24562 1

5 34764 15

Now we want to list all the Consumers with any orders.

We use the following SELECT statement:

SELECT Consumers.LastName, Consumers.FirstName, Orders.OrderNoFROM ConsumersINNER JOIN OrdersON Consumers.P_Id=Orders.P_IdORDER BY Consumers.LastName

The result-set will look like this:

LastName FirstName OrderNo

Kumar Ram 12357

Kumar Ram 24562

Sharma Sameer 12355

Sharma Sameer 12356

Atleast one match should be there in both tables involved in inner join in order for the query to return the rows.

When to useinner join

Use an inner join when you want to match values from both tables.

Why to use Inner Joins:

Use inner joins to obtain information from two separate tables and combine that information in one result set.

When you use inner joins, consider the following facts and guidelines:

1. Inner joins are the SQL Server default. You can abbreviate the INNER JOIN clause to JOIN.

Page 14: SQL

2. Specify the columns that you want to display in your result set by including the qualified column names in the select list.

3. Include a WHERE clause to restrict the rows that are returned in the result set.

4. Do not use a null value as a join condition because null values do not evaluate equally with one another.

5. SQL Server does not guarantee an order in the result set unless one is specified with an ORDER BY clause.

SQL Outer Join

Outer joins

Outer joins can be a left, a right, or full outer join.

Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause:

LEFT JOIN or LEFT OUTER JOIN

The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table. [Source]

SQL LEFT JOIN Example

The "Consumers" table:

P_Id LastName FirstName Address City

1 Kumar Ram Delhi AAA

2 Singh Laxman Chandigarh AAA

3 Sharma Sameer Ambala BBB

The "Orders" table:

O_Id OrderNo P_Id

Page 15: SQL

1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 15

Now we want to list all the Consumers and their orders - if any, from the tables above.

We use the following SELECT statement:

SELECT Consumers.LastName, Consumers.FirstName, Orders.OrderNoFROM ConsumersLEFT JOIN OrdersON Consumers.P_Id=Orders.P_IdORDER BY Consumers.LastName

The result-set will look like this:

LastName FirstName OrderNo

Kumar Ram 22456

Kumar Ram 24562

Sharma Sameer 77895

Sharma Sameer 44678

Singh Laxman

The LEFT JOIN keyword returns all the rows from the left table (Consumers), even if there are no matches in the right table (Orders).

RIGHT JOIN or RIGHT OUTER JOIN

A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.

FULL JOIN or FULL OUTER JOIN

Page 16: SQL

A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.

Why to use outer joins

Use left or right outer joins when you require a complete list of data that isstored in one of the joined tables in addition to the information that matches the join condition.

When to use outer joins

Use an outer join when you want to find unmatched rows. (because either you want to find missing values from one of the tables, like in this case, or you may want to include all values from your tables even if they are missing values in the other table).

SQL Self Join

SQL Self Join

Joining a table to itself is called self join.

Example of Self Join

Suppose you have a table that stores an employee identification number, the employee’s name, and the employee identification number of the employee’s manager. You might want to produce a list of all employees and their managers’ names. The problem is that the manager name does not exist as a category in the table:

SELECT * FROM EMP;

ID

NAME

MGR_ID

1

JOHN

0

2MAR

1

Page 17: SQL

Y

3

STEVE

1

4

JACK

2

5SUE

2

In the following example, we have included the table EMP twice in the FROM clause of the query, giving the table two aliases for the purpose of the query. By providing two aliases, it is as if you are selecting from two distinct tables. All managers are also employees, so the JOIN condition between the two tables compares the value of the employee identification number from the first table with the manager identification number in the second table. The first table acts as a table that stores employee information, whereas the second table acts as a table that stores manager information:

SELECT E1.NAME, E2.NAMEFROM EMP E1, EMP E2WHERE E1.MGR_ID = E2.ID;

Name Name

MARY JOHN

STEVE JOHN

JACK MARY

SUE MARY

[Source: Sams Teach Yourself SQL in 24 Hours By Ryan Stephens, Ron Plew, Arie Jones]

Why use self join

Page 18: SQL

While self-joins rarely are used on a normalized database, you can use them to reduce the number of queries that you execute when you compare values of different columns of the same table.

When you use self-joins, consider the following guidelines:

You must specify table aliases to reference two copies of the table. Remember that table aliases are different from column aliases. Table aliases are designated as the table name followed by the alias.

When you create self-joins, each row matches itself and pairs are repeated, resulting in duplicate rows. Use a WHERE clause to eliminate these duplicate rows

SQL Cross Join

SQL Cartesian product:

You will be able to find Cartesian product with a Cartesian join. When we join every row of a table to every row of another table we get Cartesian join

SQL Cross Join:

Cross joins, where every row from one table is matched with every row from another.

Cartesian join and Cross join are one and the same thing.

If T1 and T2 are two sets then cross join = T1 X T2.

Examples of a cross join:

SELECT *FROM emp CROSS JOIN dept

Page 19: SQL

SELECT *FROM emp, dept;

In the first example above it is explicitly written that it is a CROSS JOIN but in the second one it is implicit.

SQL Equi-join

The join condition determines whether the join is an equi-join or a non equi-join. when we relate two tables on a join condition by equating the columns from the tables, it is an equi-join. when we relate two tables on a join condition by an operator other than equality it is an non-equi-join. A query may contain equi-joins as well as non-equi-joins.

Examples of Equi-join:

SELECT emp.deptno, bonus.commFROM emp bonusWHERE emp.ename = bonus.ename

SELECT * FROM empINNER JOIN deptON emp.DeptID = dept.DeptID

Join Using Multiple Tables (more than 2)

Questions: I am looking for the resources/examples on using Oracle9i ANSI joins on multiple tables.

Most of the examples i found are using just two tables to explain the join. I'd appreciate if you could give the examples of writing complex multitable joins for Oracle9i.

I want to join tables A,B,C,D,E in such a way that tables C,D & E will have OUTER join with table A on a key column. I have used this type of join in Informix and now trying to convert it into Oracle9i.

and we said...

Page 20: SQL

The same syntax you used in Informix, given that it was "ansi" style is supported in Oracle9i. There are not "advanced resources" on this cause you are making it harder then it is. It really is as straight forward as it looks.

Just use parents and keep nesting the joins:

[email protected]> create table a ( x int );

Table created.

[email protected]> create table b ( x int );

Table created.

[email protected]> create table c ( x int );

Table created.

[email protected]> create table d ( x int );

Table created.

[email protected]> create table e ( x int );

Table created.

[email protected]>[email protected]> insert into a values ( 1 );

1 row created.

[email protected]> insert into b values ( 1 );

1 row created.

[email protected]>[email protected]> select *2 from (((( a inner join b on a.x = b.x ) left outer join c on a.x = c.x )3 left outer join d on a.x = d.x ) left outer join e on a.x = e.x )

Page 21: SQL

Explicit vs. Implicit SQL Joins

Explicit vs. Implicit SQL Joins

The explicit join is easier to read and the implicit syntax is difficult to understand and more prone to errors. Moreover implicit syntax is now a day’s outdated.

SQL specifies two different syntactical ways to express joins: "explicit join notation" and "implicit join notation":

The "explicit join notation" uses the JOIN keyword to specify the table to join, and the ON keyword to specify the predicates for the join, as in the following example:

SELECT * FROM employee INNER JOIN department ON employee.DepartmentID = department.DepartmentID;

The "implicit join notation" simply lists the tables for joining (in the FROM clause of the SELECT statement), using commas to separate them. Thus, it specifies a cross-join, and the WHERE clause may apply additional filter-predicates (which function comparably to the join-predicates in the explicit notation).

The following example shows a query which is equivalent to the one from the previous example, but this time written using the implicit join notation:

SELECT * FROM employee, department WHERE employee.DepartmentID = department.DepartmentID;

. SQL Group By

SQL Having Examples of SQL Group By and SQL Having Null in SQL Group By

It is a clause in SQL, which specifies how to report the output of the query. Allows one to define a subset of the values of a particular field and to apply an aggregate function to the subsets.

We normally use a GROUP BY clause in conjunction with an aggregate expression (like SUM, COUNT etc).

Example 1 of SQL Group BY

Page 22: SQL

Calculate the total sales for each store in the following table

store_name Sales Date

London $1500 Jan-05-1999

San Diego $250 Jan-07-1999

London $300 Jan-08-1999

Boston $700 Jan-08-1999

First, we need to make sure we select the store name as well as total sales.

SELECT store_name, SUM (Sales)FROM Store_Information

Second, we need to make sure that all the sales figures are grouped by stores.

SELECT store_name, SUM (Sales)FROM Store_InformationGROUP BY store_name

So the final query is:

SELECT store_name, SUM (Sales)FROM Store_InformationGROUP BY store_name

The result is:

store_name SUM(Sales)

London $1800

San Diego $250

Boston $700

Page 23: SQL

Example 2 of SQL Group BY

SELECT COUNT (*) FROM t_state

The above statement returns the total number of rows in the table. We can use GROUP BY to count the number of offices in each state.

With GROUP BY, the table is split into groups by state, and COUNT (*) is applied to each group in turn.

SELECT state, COUNT (*)FROM t_stateGROUP BY state;

Important points to remember:

Group by cannot use column aliasing. A GROUP BY clause must contain the column or expressions on which to perform the grouping operation. For example:

Incorrect way:

Select deptno as department, count (*) as cntFrom empGroup by department

Correct way is:

Select deptno as department, count (*) as cntFrom empGroup by deptno

What is the difference between the outputs of the following two queries?

Statement 1:

SELECT COUNT (*), SUM (comm)FROM hr.employees;

Statement 2:

Page 24: SQL

SELECT COUNT (comm), SUM (comm)FROM hr.employees;

The COUNT (*) will count all rows in the table.

The COUNT (comm) will count only the number commission values that appear in the table. If there are any rows with a NULL commission, statement 2 will not count them.

Restriction on SELECT Lists with Aggregation

If any aggregation is used, then each element of a SELECT clause must either be aggregated or appear in a group-by clause. i.e. as a rule, when using GROUP BY and aggregate functions, any items in the SELECT list not used as an argument to an aggregate function must be included in the GROUP BY clause.

SQL Group By Examples

Example 1 of SQL Group By

Let us say we have a table name Orders.

Orders (O_Id, OrderDate, OrderPrice, Customer)

we want to find the total sum (total order) of each customer.

SELECT Customer,SUM(OrderPrice)FROM OrdersGROUP BY Customer

Source: http://www.w3schools.com/sql/sql_groupby.asp

Example 2 of SQL Group By

Let us say we have a table name Sales.

Sales(OrderID, OrderDate, OrderPrice, OrderQuantity, CustomerName)

We want to retrieve a list with unique customers from our Sales table, and at the same time to get the total amount each customer has spent in our store.

SELECT CustomerName, SUM(OrderPrice)FROM SalesGROUP BY CustomerName

Source: http://www.sql-tutorial.com/sql-group-by-sql-tutorial/

Page 25: SQL

Example 3 of SQL Group By

Returns a list of Department IDs along with the sum of their sales for the date of January 1, 2000.

SELECT DeptID, SUM(SaleAmount)FROM SalesWHERE SaleDate = '01-Jan-2000'GROUP BY DeptID

Source: http://en.wikipedia.org/wiki/Group_by_(SQL)

Example 4 of SQL Group By

From Sells(bar, beer, price) find the average price for each beer

SELECT beer, AVG(price)FROM SellsGROUP BY beer;

Source: infolab.stanford.edu/~ullman/fcdb/aut07/slides/ra-sql2.ppt

Example 5 of SQL Group By

You could use the COUNT function to return the name of the department and the number of employees (in the associated department) that make over $25,000 / year.

SELECT department, COUNT(*) as "Number of employees"FROM employeesWHERE salary > 25000GROUP BY department;

SQL Having

SQL Group By Examples of SQL Group By and SQL Having Null in SQL Group By

The SQL HAVING clause allows us to restrict the data that is sent to the GROUP BY clause.

Group functions cannot be used in the WHERE clause. SQL statement can have both a WHERE clause and an HAVING clause. WHERE filters data before grouping and HAVING filters the data after grouping.

Page 26: SQL

A WHERE clause is useful in both grouped and ungrouped queries, while a HAVING clause should appear only immediately after the GROUP BY clause in a grouped query.

According to Wikipedia (http://en.wikipedia.org) HAVING statement in SQL specifies that a SQL SELECT statement should only return rows where aggregate values meet the specified conditions.

An SQL statement with the HAVING clause may or may not include the GROUP BY clause.

HAVING allows a user to perform conditional tests on aggregate values. It is often used in combination with GROUP BY. With HAVING, you can include or exclude groups based on the aggregate value for that group.

Example 1 of SQL Having

Find the average salary of for each department that has either more than 1 employee or starts with a “To”:

SELECT Dept, AvgSal=(AVG(Salary))FROM EmployeeGROUP BY DeptHAVING COUNT(Name) > 1 OR Dept LIKE “To”

Example 2 of SQL Having

Workforce (workforceno, name, position, salary, email, dcenterno)

For each distribution center with more than one member of workforce, find the number of workforce working in each of the centers and the sum of their salaries.

SELECT dCenterNo, COUNT(workforceNo) AS totalworkforce,SUM(salary) AS totalSalaryFROM workforceGROUP BY dCenterNoHAVING COUNT(workforceNo) > 1ORDER BY dCenterNo;

Important points about SQL Having:

Aggregates cannot be used in a WHERE clause; they are used only inside HAVING.

Similar to the WHERE clause, the HAVING clause requires that the column names that appear in the

Page 27: SQL

clause must also appear as column names in the GROUP BY clause.

Similar to the WHERE clause, it is ok for column names not appearing in the GROUP BY clause to appear as arguments to aggregate functions.

SQL IN

Example 1 of SQL IN

You can use the IN function as below:

SELECT *FROM EMPWHERE EMP_ID in (10000, 10001, 10003, 10005);

This SQL statement would return all EMPLOYEES where the EMP_ID is either 10000, 10001, 10003, or 10005.

Example 2 of SQL IN

SELECT *FROM suppliersWHERE supplier_name in ('Apple', 'HP', 'Microsoft');

Above query will return all rows where the supplier_name is either Apple, HP, or Microsoft.

SQL NULLs

NULL is UNKNOWN or MISSING data. NULL affects the integrity of the database.

In order to prevent nulls from inserted in the database, table should have NOT NULL constraint.

Two ways NOT NULL constraint can be implemented on database:

1) Implement Constraint when Table is created

CREATE TABLE ConstraintTable(ID INT, ColSecond INT NOT NULL)

2) Implement Constraint after Table is created

ALTER TABLE ConstraintTableALTER COLUMN ID INT NOT NULL

[Source]

Page 28: SQL

An Example showing how null values are treated in aggregate functions:

Table Item_Sales_2010_Data

item_name Sales_2010

item A 300

item B 200

item C 100

item D NULL

Following are the results for aggregate functions:

SUM (Sales_2010) = 600AVG (Sales_2010) = 200MAX (Sales_2010) = 300MIN (Sales_2010) = 100COUNT (Sales_2010) = 3

SQL - IS NULL

In order to select only the records with NULL values in the "Email" column?

Using the IS NULL operator:

SELECT LastName, FirstName, Email FROM EMPWHERE Email IS NULL

SQL - IS NOT NULL

Selecting only the records with no NULL values in the "Email" column:

Using the IS NOT NULL operator:

SELECT LastName, FirstName, Email FROM EMPWHERE Email IS NOT NULL

Page 29: SQL

ISNULL()

You can use ISNULL() function to replace NULL value with another value.

ISNULL(expression1, ValueIfNull)

The following example selects the description, Price, minimum quantity, and maximum quantity from Sales. If the maximum quantity for a particular special offer is NULL, the MaxQty shown in the result set is 0.00.

SELECT Description, Price, MinQty, ISNULL(MaxQty, 0.00) AS 'Max Quantity'FROM Sales;

Another Example

Why does query A returns a result but B doesn't?

A: select 'true' where 3 in (1, 2, 3, null)B: select 'true' where 3 not in (1, 2, null)

Query A:

select 'true' where 3 = 1 or 3 = 2 or 3 = 3 or 3 = null

Since 3 = 3 is true, you get a result.

Query B:

select 'true' where 3 <> 1 and 3 <> 2 and 3 <> null

When ansi_nulls is on, 3 <> null is UNKNOWN, so the predicate evaluates to UNKNOWN, and you don't get any rows.

When ansi_nulls is off, 3 <> null is true, so the predicate evaluates to true, and you get a row.

SQL Subqueries

SQL inline View subquery SQL Correlated subquery SQL Scalar subquery

Subquery is a query inside a main query.

Page 30: SQL

SQL subquery can be embedded:

As a column expression in the main SQL statement As a filter inside the WHERE (or HAVING) clause in the main SQL statement As a datasource inside the FROM clause in the main SQL statement

While working with SQL Subqueries you must:

Enclose the subquery in parentheses Do not use a semicolon at the end of the subquery statement

Example 1 of subquery

Find the names of all of the managers in the Employees table.

Employees (emp_id, Emp_name, ManagerID)

SELECT Emp_name AS EmployeeFROM EmployeesWHERE emp_id IN (SELECT DISTINCT ManagerID FROM Employees)

Example 2 of SQL Subquery

Store_Info (store_name, sales, date)Location (region_names, store_name)

Find the sales of all stores in the East region.

SELECT SUM(Sales) FROM Store_InfoWHERE Store_name IN(SELECT store_name FROM LocationWHERE region_name = 'East')

You can nest any number of such queries; Oracle does not have a limit.

There is also another term used NESTED SUBQUERIES. when you use subqueries in the WHERE clause of the SELECT statement it is called nested subquery. There are only 255 levels of subqueries.

SQL Subqueries

Page 31: SQL

SQL inline View subquery SQL Correlated subquery SQL Scalar subquery

Subquery is a query inside a main query.

SQL subquery can be embedded:

As a column expression in the main SQL statement As a filter inside the WHERE (or HAVING) clause in the main SQL statement As a datasource inside the FROM clause in the main SQL statement

While working with SQL Subqueries you must:

Enclose the subquery in parentheses Do not use a semicolon at the end of the subquery statement

Example 1 of subquery

Find the names of all of the managers in the Employees table.

Employees (emp_id, Emp_name, ManagerID)

SELECT Emp_name AS EmployeeFROM EmployeesWHERE emp_id IN (SELECT DISTINCT ManagerID FROM Employees)

Example 2 of SQL Subquery

Store_Info (store_name, sales, date)Location (region_names, store_name)

Find the sales of all stores in the East region.

SELECT SUM(Sales) FROM Store_InfoWHERE Store_name IN(SELECT store_name FROM LocationWHERE region_name = 'East')

You can nest any number of such queries; Oracle does not have a limit.

Page 32: SQL

There is also another term used NESTED SUBQUERIES. when you use subqueries in the WHERE clause of the SELECT statement it is called nested subquery. There are only 255 levels of subqueries.

SQL Inline View Subquery

SQL Subqueries SQL Correlated subquery SQL Scalar subquery

When you use SQL Subquery in From clause of the select statement it is called inline view.

A common use for inline views in Oracle SQL is to simplify complex queries by removing join operations and condensing several separate queries into a single query. A subquery which is enclosed in parenthesis in the FROM clause may be given an alias name. The columns selected in the subquery can be referenced in the parent query, just as you would select from any normal table or view.

Example 1 of Inline View

Display the top five earner names and salaries from the EMPLOYEES table:

SELECT ROWNUM as RANK, last_name, salaryFROM (SELECT last_name, salary FROM employees ORDER BY salary DESC)WHERE ROWNUM <= 5;

Example 2 of Inline View

Calculate the number of employees in each department

SELECT d.dept_id, d.name, emp_cnt.totFROM department d, (SELECT dept_id, count(*) tot FROM employee GROUP BY dept_id) emp_cntWHERE d.dept_id = emp_cnt.dept_id;

SQL Correlated Subquery

SQL inline View subquery SQL Subqueries SQL Scalar subquery

When you reference a column from the table in the parent query in the subquery, it is known as a

Page 33: SQL

correlated subquery. For each row processed in the parent query, the correlated subquery is evaluated once.

While processing Correlated subquery:

The first row of the outer query is fetched. The inner query is processed using the outer query’s value or values. The outer query is processed using the inner query’s value or values. This process is continued until the outer query is done.

Example 1 of Correlated subquery

Display all employees who have switched jobs at least twice.

SELECT e.last_name, e.salary, e.job_idFROM employees eWHERE 2 <= (SELECT Count(*) FROM job_history j WHERE j.employee_id = e.employee_id);

Example 2 of Correlated subquery

SELECT S.Number, S.NameFROM Salesman SWHERE S.Number IN(SELECT C.Salesman FROM Customer C WHERE C.Name = S.Name);

SQL Scalar subquery

SQL inline View subquery SQL Correlated subquery SQL Subqueries

A scalar subquery returns a single row and a single column value.

Example 1 of Scalar subquery

SELECT last_name, job_id, salaryFROM employeesWHERE salary > (SELECT avg(salary) FROM employees);

Example 2 of Scalar subquery

Page 34: SQL

Select dname, (select count(*) from emp where emp.deptno= dept.deptno) cntfrom dept

SQL Subqueries can be single row, multiple rows, single column and multiple columns.

You can use single-row subqueries with single-row operators and multiple-row subqueries with multiple-row operators.

Example of Single Row Subquery

Find the highest salary :

SELECT last_name, salaryFROM employeesWHERE salary = (Select MAX(salary) FROM employees);

Example of Multiple Row Subquery

SELECT employee_id, last_name, salaryFROM employeesWHERE salary IN (SELECT Min(salary) FROM employees GROUP BY department_id);

Example of single column subquery

A query to retrieve the name of highest paid person in the department 30

Please see that ALL is used with comparison operator because subquery is not returning single value, It is returning multiple values.

Select first_name, last_namefrom employeewhere dept_id =30 and salary >=ALL (Select salary from employee where dept_id = 30);

Example of Multiple column subquery

A subquery that compares more than just one column between the parent query and the subquery is called multiple-column subquery.

Page 35: SQL

Extract employees that make the same salaries as other employee with employee_id 420 with the same job

Select employee_ID, last_name, job_id, salaryfrom employeeswhere (job_id, salary) in (select job_id, salary from employees where employee_id =420);


Top Related