SQL Itp2
SQL Itp2
SQL, the Structured Query Language, is a mature, powerful, and versatile relational query language.
SQL features include: SQL can execute queries against a database SQL can retrieve data from a database SQL can insert new records in a database SQL can delete records from a database SQL can update records in a database SQL is easy to learn Arithmetic operators Creating, replacing, altering, and dropping objects
Understanding Tables A table is composed of columns and rows, and their intersections are fields. (such as Excel spreadsheet), these two terms are visually represented in the same manner, and the fields within a table are equivalent to the cells within a spreadsheet. From a general perspective, columns within a table describe the name and type of data that will be found (and can be entered) by row for that column's fields.
Rows within a table represent records composed of fields that are described from left to right by their corresponding column's name and type. Each field in a row is implicitly correlated with each other field in that row. In this sense, columns can be thought of as descriptors for the discrete, sequential elements of a row, and each row can be thought of as a stored record matching that description.
DEPT TABLE: DESC DEPT DEPTNO DNAME -------------------10 ACCOUNTING 20 RESEARCH 30 SALES 40 OPERATIONS LOC --------NEW YORK DALLAS CHICAGO BOSTON
ANSI-supported datatypes:
Data types
Char data types char(size) - 255 Varchar(size)Varchar2(size) Long(n) Long Raw Raw Binary integer Number data taypes Number Number(p) Number(p.s) Int Integer(p) Dec(p,s) Decimal(p,s) Smallint Real double
explanation
number
Number(p,s) integer
Max P 38 digits
Max P 38 digits Max P 38 digits
If the scale is negative, the actual data is rounded to the specified number of places to the left of the decimal point
Data types
LONG LONG is like varchar2 except that maximum length is 2Gb. We can insert 2Gb into LONG /LONG RAW column but can retrieve up to 32760 bytes in LONG /LONG RAW variable. Can stores text, array, even short doc.
can not use in function call, and certain SQL clauses like
WHERE,GROUP BY, CONNECT BY.
LONG
You can reference LONG columns in SQL statements in these places:
SELECT lists SET clauses of UPDATE statements VALUES clauses of INSERT statements
LONG
The use of LONG values is subject to some restrictions:
A table cannot contain more than one LONG column. You cannot create an object type with a LONG attribute. LONG columns cannot appear in integrity constraints (except for NULL and NOT NULL constraints). LONG columns cannot be indexed. A stored function cannot return a LONG value. Within a single SQL statement, all LONG columns, updated tables, and locked tables must be located on the same database.
LONG
LONG columns cannot appear in certain parts of SQL statements WHERE clauses, GROUP BY clauses, ORDER BY clauses, or CONNECT BY clauses or with the DISTINCT operator in SELECT statements The UNIQUE operator of a SELECT statement The column list of a CREATE CLUSTER statement The CLUSTER clause of a CREATE MATERIALIZED VIEW statement SQL functions (such as SUBSTR or INSTR) Expressions or conditions SELECT lists of queries containing GROUP BY clauses SELECT lists of subqueries or queries combined by the UNION, INTERSECT, or MINUS set operators SELECT lists of CREATE TABLE ... AS SELECT statements SELECT lists in subqueries in INSERT statements
LONG
Triggers can use the LONG datatype in the following manner:
A SQL statement within a trigger can insert data into a LONG column. If data from a LONG column can be converted to a constrained datatype (such as CHAR and VARCHAR2), a LONG column can be referenced in a SQL statement within a trigger. Variables in triggers cannot be declared using the LONG datatype. :NEW and :OLD cannot be used with LONG columns.
RAW : used to store binary data or byte string. Eg. Sequence of graphics picture/image. PLSQL/SQL does not interprete it. Max length up to 32767. RAW (Max_len) RAW to LONG RAW is possible. But can retrieve up to 32767 bytes only.
Data types
ROWID and UROWID Each table have pseudorandom called as ROWID stores values called rowid. Hexadecimal string representing the unique address of a row in its table Represents Address of each row in a table. Physical rowid -> ROWID. Logical rowid-> User defined index on table UROWID Hexadecimal string representing the logical address of a row of an index-organized table. can stores physical, logical, foreign (non oracle ) rowid.
Date types
Date : fixed length date/time Default date is first day of month Default time is midnight. SYSDATE returns current date and time of the system. The default date format is specified by the initialization parameter NLS_DATE_FORMAT and is a string such as 'DD-MON-YY'.
Date type
To specify a date value that is not in the default format, you must convert a character or numeric value to a date value with the TO_DATE function. The date format model for '11-NOV-1999' is 'DD-MONYYYY'. TO_DATE converts char of CHAR or VARCHAR2 datatype to a value of DATE datatype
internally), and the BFILE (stored externally), can store large and
unstructured data such as text, image, video, and spatial data up to 4 gigabytes in size.
The LOB locator is stored in the table column, either with or without the actual LOB value. BLOB, NCLOB, and CLOB values can be stored in separate tablespaces. BFILE data is stored in an external file on the server.
When you access a LOB column, the locator is returned. A LOB can be up to 4 gigabytes in size. BFILE maximum size is operating system dependent, but cannot exceed 4 gigabytes. LOBs permit efficient, random, piece-wise access to and manipulation of data. - You can define more than one LOB column in a table.
With the exception of NCLOB, you can define one or more LOB attributes in an object. or LOB attribute and thereby also delete the LOB value. Note that for BFILEs, the actual operating system file is not deleted. You can declare LOB bind variables. You can select LOB columns and LOB attributes. You can insert a new row or update an existing row that contains one or more LOB columns and/or an object with one or more LOB attributes. (You can set the internal LOB value to NULL, empty, or replace the entire LOB with data. You can set the BFILE to NULL or make it point to a different file.) You can update a LOB row/column intersection or a LOB attribute with another LOB row/column intersection or LOB attribute.
OPERATORS In Oracle
Arithmeti c + * / Relatio nal = > < >= <= Or != LIKE Logical Set Operators AND OR union,inters NOT ect,minus miscellaneo us IN BETWEEN NOT IN NOT LIKE || (concatenati on)
Select Name From student Where name LIKE C% or Where name LIKE %K or Where name LIKE K_ _ _ _
DDL
CREATE DROP ALTER TRUNCATE
);
Data Constraints
Constraints Primary key Foreign Key Null Not Null Unique Check Default Not user defined User defined /table level
CREATE TABLE Student ( Roll_nonumber(5) Primary Key Enroll_no number(6) Unique Not Null, Name Varchar2(10), Age number(3) Default 21, Category Varchar2(5) Check (Category in (sc, st,obc,gen)), Address Varchar2(10) );
Category
CONSTRAINT pk_rno PRIMARY KEY ( Roll_no), CONSTRAINT nn_Name NOT NULL(Name), CONSTAINT ch_category Check (Category in (sc, st,obc,gen))
);
USER_Constraint Table
The information about all the constraints is stored in table called as USER_CONSTAINTS. Structure is (Onwer, constraint_name, table_name, constraint_type, search_condition, R_onwer, R_constaint_name)
Alter table
Can be use dto Add column, integrity constraints, Modify exiting columns length, change default, decrease length, change data type Drop integrity constraints. Drop column name or rename it( only in higher version)
ALTER
ADD ALTER TABLE TABLE NAME ADD ( COLUMN1 data type, COLUMN n data type) MODIFY ALTER TABLE TABLE NAME MODIFY (COLUMN1 data
type, COLUMN n data type)
ALTER
SQL>Alter table emp add primary key(empno); SQL>Alter table student add (ph_no number(10));
Alter table
ADD foreign key constraints
Alter table emp add ( foreign key (column name) references master table name on delete cascade);
DML
INSER UPDATE DELETE
Insert a record
INSERT INTO table _Name (column1, column2.. Columnn) Values (value1, value2valuen)
Delete command
DELETE FROM table _name WHER (condition); Delete all rows DELETE * FROM student; Delete specific rows DELETE FROM Students WHERE name = Smith;
Create cust( ust_id integer, date_join date); Insert into cust values (200, to_date(12/11/1990,dd/mm/yyyy))
UPDATE TABLE
UPDATE table name SET columnname = newvalue,[ ..] WHERE columnname operator value ;
Save table
Commit; Rollback;
SQL lets you define the result,whereas, other languages make you define the process.
DEPTNO --------10 20 30 40
WHERE Clause
The WHERE Clause is used to specify the criteria. Example 1: List all employees who belong to department number 20 SELECT empno,ename,deptno FROM Emp WHERE deptno=20; EMPNO --------7369 7566 7788 7876 7902 ENAME ---------SMITH JONES SCOTT ADAMS FORD DEPTNO --------20 20 20 20 20
Conditional Operator
Example 1: List the employee name whose employee number is 7900 SELECT ename FROM Emp WHERE empno = 7900;
ENAME ---------JAMES
Conditional Operators
Example 2 : List the employees whose hiredate is before 28-SEP-81 SELECT empno, ename, hiredate, deptno FROM Emp WHERE Hiredate < = 28- SEP-81;
EMPNO ENAME --------7369 7499 7521 7566 7654 7698 7782 7844 ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK TURNER HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 08-SEP-81 DEPTNO --------20 30 30 20 30 30 10 30
SELECT
SELECT * from emp; SELECT ename,empno from emp; SELECT ename,deptno from emp WHERE deptno=10; SELECT ename,sal,job from emp WHERE job=MANAGER; SELECT DISTINCT job from emp; SELECT empno,ename from emp where comm is NULL; *NULL is absence of information.
Exercise
1. 2. 3.
4. 5.
6. 7.
IN and BETWEEN
Select ename,deptno from emp where deptno IN ( 10,20); Select ename,job,hiredate,sal from emp where job IN(CLERK,ANALYST); Select ename,sal from emp where sal BETWEEN 1200 AND 2500; Select ename,hireadate from emp where hiredate BETWEEN 01-jan81 AND 31-dec-82;
Like Operator
Select ename from emp where ename LIKE S%; Select ename from emp where ename LIKE ____; Select ename from emp where ename LIKE %A%;
Order By
Select empno,ename,sal from emp ORDER BY ename; Select ename from emp ORDER BY ename DESC; Select job,ename from emp ORDER BY job,ename; Select job,ename from emp ORDER BY job, ename DESC; Select ename,job from emp ORDER BY 1 desc;
Exercise
Write SQL queries for the following:
1. List the name job and salary of all the employees in department 20 who earn more than 2000/-. 2. Find all employees whose designation is either manager or president. 3. Find all managers who are not in department 30. 4. Find all the details of all the managers and clerks in department 10. 5. Find the details of the managers in department 10 and all clerks in department 20 . 6. Find the details of all employees who are neither managers nor clerks but whose salary is more than or equal to 2000/-.
Exercise
1. Find all the employees whose names begin with M. 2. Find all the employees whose names ends with M. 3. Find all the employees whose names contain the letter M in any case. 4. Find all the employees whose names are 5 characters long. 5. Find the employees who have the letter R as the third character of their names. 6. Find all the employees who were hired in the month of February (of any year).
Aggregate Functions
SUM AVG COUNT MIN MAX
Exercise
1. Show the first four characters of the names of all the employees. 2. Display the last three characters of the names of all the employees. 3. Show all the names of all the employees and the date, which they completed 22 years of service.(22.2 ,22.8 should be considered as 22 only) 4. For each employee, display the no. of days passed since the employee joined the company. 5. For each employee, display the no. of months passed since the employee joined the company. 6. Display the names of the employees, based on their tenure with the oldest employee coming first.
Exercise
Write SQL queries for the following: 1. Count the number of employees in department number 20. 2. Count the number of employees who are not getting any commission. 3. Display the min and max salary of department 10. 4. Count the number of managers in emp table. 5. Count the number of employees hired in the year 1981.
Exercise
Write SQL queries for the following 1. Display the count of employees in each department of EMP table. 2. Display the total amount of salary given to each department; 3. Display the minimum and maximum amount of salary given to all clerks in each department. 4. Display the minimum salary given to all managers in each department where minimum salary is less than 2900. 5. Retrieve min and max salary of clerks for each department having more than three clerks.
Joins
EQUI NON-EQUI OUTER
SELF
JOINS
If we require data from more than one table in the database, a join is used.
The columns compared by = operator are called join columns and the join operation is called an EQUI JOIN.
SELF JOIN
It is possible using table labels (aliases) to join a table to itself , as if they were two separate tables. This allows rows in a table to be joined to rows in the same table.
OUTER JOIN
If a row does not satisfy a join condition, then the row will not appear in the query result. The missing row(s) can be returned if an outer join operator is used in the join condition. The operator is plus sign enclosed in parentheses (+), and is placed on the side of the join(table) which is deficient in information.
Exercise
1.
2.
3.
4. 5. 6.
7. 8.
Exercise
Display employee name of all those employees whose designation is same as that of BLAKE. Display employee name of all those employees who are getting salary more than SMITH. Display employee name, job, deptno of all those employees who are working in the same department as that of SCOTT and ename starts with S. Display all the employee and department details from both tables. Display the department name in which no employee is working.
SUBQUERIES
A sub-query is a form of an SQL statement that appears inside another SQL statement. It is also termed as nested query. The statement containing a sub-query is called a parent statement. The parent statement uses the rows returned by the sub-query.
SUBQUERIES
To display name & salary of employees who have the same job as the employee 7896. Method 1: SQL> Select job from emp where empno=7896; O/P : CLERK SQL> Select ename,sal from emp where job=CLERK; Method 2 (using subquery): SQL> Select ename, sal from emp where job = (Select job from emp where empno = 7896);
Inline Views E.g Select ename,sal from ( select * from emp order by sal desc) where rownum <6;
Multiple-column Subqueries E.g. Select ename,job from emp Where (deptno,sal) IN (select deptno,max(sal) from emp group by deptno);
Select * from Emp where sal >= ANY ( Select sal from emp where deptno=30) and deptno=10; ANY : the condition evaluates to true , if there exist at least one row selected by the subquery for which the comparision holds. Select * from Emp where sal >= ALL ( Select sal from emp where deptno=30) and deptno<>30; * Lists all employees who are not working in dept 30 and who earn more than all employees who work in dept 30.
Exercise
Display employee names of all those employees who are working in CHICAGO. Display employee names of all those employees who are working under BLAKE. Display employee names,sal of all those employees who are getting salary more than average salary of the complete emp table. Find the departments whose salary total is more than twice the average departmental salary total. Find the employees whose salaries are among the top 5 salaries.
CO-RELATED SUBQUERIES
A co-related query is a form of query used in Select, Update
query.
A co-related query is used to answer multi-part questions
Exercise
Display ename,sal,deptno of those employees who are getting salary more than the average salary of their own department. Find the employees who make more than twice the average salary in their department.
SET OPERATIONS
UNION
UNION ALL
INTERSECT MINUS Each of these operations combines the results of two select statements into a single result
Set Operators
Union select ename,job from emp1 union select ename,job from emp2;
select ename,job from emp1 union all ( to get all duplicates) select ename,job from emp2;
**datatypes should be same of both the tables
Intersect select ename,job from emp1 Intersect select ename,job from emp2; Minus
select ename,job from emp1
Minus
select ename,job from emp2
Format model
A format model is a character literal that describes the format of
can use
To specify the format for Oracle to use to return a value from the database To specify the format for a value you have specified for Oracle to store in the database
Format Models
Format of Return Values: Examples You can use a format model to specify the format for Oracle to use to return values from the database to you. SELECT ename employee, TO_CHAR(comm, '$9,990.99') commission FROM emp WHERE deptno = 30; EMPLOYEE ---------ALLEN WARD MARTIN BLAKE TURNER COMMISSION ---------$300.00 $500.00 $1,400.00 $0.00
value:
UPDATE emp SET hiredate = TO_DATE('1998 05 20','YYYY MM DD') WHERE ename = 'BLAKE';
CREATE SEQUENCE
Purpose Use the CREATE SEQUENCE statement to create a sequence, which is a database object from which multiple users may generate unique integers. You can use sequences to automatically generate primary key values. Once a sequence is created, you can access its values in SQL statements with the CURRVAL pseudocolumn (which returns the
Syntax
CREATE SEQUENCE
When a sequence number is generated, the sequence is incremented, independent of the transaction committing or rolling back. If two users concurrently increment the same sequence, the sequence numbers each user acquires may have gaps because sequence numbers are being generated by the other user. One user can never acquire the sequence
HIREDATE -----------------December 17, 1980 April 2, 1981 April 19, 1987 May 23, 1987 December 3, 1981 October 23, 1997
VIEW
Logical tables extracted from existing tables. Stored query or virtual table. Syntax create view emp_view as select e_no, emp_name from emp;
VIEW
Select * from view_emp; Desc view_name; Drop view view_name;
joins
Select S.sid, R.bid From Sailors S Natural Left outer join REserver R;
Date functions
select sysdate from dual; select add_months('12-jan-1995',4) from dual; select add_months('12-jan-1995',- 4) from dual; Select last_day (16-jan-2009) from dual; Select months_between (31-jan-2009, 28-feb2009) from dual;
Select next_day (01-jan-2009,Monday) from dual; select next_day('01-jan-2009', 'thursday') from dual;