SQL Server
SQL Server
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.
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.
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
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
11
12
Arithmetic Expressions
Create expressions on NUMBER data by using arithmetic operators.
Operator + -
*
/
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
SELECT
ename
job
FROM emp;
Employees ------------------KINGPRESIDENT BLAKEMANAGER CLARKMANAGER JONESMANAGER MARTINSALESMAN ALLENSALESMAN ... 14 rows selected.
SELECT
DISTINCT deptno
FROM
emp;
DEPTNO --------10 20 30
SELECT International
SELECT 100
SELECT ename as Name, sal as Salary , 12*(sal+100) as Annual Salary FROM emp;
SELECT ename as Name, sal as Salary , 12*(sal+100) as Annual Salary FROM emp;
Comparison Operators
Operator
= > >= < <= <>
Meaning
Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to
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.
ENAME SAL MGR ---------- --------- --------FORD 3000 7566 SMITH 800 7902 SCOTT 3000 7566 ADAMS 1100 7788
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
LIKE '_A%';
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
Rules of Precedence
Order Evaluated 1 2 3 4
Rules of Precedence
SELECT ename, job, sal FROM emp WHERE job='SALESMAN' OR job='PRESIDENT' AND sal>1500;
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;
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.
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.
DEPT (4 rows)
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON
MILLER ...
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
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.
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.
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
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;
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
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
60
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
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
Example
CREATE TABLE student (Rollno int, Name Varchar(255), LastName Varchar(255), Address Char(10) )
64
65
Example SQL Statement ALTER TABLE student ALTER COLUMN age numeric
Drop a Column
'Dropping' a column means removing or deleting that column.
SQL syntax
67
MAX(SAL) --------5000
AVG(SAL) MAX(SAL) MIN(SAL) SUM(SAL) -------- --------- --------- --------1400 1600 1250 5600
2916.6667
average DEPTNO AVG(SAL) salary ------- --------in EMP 2175 10 2916.6667 table 20 2175 for each department 30 1566.6667
1566.6667
Divide rows in a table into smaller groups by 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;
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
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.
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
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
3000
2850
MAX(AVG(SAL)) ------------2916.6667
Subqueries
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
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
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
CLERK
AND
MIN(sal) emp);
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
ALL
AND
empno, ename, job 2175 emp 2916.6667 sal > ALL (SELECT FROM GROUP BY
JOB --------PRESIDENT MANAGER ANALYST ANALYST
1566.6667
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.
102
Matches any single character within the specified range or set that is specified between the brackets.
103
Matches any single character that is not within the range or set specified between the square brackets.
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
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.
107
SQL Insert
The SQL INSERT command allows you to insert a record into a table in your database.
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.
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.
110
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
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.
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.
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
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