SQL Server 2005
About SQL Server
Microsoft SQL Server is a Relational Database Management System (RDBMS) designed to run on platforms ranging from laptops to large multiprocessor servers. SQL Server is commonly used as the backend system for websites and can support thousands of concurrent users.
SQL Server comes with a number of tools to help you with your database administration and programming tasks.
SQL Server is much more robust and scalable than a desktop database management system such as Microsoft Access. Although SQL Server can also be run as a desktop database system, it is most commonly used as a server database 2 system.
Server Database Systems
Server based database systems are designed to run on a central server, so that multiple users can access the same data simultaneously. The users normally access the database through an application. For example, a website could store all its content in a database. Whenever a visitor views an article, they are retrieving data from the database. As you know, websites aren't normally limited to just one user. So, at any given moment, a website could be serving up hundreds, or even thousands of articles to its website visitors. At the same time, other users could be updating their personal profile in the members' area, or subscribing to a newsletter, or anything else that website users do.
SQL Server 2005 Management Studio
From the Start menu, go to All Programs, select Microsoft SQL Server 2005, and then SQL Server Management Studio.
The Microsoft SQL Server Management Studio screen contains the Object Explorer on the left portion of the screen and, to start with, a Summary tab on the right portion of the screen. The Object Explorer provides a hierarchical view of objects.
For example, you can navigate through a database, table, column, or other types of objects.
Creating a Database in Microsoft SQL Server 2005
Creating a Database in Microsoft SQL Server 2005
System Databases
Database master Type System database Description Stores system level information such as user accounts, configuration settings, and info on all other databases. is a template database. Every time a new database is created, SQL Server makes a copy of the model database (and all of the objects in it) to form the basis of the new database Used by the SQL Server Agent that performs scheduled activities such as backups and replication tasks. Holds intermediate results created internally by SQL Server during query processing and sorting. 8
model
System database
msdb
System database
tempdb
System database
The Query Editor
The most important thing you do in SQL Server 2005, or in any other database for that matter, is query the database. Queries in SQL Server 2005 are typed in the query editor. The query editor can be opened in two ways, as discussed in the following subsections: (a) by right-clicking, and (b) by using the New Query button
SQL Introduction
SQL stands for Structured Query Language. SQL is a language that enables you to work with a database. Using SQL, you can insert records, update records, and delete records. You can also create new database objects such as databases and tables. And you can drop (delete) them.
10
DML & DDL
SQL is divided into two main categories; Data Manipulation Language (DML), and Data Definition Language (DDL). An explanation follows.
Data Manipulation Language (DML)
DML enables you to work with the data that goes into the database. DML is used to insert, select, update, and delete records in the database. SQL statements will begin with one of the following commands: SELECT - Retrieves data from the database INSERT - Inserts new data into the database UPDATE - Updates existing data in the database DELETE - Deletes existing data from the database
11
Data Definition Language (DDL)
You may also occasionally need to create or drop a table or other database object. SQL enables you to do this programmatically using DDL.
Examples of DDL commands: CREATE TABLE - Creates a new table ALTER TABLE - Modifies the table DROP TABLE - Drops (deletes) a table
12
Selecting All columns
SELECT * FROM dept; DEPTNO --------10 20 30 40 DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS LOC ------------NEW YORK DALLAS CHICAGO BOSTON
Selecting Specific Columns
SELECT deptno, loc FROM dept DEPTNO --------10 20 30 40 LOC ------------NEW YORK DALLAS CHICAGO BOSTON
Arithmetic Expressions
Create expressions on NUMBER data by using arithmetic operators.
Operator + -
Description Add Subtract
*
/
Multiply
Divide
Operator Precedence
* / +
Multiplication and division take priority over addition and subtraction. Operators of the same priority are evaluated from left to right. Parentheses are used to force prioritized evaluation and to clarify statements.
SELECT ename, sal, 12*sal+100 FROM emp; ENAME SAL 12*SAL+100 ---------- --------- ---------KING 5000 60100 BLAKE 2850 34300 CLARK 2450 29500 JONES 2975 35800 MARTIN 1250 15100 ALLEN 1600 19300 ... 14 rows selected.
Using Parentheses
SELECT ename, sal, 12*(sal+100) FROM emp; ENAME SAL 12*(SAL+100) ---------- --------- ----------KING 5000 61200 BLAKE 2850 35400 CLARK 2450 30600 JONES 2975 36900 MARTIN 1250 16200 ... 14 rows selected.
Concatenation Operator
Concatenates columns or character strings to other columns Is represented by plus sign (+) Creates a resultant column that is a character expression
Using the Concatenation Operator
SELECT
ename
job
FROM emp;
Employees ------------------KINGPRESIDENT BLAKEMANAGER CLARKMANAGER JONESMANAGER MARTINSALESMAN ALLENSALESMAN ... 14 rows selected.
Eliminating Duplicate Rows
Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause.
SELECT
DISTINCT deptno
FROM
emp;
DEPTNO --------10 20 30
SELECT without FROM
SELECT International
SELECT 100
Renaming Result Set Column Names
SELECT ename as Name, sal as Salary , 12*(sal+100) as Annual Salary FROM emp;
Renaming Result Set Column Names
SELECT ename as Name, sal as Salary , 12*(sal+100) as Annual Salary FROM emp;
Limiting Rows Selected
Restrict the rows returned by using the WHERE clause.
SELECT FROM [WHERE [DISTINCT] {*, column...} table condition(s)];
The WHERE clause follows the FROM clause.
Using the WHERE Clause
SELECT ename, job, deptno FROM emp WHERE job='CLERK';
ENAME ---------JAMES SMITH ADAMS MILLER
JOB DEPTNO --------- --------CLERK 30 CLERK 20 CLERK 20 CLERK 10
Comparison Operators
Operator
= > >= < <= <>
Meaning
Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to
Using the Comparison Operators
SELECT ename, sal, comm FROM emp WHERE sal<=comm;
ENAME SAL COMM ---------- --------- --------MARTIN 1250 1400
Other Comparison Operators
Operator BETWEEN ...AND... IN(list) LIKE IS NULL
Meaning Between two values (inclusive)
Match any of a list of values Match a character pattern Is a null value
Using the BETWEEN Operator
Use the BETWEEN operator to display rows based on a range of values.
SELECT FROM WHERE ename, sal emp sal BETWEEN 1000 AND 1500;
ENAME SAL ---------- --------MARTIN 1250 TURNER 1500 WARD 1250 ADAMS 1100 MILLER 1300
Lower limit
Higher limit
Using the IN Operator Use the IN operator to test for values in a list.
SELECT FROM WHERE
empno, ename, sal, mgr emp mgr IN (7902, 7566, 7788);
EMPNO --------7902 7369 7788 7876
ENAME SAL MGR ---------- --------- --------FORD 3000 7566 SMITH 800 7902 SCOTT 3000 7566 ADAMS 1100 7788
Using the LIKE Operator
Use the LIKE operator to perform wildcard searches of valid search string values. Search conditions can contain either literal characters or numbers. % denotes zero or many characters _ denotes one character
SELECT FROM WHERE
ename emp ename LIKE 'S%';
Using the LIKE Operator
SELECT FROM WHERE
ename emp ename
LIKE '_A%';
ENAME ---------JAMES WARD
Logical Operators
Operator AND OR
Meaning Returns TRUE if both component conditions are TRUE Returns TRUE if either component condition is TRUE Returns TRUE if the following condition is FALSE
NOT
Using the AND Operator
Using the AND Operator
SQL> 2 3 4 SELECT FROM WHERE AND empno, ename, job, sal emp sal>=1100 job='CLERK'; JOB SAL --------- --------CLERK 1100 CLERK 1300
EMPNO --------7876 7934
ENAME ---------ADAMS MILLER
Using the OR Operator OR requires either condition to be TRUE.
SELECT empno, ename, job, sal FROM emp WHERE sal>=1100 OR job='CLERK'; EMPNO ENAME JOB SAL --------- ---------- --------- --------7839 7698 7782 7566 7654 KING BLAKE CLARK JONES MARTIN PRESIDENT MANAGER MANAGER MANAGER SALESMAN 5000 2850 2450 2975 1250
... 14 rows selected.
Using the NOT Operator
SELECT ename, job FROM emp WHERE job NOT IN ('CLERK','MANAGER','ANALYST');
ENAME ---------KING MARTIN ALLEN TURNER WARD
JOB --------PRESIDENT SALESMAN SALESMAN SALESMAN SALESMAN
Rules of Precedence
Order Evaluated 1 2 3 4
Operator All comparison operators NOT AND OR
Override rules of precedence by using parentheses.
Rules of Precedence
SELECT ename, job, sal FROM emp WHERE job='SALESMAN' OR job='PRESIDENT' AND sal>1500;
ENAME ---------KING MARTIN ALLEN TURNER WARD
JOB SAL --------- --------PRESIDENT 5000 SALESMAN 1250 SALESMAN 1600 SALESMAN 1500 SALESMAN 1250
Rules of Precedence
Use parentheses to force priority.
SELECT ename, job, sal FROM emp WHERE (job='SALESMAN' OR job='PRESIDENT') AND sal>1500;
ENAME ---------KING ALLEN
JOB SAL --------- --------PRESIDENT 5000 SALESMAN 1600
ORDER BY Clause
Sort rows with the ORDER BY clause ASC: ascending order, default DESC: descending order The ORDER BY clause comes last in the SELECT statement.
SELECT ename, job, deptno, hiredate FROM emp ORDER BY hiredate;
ENAME JOB DEPTNO HIREDATE ---------- --------- --------- --------SMITH CLERK 20 17-DEC-80 ALLEN SALESMAN 30 20-FEB-81 ... 14 rows selected.
Sorting in Descending Order
SELECT ename, job, deptno, hiredate FROM emp ORDER BY hiredate DESC; ENAME JOB DEPTNO HIREDATE ---------- --------- --------- --------ADAMS CLERK 20 12-JAN-83 SCOTT ANALYST 20 09-DEC-82 MILLER CLERK 10 23-JAN-82 JAMES CLERK 30 03-DEC-81 FORD ANALYST 20 03-DEC-81 KING PRESIDENT 10 17-NOV-81 MARTIN SALESMAN 30 28-SEP-81 ... 14 rows selected.
Sorting by Multiple Columns
The order of ORDER BY list is the order of sort.
SELECT ename, deptno, sal FROM emp ORDER BY deptno, sal DESC; ENAME DEPTNO SAL ---------- --------- --------KING 10 5000 CLARK 10 2450 MILLER 10 1300 FORD 20 3000 ... 14 rows selected.
You can sort by a column that is not in the SELECT list.
Displaying Data from Multiple Tables
Obtaining Data from Multiple Tables
EMP
EMPNO -----7839 7698 ... 7934 ENAME ----KING BLAKE ... DEPTNO ... -----... 10 ... 30 10
DEPT
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON
MILLER ...
EMPNO DEPTNO LOC ----- ------- -------7839 10 NEW YORK 7698 30 CHICAGO 7782 10 NEW YORK 7566 20 DALLAS 7654 30 CHICAGO 7499 30 CHICAGO ... 14 rows selected.
What Is a Join?
Use a join to query data from more than one table.
SELECT FROM WHERE table1.column, table2.column table1, table2 table1.column1 = table2.column2;
Write the join condition in the WHERE clause. Prefix the column name with the table name when the same column name appears in more than one table.
Cartesian Product
A Cartesian product is formed when:
A join condition is omitted A join condition is invalid All rows in the first table are joined to all rows in the second table
To avoid a Cartesian product, always include a valid join condition in a WHERE clause.
Generating a Cartesian Product
EMP (14 rows) EMPNO -----7839 7698 ... 7934 ENAME ----KING BLAKE ... DEPTNO ... -----... 10 ... 30 10
DEPT (4 rows)
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON
MILLER ...
Cartesian product: 14*4=56 rows
ENAME DNAME --------------KING ACCOUNTING BLAKE ACCOUNTING ... KING RESEARCH BLAKE RESEARCH ... 56 rows selected.
What Is an Equijoin?
EMP
EMPNO ENAME DEPTNO ------ ------- ------7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20 ... 14 rows selected.
DEPT
DEPTNO ------10 30 10 20 30 30 30 30 30 20 20 ... 14 rows DNAME ---------ACCOUNTING SALES ACCOUNTING RESEARCH SALES SALES SALES SALES SALES RESEARCH RESEARCH selected. LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO DALLAS DALLAS
Primary key
Foreign key
Retrieving Records with Equijoins
SQL> SELECT 2 3 FROM 4 WHERE
emp.empno, emp.ename, emp.deptno, dept.deptno, dept.loc emp, dept emp.deptno=dept.deptno;
EMPNO ENAME DEPTNO DEPTNO LOC ----- ------ ------ ------ --------7839 KING 10 10 NEW YORK 7698 BLAKE 30 30 CHICAGO 7782 CLARK 10 10 NEW YORK 7566 JONES 20 20 DALLAS ... 14 rows selected.
Qualifying Ambiguous Column Names
Use table prefixes to qualify column names that are in multiple tables. Improve performance by using table prefixes. Distinguish columns that have identical names but reside in different tables by using column aliases.
Additional Search Conditions Using the AND Operator
EMP
EMPNO ENAME DEPTNO ------ ------- ------7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20 ... 14 rows selected.
DEPT
DEPTNO DNAME ------ --------10 ACCOUNTING 30 SALES 10 ACCOUNTING 20 RESEARCH 30 SALES 30 SALES 30 SALES 30 SALES 30 SALES 20 RESEARCH 20 RESEARCH ... 14 rows selected. LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO DALLAS DALLAS
Using Table Aliases
Simplify queries by using table aliases.
SQL> SELECT emp.empno, emp.ename, emp.deptno, 2 dept.deptno, dept.loc 3 FROM emp, dept 4 WHERE emp.deptno=dept.deptno;
SQL> SELECT e.empno, e.ename, e.deptno, 2 d.deptno, d.loc 3 FROM emp e, dept d 4 WHERE e.deptno=d.deptno;
Joining More Than Two Tables
CUSTOMER
NAME CUSTID ---------------JOCKSPORTS 100 TKB SPORT SHOP 101 VOLLYRITE 102 JUST TENNIS 103 K+T SPORTS 105 SHAPE UP 106 WOMENS SPORTS 107 ... ... 9 rows selected.
ORD
CUSTID ORDID ------- ------101 610 102 611 104 612 106 601 102 602 ITEM 106 604 ORDID ITEMID 106 605 ------ ------... 610 3 21 rows selected. 611 1 612 1 601 1 602 1 ... 64 rows selected.
Outer Joins
EMP
ENAME ----KING BLAKE CLARK JONES ... DEPTNO -----10 30 10 20
DEPT
DEPTNO -----10 30 10 20 ... 40 DNAME ---------ACCOUNTING SALES ACCOUNTING RESEARCH OPERATIONS
No employee in the OPERATIONS department
Join Types
INNER JOIN: This will only return rows when there is at least one row in both tables that match the join condition. SELECT * FROM emp INNER JOIN dept ON emp.deptno = dept.deptno
LEFT OUTER JOIN (or LEFT JOIN): This will return rows that have data in the left table (left of the JOIN keyword), even if there's no matching rows in the right table. SELECT * FROM emp LEFT JOIN dept ON emp.deptno = dept.deptno
56
Join Types
RIGHT OUTER JOIN (or RIGHT JOIN): This will return rows that have data in the right table (right of the JOIN keyword), even if there's no matching rows in the left table.
SELECT * FROM emp RIGHT JOIN dept ON emp.deptno = dept.deptno FULL OUTER JOIN (or FULL JOIN): This will return all rows, as long as there's matching data in one of the tables. SELECT * FROM emp FULL JOIN dept ON emp.deptno = dept.deptno
57
SQL Functions
SQL has a number of functions to assist you in your database programming. Functions are a self contained script/program built for a specific purpose. Generally, the value returned by a function will depend on the context in which it is being used. Often, a SQL function will be used within a query and this is what provides it with it's context.
58
SQL Count
A commonly used aggregate function in SQL is COUNT. COUNT returns the number of rows that match the given criteria.
COUNT(*)
If we only want to see how many records are in a table we could use COUNT(*). COUNT(*) returns everything - including null values and duplicates. SQL statement SELECT COUNT(*) FROM student
59
SQL Sum
Sum(column name)
To sum the total salary Select sum(sal) from emp; Displays the total salary of all employees
SELECT average(sal) FROM student
60
SQL AVG ( Average)
Avg(column name)
To find the average of salary
Select avg(sal) from emp;
Displays the average salary of all employees SELECT average(sal) FROM student
61
The GROUP BY Clause You can use the GROUP BY clause to divide the rows in a table into groups. You can then use the group functions to return summary information for each group. In the syntax:
SELECT column, group_function(column) FROM table [WHERE condition] [GROUP BY group_by_expression] [ORDER by column];
group_by_expression:-specifies columns whose values determine the basis for grouping rows. SELECT deptno, AVG(sal) FROM emp GROUP BY deptno;
62
The HAVING Clause
You use the HAVING clause to specify which groups are to be displayed. Therefore, you further restrict the groups on the basis of aggregate information. In the syntax: SELECT column, group_function FROM table [WHERE condition] [GROUP BY group_by_expression] [HAVING group_condition] [ORDER by column];
SELECT deptno, AVG(sal) FROM emp GROUP BY deptno HAVING MAX(sal) > 2900;
63
SQL Create Table
You create a table using the CREATE TABLE command.
SQL syntax CREATE TABLE table_name (column_name_1 datatype, column_name_2 datatype, ... )
Example
CREATE TABLE student (Rollno int, Name Varchar(255), LastName Varchar(255), Address Char(10) )
64
SQL Alter Table
In an earlier lesson, we created a table with the CREATE TABLE command. In this lesson, we will modify the table using the ALTER TABLE command.
Add a Column SQL syntax
ALTER TABLE table_name ADD column_name datatype
Example SQL Statement
ALTER TABLE student ADD age int
65
Change the Datatype
SQL syntax
ALTER TABLE table_name ALTER COLUMN column_name datatype
Example SQL Statement ALTER TABLE student ALTER COLUMN age numeric
Drop a Column
'Dropping' a column means removing or deleting that column.
SQL syntax
ALTER TABLE table_name DROP COLUMN column_name
Example SQL Statement ALTER TABLE student DROP COLUMN age
66
Drop the Table
SQL syntax Drop Table tablename;
Example SQL Statement
Drop Table student;
67
Aggregating Data Using Group Functions
What Are Group Functions?
Group functions operate on sets of rows to give one result per group.
EMP
DEPTNO SAL --------- --------10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250
maximum salary in the EMP table
MAX(SAL) --------5000
Using AVG and SUM Functions
You can use AVG and SUM for numeric data.
SQL> SELECT 2 3 FROM 4 WHERE AVG(sal), MAX(sal), MIN(sal), SUM(sal) emp job LIKE 'SALES%';
AVG(SAL) MAX(SAL) MIN(SAL) SUM(SAL) -------- --------- --------- --------1400 1600 1250 5600
Using MIN and MAX Functions
SQL> SELECT 2 FROM MIN(sal), MAX(sal) emp;
Using the COUNT Function
COUNT(*) returns the number of rows in a table.
SQL> SELECT 2 FROM 3 WHERE COUNT(*) --------6 COUNT(*) emp deptno = 30;
Using the COUNT Function
COUNT(expr) returns the number of nonnull rows.
SQL> SELECT 2 FROM 3 WHERE COUNT(COMM) ----------4 COUNT(comm) emp deptno = 30;
Creating Groups of Data
EMP
DEPTNO SAL --------- --------10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250
2916.6667
average DEPTNO AVG(SAL) salary ------- --------in EMP 2175 10 2916.6667 table 20 2175 for each department 30 1566.6667
1566.6667
Creating Groups of Data: GROUP BY Clause
SELECT FROM [WHERE [GROUP BY [ORDER BY
column, group_function(column) table condition] group_by_expression] column];
Divide rows in a table into smaller groups by using the GROUP BY clause.
Using the GROUP BY Clause
All columns in the SELECT list that are not in group functions must be in the GROUP BY clause.
SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 GROUP BY deptno;
DEPTNO AVG(SAL) --------- --------10 2916.6667 20 2175 30 1566.6667
Using the GROUP BY Clause
The GROUP BY column does not have to be in the SELECT list.
SQL> SELECT AVG(sal) 2 FROM emp 3 GROUP BY deptno;
AVG(SAL) --------2916.6667 2175 1566.6667
Grouping by More Than One Column
EMP
DEPTNO --------10 10 10 20 20 20 20 20 30 30 30 30 30 30 JOB SAL --------- --------MANAGER 2450 PRESIDENT 5000 CLERK 1300 CLERK 800 CLERK 1100 ANALYST 3000 ANALYST 3000 MANAGER 2975 SALESMAN 1600 MANAGER 2850 SALESMAN 1250 CLERK 950 SALESMAN 1500 SALESMAN 1250
sum salaries in the EMP table for each job, grouped by department
DEPTNO -------10 10 10 20 20 20 30 30 30
JOB SUM(SAL) --------- --------CLERK 1300 MANAGER 2450 PRESIDENT 5000 ANALYST 6000 CLERK 1900 MANAGER 2975 CLERK 950 MANAGER 2850 SALESMAN 5600
Using the GROUP BY Clause on Multiple Columns
SQL> SELECT deptno, job, sum(sal) 2 FROM emp 3 GROUP BY deptno, job;
DEPTNO JOB SUM(SAL) --------- --------- --------10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 ANALYST 6000 20 CLERK 1900 ... 9 rows selected.
Illegal Queries Using Group Functions
Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause.
SQL> SELECT 2 FROM deptno, COUNT(ename) emp;
SELECT deptno, COUNT(ename) * ERROR at line 1: ORA-00937: not a single-group group function
Illegal Queries Using Group Functions
You cannot use the WHERE clause to restrict groups. You use the HAVING clause to restrict groups.
SQL> 2 3 4 SELECT FROM WHERE GROUP BY deptno, AVG(sal) emp AVG(sal) > 2000 deptno;
WHERE AVG(sal) > 2000 * ERROR at line 3: ORA-00934: group function is not allowed here
Excluding Group Results
EMP
DEPTNO SAL --------- --------10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250
5000 maximum salary per department greater than $2900
3000
DEPTNO MAX(SAL) --------- --------10 5000 20 3000
2850
Excluding Group Results: HAVING Clause
Use the HAVING clause to restrict groups
Rows are grouped. The group function is applied. Groups matching the HAVING clause are displayed.
SELECT FROM [WHERE [GROUP BY [HAVING [ORDER BY
column, group_function table condition] group_by_expression] group_condition] column];
Using the HAVING Clause
SQL> 2 3 4 SELECT FROM GROUP BY HAVING deptno, max(sal) emp deptno max(sal)>2900;
DEPTNO MAX(SAL) --------- --------10 5000 20 3000
Using the HAVING Clause
SQL> 2 3 4 5 6 SELECT FROM WHERE GROUP BY HAVING ORDER BY job, SUM(sal) PAYROLL emp job NOT LIKE 'SALES%' job SUM(sal)>5000 SUM(sal);
JOB PAYROLL --------- --------ANALYST 6000 MANAGER 8275
Nesting Group Functions
Display the maximum average salary.
SQL> SELECT max(avg(sal)) 2 FROM emp 3 GROUP BY deptno;
MAX(AVG(SAL)) ------------2916.6667
Subqueries
Using a Subquery to Solve a Problem
Who has a salary greater than Joness?
Main Query
Which employees have a salary greater than Joness salary?
Subquery
What is Joness salary?
Subqueries
SELECT FROM WHERE select_list table expr operator (SELECT FROM
select_list table);
The subquery (inner query) executes once before the main query. The result of the subquery is used by the main query (outer query).
Using a Subquery
SQL> SELECT ename 2 FROM emp 2975 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE empno=7566); ENAME ---------KING FORD SCOTT
Guidelines for Using Subqueries
Enclose subqueries in parentheses. Place subqueries on the right side of the comparison operator. Do not add an ORDER BY clause to a subquery. Use single-row operators with single-row subqueries. Use multiple-row operators with multiple-row subqueries.
Types of Subqueries
Single-row subquery
Main query returns
Subquery
CLERK
Multiple-row subquery
Main query returns Subquery
CLERK MANAGER
Multiple-column subquery
Main query returns Subquery
CLERK 7900 MANAGER 7698
Single-Row Subqueries
Return only one row Use single-row comparison operators
Operator = > >= < <= <> Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to
Executing Single-Row Subqueries
SQL> 2 3 4 5 6 7 8 9 10 SELECT FROM WHERE ename, job emp job = (SELECT FROM WHERE sal > (SELECT FROM WHERE
CLERK
job emp empno = 7369)
1100
AND
sal emp empno = 7876);
ENAME JOB ---------- --------MILLER CLERK
Using Group Functions in a Subquery
SQL> SELECT 2 FROM 3 WHERE 4 5 ename, job, sal emp sal = (SELECT FROM
800
MIN(sal) emp);
ENAME JOB SAL ---------- --------- --------SMITH CLERK 800
What Is Wrong with This Statement?
SQL> SELECT empno, ename 2 FROM emp 3 WHERE sal = 4 (SELECT 5 FROM 6 GROUP BY
MIN(sal) emp deptno);
ERROR: ORA-01427: single-row subquery returns more than one row no rows selected
Multiple-Row Subqueries
Return more than one row Use multiple-row comparison operators
Operator IN Meaning Equal to any member in the list
ANY
Compare value to each value returned by the subquery
Compare value to every value returned by the subquery
ALL
Using ANY Operator in Multiple-Row Subqueries
SQL> 2 3 4 5 6 7 SELECT FROM WHERE empno, ename, job 1300 1100 emp 800 sal < ANY 950 (SELECT sal FROM emp WHERE job = 'CLERK') job <> 'CLERK';
JOB --------SALESMAN SALESMAN
AND
EMPNO --------7654 7521
ENAME ---------MARTIN WARD
Using ALL Operator in Multiple-Row Subqueries
SQL> SELECT 2 FROM 3 WHERE 4 5 6
EMPNO --------7839 7566 7902 7788
empno, ename, job 2175 emp 2916.6667 sal > ALL (SELECT FROM GROUP BY
JOB --------PRESIDENT MANAGER ANALYST ANALYST
1566.6667
avg(sal) emp deptno);
ENAME ---------KING JONES FORD SCOTT
Using TOP and PERCENT
The TOP option is used for limiting the output of a query result set. TOP can either specify the number of rows to return, or the percentage of rows to return. The ORDER BY clause can be used successfully with the TOP option. SELECT TOP 10 * FROM employees SELECT TOP 20 PERCENT * FROM employees SELECT TOP 10 * FROM employees ORDER BY Salary DESC SELECT TOP 1 WITH TIES * FROM EMP ORDER BY SAL
101
INTO CLAUSE
INTO clause creates a new table and inserts rows and columns listed in the SELECT statement into it. INTO clause also inserts existing rows into a new table.
SELECT EMPNO,ENAME,JOB INTO EMP20 FROM EMP WHERE DEPTNO =10;
102
[ ] (Wildcard - Character(s) to Match)
Matches any single character within the specified range or set that is specified between the brackets.
SELECT * FROM EMP WHERE SAL LIKE '[0-9][0-9][0-9]'
103
[^] (Wildcard - Character(s) Not to Match)
Matches any single character that is not within the range or set specified between the square brackets.
SELECT * FROM EMP WHERE ENAME LIKE 'A[^L]%'
104
GROUP BY ALL
If you use ALL, the query results include all groups produced by the GROUP BY clause, even if some of the groups have no rows that meet the search conditions. Without ALL, a SELECT statement that includes GROUP BY does not show groups for which no rows qualify.
SELECT AVG(SAL),DEPTNO FROM EMP WHERE DEPTNO IN(10,20) GROUP BY ALL DEPTNO
105
GROUP BY CUBE CUBE is an aggregate operator that produces a super aggregate row. In addition to the usual rows provided by the GROUP BY, it also provides the summary of the rows that the GROUP BY clause generates. The Summary row is displayed for every possible combination of groups in the result set. The Summary row displays NULL in the result set
SELECT AVG(SAL),DEPTNO,JOB FROM EMP GROUP BY DEPTNO ,JOB WITH CUBE
106
GROUP BY ROLLUP ROLLUP:- In addition to the rows generated by the group by clause , it also introduces summary rows into the result set. It arranges the groups from the lowest to the highest.
SELECT AVG(SAL),DEPTNO,JOB FROM EMP GROUP BY DEPTNO,JOB WITH ROLLUP
107
SQL Insert
The SQL INSERT command allows you to insert a record into a table in your database.
INSERT INTO Student (Rollno, name, age) VALUES ( 1, 'Benny', 12)
108
SQL Update
The SQL UPDATE statement allows you to update an existing record in the database. The UPDATE command uses a WHERE clause. If you don't use a WHERE clause, all rows will be updated.
UPDATE student SET age = 12 WHERE rollno = 1
109
SQL Delete
The SQL DELETE statement allows you to delete a record from the database. The DELETE command uses a WHERE clause. If you don't use a WHERE clause, all rows in the table will be deleted.
DELETE FROM Individual WHERE Rollno = 1
110
Exact-number data types that use integer data.
Data Type
Description Integer (whole number) data from 2^63 (9,223,372,036,854,775,808) through 2^631 (9,223,372,036,854,775,807). Storage size is 8 bytes.
bigint
integer
Integer (whole number) data from 2^31 (2,147,483,648) through 2^311 (2,147,483,647). Storage size is 4 bytes.
smallint tinyint
Integer data from 32,768 to 32,767. Storage size is 2 bytes. Integer data from 0 to 255. Storage size is 1 byte. Integer data with a value of either 1 or 0.
bit
Storage size is 1 bit.
111
Fixed-precision and scale-numeric data from 10^38+1 through 10^381. The p variable specifies precision and can vary between 1 and 38. The s variable numeric (p, s) specifies scale and can vary between 0 and p. Storage size is 19 bytes. Monetary data values from (2^63/10000) (922,337,203,685,477.5808) through 2^631 (922,337,203,685,477.5807 Storage size is 8 bytes. Floating point number data from 1.79E -308 through 1.79E +308
money
float
Storage size is 8 bytes. Floating precision number data from 3.40E+38 through 3.40E+38. real
Storage size is 4 bytes.
112
Date and time data from January 1, 1753, to December 31, 9999,
datetime
Values for datetime earlier than January 1, 1753, are not permitted.
national character(n) Synonym: nchar(n)
Fixed-length Unicode data with a maximum length of 4000 characters. Default length = 1. Storage size, in bytes, is two times the number of characters entered.
Variable-length Unicode data with a length of 1 to 4000 characters. Default length = 1. Storage size, in bytes, is two times the number of characters Synonym: nvarchar(n) entered.
national character varying(n)
113
ntext
Variable-length Unicode data with a maximum length of (2^302)/2 (536,870,911) characters. Storage size, in bytes, is two times the number of characters entered. Fixed-length binary data with a maximum length of 8000 bytes. Default length = 1. Storage size is fixed, which is the length in bytes declared in the type. Variable-length binary data with a maximum length of 8000 bytes. Default length = 1. Storage size varies. It is the length of the value in bytes. Variable-length binary data with a maximum length of 2^301 (1,073,741,823) bytes. Storage is the length of the value in bytes.
binary(n)
varbinary(n)
image
unique identifier A globally unique identifier (GUID). Storage size is 16 bytes.
114
binary(n)
Fixed-length binary data with a maximum length of 8000 bytes. Default length = 1. Storage size is fixed, which is the length in bytes declared in the type. Variable-length binary data with a maximum length of 8000 bytes. Default length = 1. Storage size varies. It is the length of the value in bytes. Variable-length binary data with a maximum length of 2^301 (1,073,741,823) bytes. Storage is the length of the value in bytes.
varbinary(n)
image
uniqueidentifier A globally unique identifier (GUID). Storage size is 16 bytes. This is a property of a data column, not a distinct data type. Only data columns of the integer data types can be used for identity columns. A table can have only one identity column. A seed and increment can be specified and the column IDENTITY [(s, i)] cannot be updated. s (seed) = starting value i (increment) = increment value This is a property of a data column, not a distinct data type. It is a column in a table that is ROWGUIDCOL defined by using the unique identifier data type. A table can have only one ROWGUIDCOL column. 115