Maa Corporate Training Center: Given by Mr. Loknadh
Maa Corporate Training Center: Given by Mr. Loknadh
1. SQL Fundamentals
SQL is the basic Language used for retrieve and manipulate data from database. SQL is non procedural Language , does not contains Programming constructs like Loops. SQL is 4th generation language , request-response kind of language. ANSI has standards for SQL , Oracle Supports there standards of SQL and extended its SQL to support it.
1. Data Manipulation Language (DML) Used to access, create, modify, or delete data in the existing structures of the database. Statements Include: INSERT,INSERT,UPDATE,DELETE,MERGE 2. Data Definition Language (DDL) Used to define, alter, or drop database objects and their privileges. Statements Include : CREATE, ALTER,DROP,RENAME,TRUNCATE, GRANT,REVOKE,AUDIT,NOAUDIT 3. Transaction Control Used to group a set of DML statements as a single transaction. COMMIT,ROLLBACK,SAVEPOINT,SET TRANSACTION 4. Session Control Used to control the properties of a user session. Includes : ALTER SESSION, SET ROLE 5. System Control Used to Manage the Properties of the Database ALTER SYSTEM
CHAR ( <size> )
: Default 1 , Maximum : 2KB -Fixed-Length, Alpha Numeric -Space-padded to fill maximum Length
VARACHAR2(<size>)
: Default : NA : Maximum: 4K : Variable-Length, Alpha Numeric : ONLY required amount of space is used for columns.
NUMBER((<p>. <s>)
: P 1-38 , S -84 127 : NUMBER(5,2) : 5-2 = 3 , Integer Part : 3 Decimal Part 2 It can store -999.99 to 999.99 Oracle rounds the values in the scale part is smaller than inserted number. Ex : NUMBER(4,2) : 12.124 Stored as 12.12 If Scale is Negative, rounded to left of the decimal.
Date :
7 Bytes Date stores Date and Time information Functions are applied to convert this data type. Occupies 7-Bytes Century:Year:Month:Day:Hour:Minute:Second Default Date Format : DD-MON-YY SYSDATE Function returns Current system date in Database server
SET Operators UNION UNION ALL INTERSECT MINUS Returns all rows from either queries; no duplicate rows Returns all rows from either query, including duplicates Returns distinct rows that are returned by both queries Returns distinct rows that are returned by the first query but not returned by the second.
Integer /Numbers : 50 , 43.21 Interval : Specify Period of Times in terms of Years or Months, Days to Seconds INTERVAL YEAR TO MONTH, INTERVAL DAY TO SECOND
Column Alias SQL> SELECT job_title AS Title, min_salary AS "Minimum Salary" FROM jobs SQL> /
DISTINCT /UNIQUE Uniqueness is verified against complete row. SQL> SELECT DISTINCT department_id FROM employees; SQL> SELECT DISTINCT department_id, job_id FROM employees; DUAL Table Dummy table available to users in the database. Contains one row and one column Used to Select SYSTEM Varibles and evaluate Expressions
Limiting Rows WHERE Clause is used to limit the number rows retrieved SQL>SELECT first_name ||''||last_name "Name", 2 department_id 3 FROM employees 4 WHERE department_id =90;
Comparison Operators =, !=, <,> ,=<,=> NULL Does not participate in Comparison
Examples : SQL> SELECT first_name, department_id 2 FROM employees 3* WHERE not (department_id >= 30); SQL> SELECT first_name, salary 2 FROM employees 3 WHERE last_name = 'Smith' 4* AND salary > 7500; SQL> SELECT first_name, last_name 2 FROM employees
SQL> SELECT first_name, last_name, department_id 2 FROM employees 3 WHERE department_id NOT IN 4* (10, 30, 40, 50, 60, 80, 90, 110, 100) SQL> /
BETWEEN : Used to test a range Inclusively of boundaries SQL> SELECT first_name, last_name, salary 2 FROM employees 3* WHERE salary BETWEEN 5000 AND 6000; SQL> SELECT first_name, last_name, salary 2 FROM employees 3* WHERE first_name BETWEEN A AND G;
EXISTS: The EXISTS operator is always followed by a sub query in parenthesis. EXISTS evaluates to TRUE if sub query returns at least one row SQL> SELECT last_name, first_name, department_id 2 FROM employees e 3 WHERE EXISTS (select 1 FROM departments d 4 WHERE d.department_id = e.department_id 5* AND d.department_name = 'Administration'); IS NULL and IS NOT NULL = and != operators does not work with NULL Values. IS NULL is used evaluate them. SQL> SELECT last_name, department_id 2 FROM employees 3 WHERE department_id IS NULL; LAST_NAME DEPARTMENT_ID
LIKE Used for Pattern Matching % Is used match any character and number of characters _ used to match any character but one character Escape : Using ESCAPE Keyword
SQL> SELECT first_name, last_name 2 FROM employees 3 WHERE first_name LIKE 'Su%' 4* AND last_name NOT LIKE 'S%'; SQL> SELECT job_id, job_title 2 FROM jobs 3 WHERE job_id like 'AC\_%' ESCAPE '\';
SQL> SELECT first_name, hire_date, salary, manager_id mid 2 FROM employees 3 WHERE department_id IN (110,100) 4* ORDER BY 4, 2, 3;
SQL> SELECT last_name, commission_pct 2 FROM employees 3 WHERE last_name LIKE 'R%' 4* ORDER BY commission_pct ASC, last_name DESC; SQL> SELECT last_name, commission_pct 2 FROM employees 3 WHERE last_name LIKE 'R%' 4* ORDER BY commission_pct ASC NULLS FIRST, last_name DESC; CASE Statement Case statement is used to derive IF-THEN-ELSE Logic SQL> SELECT country_name, region_id, 2 CASE region_id WHEN 1 THEN 'Europe' 3 WHEN 2 THEN 'America' 4 WHEN 3 THEN 'Asia' 5 ELSE 'Other' END Continent 6 FROM countries 7* WHERE country_name LIKE 'I%'; SQL> SELECT first_name, department_id, salary, 2 CASE WHEN salary < 6000 THEN 'Low'
2. SQL*Plus Overview
SQL*Plus is widely used tool by DBAs and Developers to access database. SQL*Plus is Installed with Client Software Automatically installed when Server software is installed.
Connect SQLPlus Session Sqlplus username/password@connectstring SQL> connect USERNAME/Password SQL>DISCONNECT SQL> Password SCOTT : To Change Scott Password Entering SQL Statements Statements can be entered in multiple Lines End of statements denoted by semicolon Previously executed Statements are stored SQL Buffer / or RUN is used to re execute the statement in the buffer Edit the Buffer DEFINE _EDITOR=vi SQL>LIST (L) : Shows Statements in the buffer
SQL>APPEND (A) WHERE EMPLOYEE_NUMBER=110 : Appends at the end of the line SQL> CHANGE (C) / <> /= SQL>I 7777 AND EMP_NO=110 : Changes <> to =
SQL> SAVE filename : Saves statement in buffer to file SQL>@filename SQL>EDIT SQL>GET filename Saving Results to File SPOOL filename Comments /* Line Comment */ Single/Multiline Comments : Runs the File , @@ to Run from within a file : Edit the Buffer : Gets file content to buffer
SHOW variable/ALL: Shows the environment SET Command : To Modify the values Important Variables SET LINESIZE SET AUTOCOMMIT OFF SET SCAN OFF SET TIME ON Formatting output COL colname for a23
3. Functions
Functions are programs that take zero or more arguments and returns a single value Types of Functions: Single Row Functions Group Functions Analytics Functions 3.1 Single Row Functions Single row Functions can be incorporated into SELECT, WHERE, ORDER BY Clauses
NULL and Single Row Functions NVL , NVL2 SELECT first_name, last_name, salary, bonus ,salary + bonus total_comp FROM employees; SELECT first_name, last_name, salary, bonus ,salary + NVL(bonus,0) total_comp FROM employees; SELECT first_name, last_name, salary, bonus ,NVL2(bonus,salary + bonus,salary) total_comp FROM employees;
INSTR(<c1>,<c2>[,<i>[,<j>]]) I : Starting Position J : J th Occurance SELECT INSTR('Mississippi', 'i',3,3) test1 ,INSTR('Mississippi', 'i',1,3) test1 ,INSTR('Mississippi', 'i',-2,3) test3 FROM dual; LENGTH SELECT LENGTH('The Three Musketeers') title_length FROM dual; LOWER SELECT colorname, LOWER(colorname) FROM itemdetail WHERE LOWER(colorname) LIKE '%white%'; UPPER SELECT ename, job, hiredate FROM emp WHERE UPPER(ename) LIKE 'KIN%'; LTRIM SELECT LTRIM('Mississippi','Mis') test1 ,LTRIM('Rpadded ') test2 ,LTRIM(' Lpadded') test3 ,LTRIM(' Lpadded', 'Z') test4 FROM dual; RTRIM SELECT RTRIM('Mississippi','ip') test1
CEIL SELECT CEIL(9.8) ,CEIL(-32.85) ,CEIL(0),CEIL(5) FROM dual; FLOOR SELECT FLOOR(9.8),FLOOR(-32.85),FLOOR(137) FROM dual; ROUND SELECT ROUND(12345,-2) test1 ,ROUND(12345.54321,2) test2 FROM dual;
Date Functions
ADD_MONTHS SELECT SYSDATE ,ADD_MONTHS(SYSDATE,3) plus_3 ,ADD_MONTHS(SYSDATE,-2) dual; CURRENT_DATE SELECT SYSDATE ,CURRENT_DATE ,SESSIONTIMEZONE FROM dual; CURRENT_TIMESTAMP SELECT CURRENT_TIMESTAMP FROM dual; DBTIMEZONE SELECT DBTIMEZONE FROM dual; ALTER DATABASE SET TIME_ZONE='-06:00'; EXTRACT ( <c> FROM <date> ) Extracts c from date c Can be YEAR, MONTH, DAY, minus_2 FROM
SELECT SYSDATE ,EXTRACT(YEAR FROM SYSDATE ) YEAR ,EXTRACT(MONTH FROM SYSTIMESTAMP) MONTH ,EXTRACT(TIMEZONE_HOUR FROM SYSTIMESTAMP) TZH FROM dual; LAST_DAY SELECT SYSDATE ,LAST_DAY(SYSDATE) END_OF_MONTH ,LAST_DAY(SYSDATE)+1 FROM dual; MONTHS_BETWEEN SELECT MONTHS_BETWEEN('19-Dec-2002','19-Mar-2003') test1 ,MONTHS_BETWEEN('19-Dec-2002','19-Mar-2002') test2 FROM dual NEXT_DAY SELECT NEXT_DAY('01-Jan-2000','Monday') "1st Monday" ,NEXT_DAY('01-Nov-2004','Tuesday')+7 "2nd Tuesday" FROM dual; ROUND SELECT SYSDATE,ROUND(SYSDATE,'HH24') FROM dual; TRUNC SELECT TRUNC(last_analyzed,'HH') FROM user_tables WHERE table_name='TEST_CASE'; SYSTEMTIMESTAMP/SYSDATE SELECT SYSTIMESTAMP ,SYSDATE from dual; NEXT_MONTH
Conversion Functions
TO_CHAR(<x>,[,<frmt>])
SELECT SYSDATE ,TO_CHAR(SYSDATE,'Mmspth') Month ,TO_CHAR(SYSDATE,'DDth') Day ,TO_CHAR(SYSDATE,'Yyyysp') Year FROM dual; SELECT TO_CHAR(SYSDATE,'MONTH') upperCase ,TO_CHAR(SYSDATE,'Month') mixedCase
Other Functions
DECODE SELECT sid ,serial# ,username ,DECODE(command ,0,'None' ,2,'Insert' ,3,'Select' ,6,'Update' ,7,'Delete' ,8,'Drop' ,'Other') cmd from v$session; GREATEST SELECT GREATEST('19','24',9) string FROM dual; LEAST SELECT LEAST(SYSDATE,'15-MAR-2002','17-JUN-2002') oldest FROM dual; NULLIF(x1,x2) Returns
Group Functions
: Returns the statistical mean :Returns number of non-NULL rows : Returns largest Value : Return smallest value : Return Sum of all values
AVG([{DISTINCT | ALL}] <n>), SELECT job_id, AVG(salary) FROM hr.employees WHERE job_id like AC%
GROUP BY SELECT cust_state_province, count(*) customer_count FROM sh.customers GROUP BY cust_state_province; HAVING SELECT t.fiscal_month_desc ,s.channel_id ,SUM(s.quantity_sold) ,SUM(s.amount_sold) FROM sh.times t ,sh.sales s WHERE t.time_id = s.time_id AND s.promo_id <> 9999 GROUP BY t.fiscal_month_desc, s.channel_id HAVING SUM(S.amount_sold) > 2000000;