0% found this document useful (0 votes)
254 views

SQL Notes

The document discusses Structured Query Language (SQL) and data types in Oracle. It provides details on the 9 common SQL commands, 6 data types including CHAR, VARCHAR, DATE, NUMBER, LONG, and RAW/LONG RAW. It also summarizes the SQL functions including date functions like ADD_MONTHS and MONTHS_BETWEEN, numeric functions like ABS and CEIL, and character functions like INITCAP and LOWER.

Uploaded by

Harry
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
254 views

SQL Notes

The document discusses Structured Query Language (SQL) and data types in Oracle. It provides details on the 9 common SQL commands, 6 data types including CHAR, VARCHAR, DATE, NUMBER, LONG, and RAW/LONG RAW. It also summarizes the SQL functions including date functions like ADD_MONTHS and MONTHS_BETWEEN, numeric functions like ABS and CEIL, and character functions like INITCAP and LOWER.

Uploaded by

Harry
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 13

Structured Query Language (SQL): It has 9 commands which are common to all DBMS CREATE, DROP, ALTER for

Tables INSERT, UPDATE, DELETE for Records GRANT, REVOKE for Permission SELECT for Query

Data Types of Oracle


1. CHAR (size) 2. VARCHAR (size)/VARCHAR2 (size) 3. DATE 4. NUMBER (P, S) 5. LONG 6. RAW/LONG RAW 1. CHAR (SIZE) This data type is used to store character strings values of fixed length. The size in brackets determines the number of character the cell can hold. The maximum number characters this data type can hold is 255 characters Example: Name CHAR(60) 2. VARCHAR (size)/VARCHAR2 (size) This data type used store variable length alphanumeric data. It is more flexible form of the CHAR data type. The maximum this data type can hold up to 4000 characters. VARCHAR can hold 1 to 255 characters. That CHAR is much faster than VARCHAR, sometimes up to 50%. 3.DATE This data type is used to represent date and time. The standard format is DD-MON-YY as in 21-JUN-09. Date time stores date in the 24-hours format. Valid dates range from January 1, 4712 B.C. to December 31, 4712 A.D. 4.NUMBER(P,S) The NUMBER data type is used store numbers (fixed and floating point). Number of virtually any magnitude maybe stored up to 38 digits of precision Number may be expressed in two ways: first, with number 0 to 9, the sign + and -, and a decimal point (.); second, in scientific notation, such as, 1.85E3 for 1850. The precision (P), determines the maximum length of data, whereas the scale(s), determines the number of places to the right of the decimal. 4. LONG This data type is used to store variable length character strings containing 2 GB. LONG data can be used to store arrays of binary data in ASCII format. 5. RAW/LONG RAW The RAW/LONG RAW data type are used to store binary data, such as digitized picture or image RAW data type can have a maximum length of 255 bytes. LONG RAW data type can contain up to 2 GB.

4.3 Database Language


DDL(Data-Definition Language) We specify a database schema by a set of definition expressed by a special language called a data-definition language(DDL) CREATE, ALTER, TRUNCATE, DROP TABLE CREATE The CREATE TABLE command defines each column of the uniquely. Each column has a minimum of three attributes, a name, datatype and size. Syntax: Create table <table name> (<columnname1> <datatype> (<size>), <columnname2> <datatype> (<size>)); Example: create table client_master(client_no varchar2(6),name varchar2(20),city varchar2(15),pincode number(8),state varchar2(15)); ALTER The structure of a table can modified by using ALTER TABLE command With ALTER TABLE it is possible to add or delete columns, create or destroy indexes, change the data type of existing columns, or rename columns or the table itself. Syntax: Adding New Columns Alter table <TableName> Add (<NewColumnName <Datatype> (<size>), <NewColumnName <Datatype> (<size>).); Modifying Existing Columns Alter table <TableName> Modify(<ColumnName> <NewDatatype>(<NewSize>)); Example: 1). alter table client_master add(telephone_no number(10)); 2). alter table product_master modify(SELL_PRICE number(10,2)); TRUNCATE TABLE TRUNCATE TABLE empties a table completely Logically, this is equivalent to DELETE statement that deletes all rows TRUNCATE operations drop an re-create the table, which is much faster than deleting rows one by one TRUNCATE operations are not transaction-safe The number of deleted rows are not returned Syntax: TRUNCATE TABLE <Table Name> Example: TRUNCATE TABLE client_master; DROP TABLE Such situation using the DROP TABLE statement with table name can destroy a specific table. Syntax: DROP TABLE <TableName>

Example: DROP TABLE client_master; DML (Data-Manipulation language) Types of DML:1. Procedural DML Require a user to specify what data are needed and how to get those data. 2. Nonprocedural (Declarative) DML Require a user to specify what data are needed without specifying how to get those data. Commands: INSERT,SELECT,UPDATE,DELETE INSERT When inserting a single row data into the table, the insert operation: Creates a new row in the database table Loads the values passed into the column specified Syntax: Insert table <table name> (<columnname1>,<columnname12>) values (<expression1>,<expression2>); Example: Insert table client_master (client_no,name) Values (C00001,RAHUL); SELECT The SELECT command is used to retrieve rows selected from one or more tables Syntax: 1). SELECT * FROM <TableName>; 2). SELECT <ColumnName1>,<ColumnName2> From <TableName>; 3). SELECT * FROM <TableName> WHERE <Condition>; 4). Etc Example: 1). SELECT * FROM client_master; 2). SELECT name, city FROM client_master; 3). SELECT * FROM client_master Where city=Bombay; UPDATE The UPDATE command is used to change or modify data values in a table The verb update in SQL is used to either update: All the rows from table A select set of rows from table Syntax: Update <table name> Set <columnname1> = <expression1>, <columnname2> = <expression2>;

Example: Update client_master Set city=Bombay; DELETE The DELETE command deletes rows from the table that satisfies the condition provided by its where clause, and returns the number of records deleted. The verb DELETE in SQL is used to remove either: All the rows from table A select set of rows from table Syntax: 1) Delete from <table name>; 2) Delete from <table name> Where <Condition>; Example: 1) Delete from client_master; 2) Delete from client_master Where client_no=C00001; 4.5 SQL functions Single row functions Date function 1. ADD_MONTHS() It returns the date after adding the number of months specified within the function Syntax: ADD_MONTHS(date,n) Example: select ADD_MONTHS (04-jun-2009,2) from dual; Output: 04-AUG-2009 2. MONTHS_BETWEEN It returns the date the number of months between the specified dates. Syntax: MONTHS_BETWEEN(date1,date2) Example: select MONTHS_BETWEEN (02-FEB-09,02-JAN-09) from dual; Output: 1 3. Round() It rounds a date to 12 A.M(midnight) if time of the date is before noon, otherwise it rounds up to next day. Syntax: ROUND(date) Example: select ROUND(14-08-09) from dual; Output:-3 4. NEXT_DAY It returns the date of the first weekday named by char that is after the date named by date. char must be day of the week. Syntax: NEXT_DAY(date,char) Example: select NEXT_DAY(04-FEB-09,FRIDAY) from dual; Output: 06-FEB-09 5. TRUNC() It always sets a date to 12 A.M (midnight). Syntax: TRUNC(date) Example: select TRUNC(02-08-09) from dual; Output:-15

6. GREATEST() It displays the latest date from a list of dates Syntax: GREATEST (date1, date2, date3 ) Example: select GRETEST(02-FEB-09, 02-JAN-09) from dual; Output: 02-JAN-09 7. NEW_TIME() It display the date in the required time zone Syntax: : NEW_TIME (date,currenttimezone,newtimezone) Example: select NEW_TIME(sysdate,'EST','HST') from dual; Output: 22-JUL-09 Numeric function 1. ABS() It returns the absolute value. Syntax: ABS(n) Example: select ABS(-15) from dual; Output: 15 2. CEIL() It returns the smallest integer that is greater than or equal to a specific value Syntax: CEIL(n) Example: select CEIL(1.3) from dual; Output:2 Example: select CEIL(2) from dual; Output:2 Example: select CEIL(-2.3) from dual; Output:2 3. COS() It returns the cosine of a given value. Syntax: COS Example: select COS(45) from dual; Output: 1 4. COSH() It returns hyperbolic cosine of a given value. Syntax: COSH Example: select COSH(45) from dual; Output: 1.7467E+19 5. EXP() It returns e raised to the nth power, where e=2.71828183. Syntax: EXP(n) Example: select EXP(5) Exponent from dual; Output: Exponent 148.413159

6. FLOOR() It returns the greatest integer that is less than or equal to a specific value. Syntax: FLOOR(n) Example: select FLOOR(1.3) from dual; Output: 1

Example: select FLOOR(2) from dual; Output: 2 Example: select FLOOR(-2.3) from dual; Output: -3 7. POWER() It returns the value raised to a given positive exponent. Syntax: POWER(value, exponent) Example: select POWER(3,2) from dual; Output: 9 Example: select POWER(64,0.5) from dual; Output: 8 8. MOD() It divides a value by a divisor and returns the remainder. Syntax: MOD(value, divisor) Example: select MOD(100,10) from dual; Output: 0 Example: select MOD(10,3) from dual; Output: 1 9. ROUND() It rounds a number to given number of digits of precision Syntax: ROUND(value, precision) Example: select ROUND(66.666,2) from dual; Output: 66.67 10. TRUNC() It truncates digits of precision from a number Syntax: TRUNC(value, precision) Example: select TRUNC(66.666,2) from dual; Output: 66.66

11. SORT() It returns the square root given number Syntax: SQRT(n) Example: select SQRT(64) from dual; Output: 8 Character function
1. INITCAP() Returns a string with the first letter of each word in UPPER CASE Syntax: INITCAP(char) Example: select INITCAP('rahul kumar') from dual; Output: Rahul Kumar 2. LOWER() It takes any string or column and converts it into lowercase Syntax: LOWER(string) Example: select LOWER(RAHUL) from dual; Output: rahul

3. UPPER() It takes any string or column and converts it into upper case Syntax: UPPER(string) Example: select UPPER(rahul) from dual; Output: RAHUL 4. LTRIM() It removes character from the left of char with initial characters removed up to the first character not in set Syntax: LTRIM(char, set) Example: select LTRIM(RAHUL,R) from dual; Output: AHUL 5. RTRIM() It returns char with final character removed after the last character not in the set. set is optional, it defaults to spaces. Syntax: RTRIM(char, set) Example: select RTRIM(RAHUL,L) from dual; Output: RAHU 6. TRANSLATE() Replace a sequence of character in a string with another set of character. Syntax: TRANSLATE(string1,string to replace, replacement string) Example: select TRANSLATE(1sct523,123,7a9) from dual; Output: 7sct5a9

7. REPLACE() It replaces a character in a string with zero or more character. Syntax: REPLACE(string1, character to be replaced, characters) Example: select REPLACE(Hello, o, rec ) from dual; Output: hellrec 8. SUBSTRING() It returns a substring from a given string It returns a portion of char, beginning at character m exceeding up to n characters. Syntax: SUBSTR(string) Example: select SUBSTR(SECURE,3,4) from dual; Output: CURE

Conversion function
1. TO_CHAR() It converts a value of DATE data type to CHAR value. It accept a date as well as the format in which the date has to appear. The format must be a date format Syntax: TO_CHAR(date, format) Example: select TO_CHAR(SYSDATE,DD-MM-YY) from dual; Output: 22-07-09 2. TO_DATE()

It converts a CHAR filed to a DATE filed. Syntax: TO_DATE (char, format) Example: select TO_DATE(26/08/09,DD/MM/YY) from dual; Output: 26-AUG-09

3. TO_NUMBER() It converts a character value containing a number to a value of NUMBER data type. Syntax: TO_NUMBER(char) Example: select TO_NUMBER(100) from dual; Output: 100

Miscellaneous function
1. UID It returns an integer that uniquely identifies the session user. Example: select UID from dual; Output: 18 2. USER It returns the name by which the current user is know to Oracle. Example: select USER from dual; Output: scott 3. NVL It stands for Null value Substitution. Syntax: NVL(value, substitute) If the value is NULL, this function is equal to substitute. If the value is not NULL, this unction is equal to value. Example Table name: Shipping
Client Johnson tools Inf Software Peterson Industries Weight 59 27 NULL

4. VSIZE It returns the number of bytes in the internal representation of an expression. Syntax: VSIZE(expression) Example: select VSIZE(SCT on the net) from dual; Output: 14

Group function
1. AVG() It returns average value of the specified column, ignoring NULL values. Syntax: AVG(Column name)

Example: select AVG(sell_price) from product_master; Output: 2012.345

2. MIN() It returns the minimum value in the specified column. Syntax: MIN(column name) Example: select MIN(sell_price) from product_master; Output: 250 3. MAX() It returns the maximum value in the specified column. Syntax: MAX(column name) Example: select MAX(sell_price) from product_master; Output: 1500 4. SUM() It returns the sum of values of the specified column. Syntax: SUM(column name) Example: select SUM(salary) from salesman_master; Output: 65000

5. COUNT() It returns the number of rows in specified column or the total number of rows in the table. Syntax: COUNT(column name) Example: select COUNT(salesman_no) from salesman_master; Output: 15 Syntax: COUNT(*) Example: select COUNT(*) from salesman_master; Output: 50

Group by, Having by and order by clause


GROUP BY Clause
GROUP BY clause is another section of the select statement This optional clause tells Oracle to group rows based on distinct values that exist for specified columns The GROUP BY clause creates a data set, containing several sets of records grouped together based on a condition Syntax: Select <column name1>,<column name2>, <column nameN> AGGREGATE_FUNCTION (<Expression>) From Table Name WHERE <condition> GROUP BY<column name1>,<column name2>,<column nameN>;

Example: SELECT branch_nobranch_no,COUNT(emp_no)No Employees From emp_master GROUP BY branch_no;

HAVING Clause
HAVING Clause can be used in conjunction with the GROUP BY clause HAVING imposed a condition on the GROUP BY clause. which further filter the group created by the groups by clause

Syntax: Select <column name1>,<column name2>, <column nameN> AGGREGATE_FUNCTION (<Expression>) From Table Name WHERE <condition> GROUP BY<column name1>,<column name2>,<column nameN>; HAVING <condition>
Example: Select product_no,sum (qty_ordered) total QTY ordered From sales_order GROUP BY product_no HAVING product_no=P00001 or product_no=P00004 HAVING clause is specified row displayed on screen.

ORDER BY Clause
ORDER BY is use want the information it return sorted in the order specify. Syntax: Select <column name1>,<column name2>, <column nameN> From Table Name Where <condition> ORDER BY <column name1>; Example: Select feature, section, page from NEWSPAPER Where section=F ORDER BY feature;

JOINS
Simple, Equi-join, Non-Equi join, Self-join, Outer-join The process of forming rows from two or more tables by comparing the contents of a related column is called Joining tables. The resulting table is called a JOIN between the tables.

1. Equi Join : A join based on an exact match between two columns is called an Equi Join The comparison operator in the join condition is = Example: Table Name: emp Ename Eid Sal Deptno Rahul E01 1000 10 Vishal E02 1500 15 Ajit E03 2000 20 Table Name: dept Deptno Deptname Location 10 Sales Mumbai 15 Accounts Chennai 20 Purchase Mumbai

select ename,eid,location from emp,dept where emp.deptno=dept.deptno;


The above join query will retrieve the name, id and location of all employees Output: Ename Rahul Vishal Ajit Eid E01 E02 E03 Location Mumbai Chennai Mumbai

2. Non-Equi Join :
Joins which use Equi joins. Example: Table Name: emp Ename Eid Rahul E01 Vishal E02 comparison operators other than = are called Non-

Sal 1000 1500

Deptno 10 15

Ajit E03 2000 20 Table Name: dept Deptno Deptname Location 10 Sales Mumbai 15 Accounts Chennai 20 Purchase Mumbai Select ename, location from emp, dept Where sal BETWEEN 1000 AND 2000; The above join query will retrieve the name, and location of employees having salary between 1000 and 2000 Output: Ename Location Vishal Chennai

3. Self Join :
A join that joins one row in table with another row in the same table is called Self Join. Using the table alias names these two identical tables can be joined. From <TableName> [<alias1>], <TableName> [<alias2>] Example: Table Name: employee Eid Ename Manager_no E00001 Rahul E00002 E00002 Vishal E00005 E00003 Ajit E00004 E00004 Prem E00005 Ronak

select e1.ename,e2.ename from employee e1,employee e2 where e1.manager_no = e2.eid;


The above query will retrieve the names of the employees and the names of their respective manager from the employee table

Output: Ename Manager_no Rahul Vishal Vishal Ronak Ajit Prem

4. Outer Join :
A join that joins one row in table with another row in the same table is called Self Join.

An Outer Join extends the result of an inner join by including rows from one table ( say table A ) that dont have corresponding rows in another table ( say table B ). An important thing to note here is that the outer join operation will not include the rows from table B that dont have corresponding rows in table A. In other words, an outer join is unidirectional. But there are situations when you may want a bidirectional outer join, i.e., you want to include all the rows from A and B. Rows from the result of the inner join Rows from A that dont have corresponding rows in B Rows from B that dont have corresponding rows in A

Outer join in three types Left outer join Right outer join Full outer join

You might also like