Professional Documents
Culture Documents
SQL
SQL
SQL
Syntax to create a Table: CREATE TABLE <table name> ( {<column name> <data type> [(<size>)] [DEFAULT <value>] {[[CONSTRAINT <constraint name>] <constraint definition>]} [ ] } [ , ] [ , <table level constraints> ] [ ] ); Example (without Constraints): CREATE TABLE customer ( customer_id NUMBER (4), customer_name VARCHAR2(30), customer_dob DATE, customer_income NUMBER(8,2), customer_type VARCHAR2(15) );
Example: ALTER TABLE customer ADD ( customer_phone VARCHAR2(30) NOT NULL, customer_email VARCHAR2(30) UNIQUE );
Example: ALTER TABLE customer MODIFY ( customer_name VARCHAR2(40) NULL, customer_email VARCHAR2(50) );
Example: INSERT INTO customer VALUES (1, Mr. Ashok, 01-Jan-1970, 10000, P); INSERT INTO customer (customer_id, customer_name) VALUES (1, Mr. Ashok); INSERT INTO customer_copy (customer_id, customer_name) SELECT customer_id, customer_name FROM customer;
WHERE customer_id = 1;
Example: DELETE FROM customer; DELETE customer; DELETE FROM customer WHERE customer_id = 1;
Example: SELECT * FROM customer; SELECT customer_id, customer_name FROM customer; SELECT customer_id ID, customer_name Name FROM customer; SELECT customer_id, customer_income * 1.1 NewIncome FROM customer;
5. Other Functions The functions that do not fall in the above types are grouped under this category.
-----> 10
2. Mod(<val>,<n>): Returns remainder of division. Value is divided by <n>. SELECT mod(10,3) DROM dual; ------> 1
3. Power(<val>,<n>): Returns value raised up to <n> SELECT power (10,2) FROM dual;
----> 100
4. Sign(<val>): Returns 1 if value is positive, 0 if value is 0 and -1 if value is negative. SELECT sign(10), sign(0), sign(-10) FROM dual; -------> 1 0 -1 5. Round(<val> [,<n>]): Returns rounded value up to specified <n> decimal digits. If <n> not specified, no decimal digits are included in the output. SELECT round (10) FROM dual; --------> 10 SELECT round (10.4) FROM dual; --------> 10 SELECT round (10.5) FROM dual; --------> 11 SELECT round (10.523,2) FROM dual; --------> 10.52 SELECT round (10.525,2) FROM dual; --------> 10.53
4. Upper (<str>): Returns the string in upper case characters. SELECT upper ('usha') FROM dual;
USHA
usha
6. Rpad (<str>,<output size> [,<filler chars>]): Used to pad the filler character within the string during output to the right side of the string. filler character is used when size is greater than the string length SELECT Rpad (Ramesh,10, '* ) FROM dual; Ramesh**** 7. Lpad (<str>,<output size> [,<filler chars>]): Same as Rpad but starts padding from left side of the string. SELECT Rpad (Ramesh,10, '* ) FROM dual; ****Ramesh 8. Rtrim (<str> [,<char set>]): Trims or removes the character set from the right side of the string. If character set is not defined, then spaces are removed. SELECT Rtrim (Ramesh ) FROM emp; Ramesh SELECT Rtrim (Ramesh, sh) FROM emp; Rame 9. Ltrim (<str> [,<char set>]): Same as Rtrim but trims from left side of the string. SELECT Ltrim (Ramesh, Ra) FROM emp; mesh
10. Initcap (<str>): First character of each word will be converted in capital and rest in lower case. SELECT initcap (raj kumar) FROM dual; Raj Kumar
11. Ascii (<char>): Returns ascii value of given character. SELECT Ascii (A) FROM dual;
65
12. Chr (<ascii value>): Returns the character represented by ascii value. SELECT Chr (65) FROM dual; A
2. Months_Between (<date1>, <date2>): Returns a number indicating the difference between two dates in terms of months. Return value may be positive or negative. Positive if first date is higher than the second date. Negative if second date is higher. SELECT Months_Between (sysdate, hiredate) FROM dual;
3. Sysdate: Returns system date. SELECT sysdate FROM dual; 4. Last_Day (<date>): Returns a new date with last day of the month for the date. SELECT Last_Day (sysdate) FROM dual; 5. Next_Day (<date> , <day name>): Returns a new date for the day mentioned as <day name> which comes after the <date>. SELECT Next_Day (sysdate, 'SUNDAY') FROM dual;
2. To_Date (<char>, <input format>): Converts character value in to date as per the given input format. INSERT INTO emp (empno, hiredate) VALUES (1, To_Date ('12/04/2001', 'dd/mm/yyyy'));
3. LEAST (<value list>): Returns smallest value from the list of values.
DECODE ( <value / expression> {,<search pattern>, <return value>} [,...] [,<default return value>] ) if <value / expression> matches with any of the search pattern then return value for the pattern will be returned. If <value /expression> do not match with any pattern then default value will be returned. If default return value is not mentioned then null Is the return value. For example: Display the grades as defined below: 1 as Poor 2 as Average 3 as Good Rest as Excellent
SELECT DECODE (grade, 1, Poor, 2, Average, 3, Good, Excellent) FROM salgrade;
What is sub-query: It is a method to retrieve data from a table and pass the same to its parent query. At least two queries are must in sub query method. Different queries used in subqueries are: Root Query: Top most query is referred as Root Query. Parent Query: A Query that receives values from other queries. Child Query / Sub-query: A Query called by another query.
When Sub Query is required: When output is required from one table and condition(s) require another table. For example: Display those employees whose department is SALES. SELECT * FROM emp WHERE deptno = (SELECT deptno FROM dept WHERE dname = SALES) When output is required from one or more records and condition requires another record(s) from the same table. For example: Display those employees who are working under KING. SELECT * FROM emp WHERE mgr = (SELECT empno FROM emp WHERE ename = KING)
Independent or simple Sub-query: An Independent Sub-query is processed once for its parent query. After receiving values from Sub-query, Parent Query is processed. In case of Independent Sub-query, Parent Querys columns are not used. SELECT * FROM emp WHERE deptno = (SELECT deptno FROM dept WHERE dname = SALES) Correlated Sub Query: In correlated Sub Query method, Sub-query is processed for each record of Parent Query i.e. Sub-query is processed as many times as the number of records processed by Parent Query. In case of correlated Sub-query, table aliases are must since the columns from Parent Table and Child Tables are used in a single condition. So to refer the columns from Parent Table into Sub-query, we need to use Table Name or Alias Name with Columns. If Parent and Child both tables are same then Alias is must.
Generally Number of Join Conditions are Number of Tables - 1. If Join Conditions is not defined then output will be Multiple of Records from all the Tables.
Example: SELECT dept.dname, emp.ename FROM dept, emp WHERE dept.deptno = emp.deptno; SELECT emp.ename, salgrade.grade FROM emp, salgrade WHERE emp.sal BETWEEN salgrade.losal AND salgrade.hisal;
Equi Join: When two tables relation is based on Common Columns / Values (or based on Equality). For example: EMP and DEPT tables are related via DEPTNO common column (like emp.deptno = dept.deptno).
Non-equi Join: When two tables relation is based on Range of Values (or based on other than Equality). For example: EMP and SALGRADE tables are related via SAL from emp table and LOSAL & HISAL from salgrade table (like emp.sal BETWEEN salgrade.losal AND salgrade.hisal).
Outer Join: When we need to select Matching Records as well as Non Matching Records from two tables. For Outer Join Query we need to use Outer Join Operator (+). For Example: Display all Department names and Employee names including the Department not having any employee. SELECT D.dname, E.ename FROM emp, dept WHERE emp.deptno (+) = dept.deptno; Display all Employees name and Managers name including the Employee not having a Manager. SELECT E.ename, M.ename FROM emp E, emp M WHERE E.mgr (+)= M.empno;
UNION ALL: Returns all the data from both the queries including duplicate values. SELECT deptno FROM dept UNION ALL SELECT deptno FROM emp;
SQL ( DCL - 1)
Data Control Language Commands: Commands under this group are used to grant or revoke privileges on System Resource or on Objects. There are two commands under this: GRANT { <system privileges> | <roles> | ALL PRIVILEGES } TO { <user name> | <role name> | PUBLIC } [ IDENTIFIED BY <password> ] [ WITH ADMIN OPTION ]; 2. GRANT { <object privileges> | ALL | ALL PRIVILEGES } [ (<column name list>) ] ON <object name> TO { <user name> | <role name> | PUBLIC } [ WITH GRANT OPTION ]; Example: 1. GRANT CREATE TABLE, CREATE VIEW TO Scott WITH ADMIN OPTION; 2. GRANT ALL PRIVILEGES TO Scott WITH ADMIN OPTION; 3. GRANT INSERT, UPDATE (ename,sal) ON emp TO Scott; 4. GTANT ALL ON emp TO Scott WITH GRANT OPTION;
SQL ( DCL - 2)
REVOKE { <system privileges> | <roles> | ALL PRIVILEGES } FROM { <user name> | <role name> | PUBLIC }; 2. REVOKE { <object privileges> | ALL | ALL PRIVILEGES } ON <object name> FROM { <user name> | <role name> | PUBLIC };
Example: 1. REVOKE CREATE TABLE, CREATE VIEW FROM Scott; 2. REVOKE ALL PRIVILEGES FROM Scott; 3. REVOKE INSERT, UPDATE (ename,sal) FROM emp TO Scott; 4. REVOKE ALL ON emp FROM Scott;
SQL ( TCL - 1)
Transaction Control Language Commands: These commands are to control effects of DML commands on Database. There are following three commands: 1. SAVEPOINT <savepoint name>; Savepoint is a portion within a Transaction to which you may rollback. It allows to rollback portion of current transaction.
View
View: View is like a table but does not keep any data. A view is created on table(s) using select statement: CREATE [ OR REPLACE ] [ FORCE ] VIEW <view name> AS <query> [ WITH READ ONLY ];
Synonym
Synonym: It is used to provide another name to objects. So a single object can be accessed by many different names. It is very useful for Remote Objects to provide them short cut Name. It is used for Tables, Views, Synonyms, Sequences, Procedures, etc. Syntax : CREATE [PUBLIC] SYNONYM <synonym name> FOR [<schema name>.] <object name> [@<dblink name>]; Example: 1. CREATE SYNONYM s1 FOR scott.emp; 2. CREATE PUBLIC SYNONYM s2 FOR scott.dept; Sequence: CREATE SEQENCE <sequence name> [ START WITH <n>] [ INCREMENT BY <n> ] [ MAXVALUE <n> | NOMAXVALUE ] [ MINVALUE <n> | NOMINVALUE ] [ CYCLE | NOCYCLE ] [ CACHE <n> | NOCHACHE ];