You are on page 1of 13

ORACLE

SQL & PL/SQL QUERIES WITH EXPLAINATION SQL-Structured Query Language:

SQL is a programming language that is used to manage the RDBMS. It includes data creation, modification and data access control.

TYPES OF SQL COMMANDS


DDL-Data Definition Language used to create, alter and delete Database Objects. The commands are: CREATE ALTER DROP TRUNCATE DML-Data Manipulation Language used to insert, modify and delete the data in the database. INSERT INTO UPDATE DELETE DQL-Data Query Language is used to query one or more tables to retrieve the data needed from database. It also comes under the DML section. SELECT DCL-Data Control Language that is used to control the user access to the database objects. COMMIT ROLLBACK SAVEPOINT GRANT REVOKE DATABASE SCHEMA OBJECTS: OBJECT TABLE VIEW SEQUENCE SYNONYM INDEX NAMING RULES:Table names and column names: Must begin with a letter. Must be 1-30 characters long. DESCRIPTION Basic unit of storage; composed of rows. Logically represents subsets of data from one or more tables. Generates numeric values.

Must contain only A-Z,a-z,0-9,_,$,# Must not duplicate the name of the another object. Must not use the keywords and other code related words.

DDL
[SQL Statements are not case-sensitive]
CREATE Statement:Used to create a table, view, index, sequence, procedure, functions and others. SYNTAX for creating a table: CREATE TABLE table_name(column_name data_type(limit),); ALTER Statement:The ALTER TABLE statement allows you to rename an existing table. It can also be used to add, modify, or drop a column from an existing table. SYNTAX: ALTER TABLE table_name ADD(column_name data_type(limit),...); //The above syntax will add some new columns to the table. ALTER TABLE table_name DROP COLUMN column_name; //Deletes the specific column mentioned. ALTER TABLE table_name MODIFY column_name datatype; //Modifies the data type of the column. ALTER TABLE table_name RENAME TO new_table_name; //Renaming the table.[Note: Another syntax to rename tables alone- RENAME old_tab TO new_tab;] ALTER TABLE table_name RENAME COLUMN old_column_name TO new_name; //Renaming a column. DROP Statement:Deletes the whole content from the database. SYNTAX: DROP TABLE table_name; //Used to delete the table completely including its structure. [Note: You can get back the dropped table before commit using the following syntax: FLASHBACK TABLE table_name TO BEFORE DROP; ] In the same way we can PROCEDURES,SEQUENCES,FUNCTIONS,TRIGGERS, PACKAGES. drop anything like

TRUNCATE Statement:It is used to delete all the rows from the table which cannot be rollback or triggered. And it is faster than DELETE statement because it does not occupy the UNDO space in memory. SYNTAX: TRUNCATE TABLE table_name; //It will deletes the contents of the table permanently and cannot be regained by the database.

DML
INSERT INTO Statement:The INSERT INTO statement is used to insert a new row in a table. SYNTAX: INSERT INTO table_name VALUES (value1, value2, value3,...); //This one is used to enter the values in a new row. [Note: To insert a character and date values you should use single quotes to represent them eg: arun ,11-JUN-2012 and we can also use & symbol definition to enter the values continuously] INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...); //This is another type of inserting the values. But it is more specific. UPDATE Statement:The UPDATE statement is used to update existing records in a table. SYNTAX: UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value; //This will update the values in the columns specified using some condition. DELETE Statement:The DELETE statement is used to delete rows in a table. And they can be rolled back if the query is not committed. SYNTAX: DELETE FROM table_name WHERE some_column=some_value; //Deletes a specified conditioned rows from table. DELETE FROM table_name; [or] DELETE * FROM table_name; //Any one of the above can be used to delete all the rows in a table.

DQL
SELECT Statement:The SELECT statement is used to select data from a database. SYNTAX: SELECT * FROM table_name; //To view all the columns in a table. SELECT column_name(s) FROM table_name; //To view the specific columns in a table. Now in the following section we are going to see various conditions and ways of using the SELECT Statement. SYNTAXES RESTRICTING & SORTING DATA: SELECT column_name(s) FROM table_name WHERE some_column=some_value; //this is a sample syntax for using the WHERE Clause. The BETWEEN Operator: The BETWEEN operator is used in a WHERE clause to select a range of data between two values. The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates.

SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2; [ Note: we used AND operator in this syntax we can also use OR in the place of AND in some other required conditions. And we can also combine AND/OR in a single statement It is shown in example here. eg: SELECT * FROM table WHERE column_name='value' AND (col1='val1' OR col2='val2'); ] The IN Operator:The IN operator allows you to specify multiple values in a WHERE clause. SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...); //This statement will show the records that are in the IN condition. [ Note: We can also use NOT IN key word for opposite results ] LIKE Operator:The LIKE operator is used to list all rows in a table whose column values match a specified pattern. It is useful when you want to search rows to match a specific pattern, or when you do not know the entire value. For this purpose we use a wildcard character '%'
For example: To select all the students whose name begins with 'S'

SELECT first_name, last_name FROM student_details WHERE first_name LIKE 'S%';

The output would be similar to: first_name last_name Stephen Fleming Shekar Gowda The above select statement searches for all the rows where the first letter of the column first_name is 'S' and rest of the letters in the name can be any character. There is another wildcard character we can use with LIKE operator. It is the underscore character, ' _ '. In a search string, the underscore signifies a single character. For example: To display all the names with 'a' second character, SELECT first_name, last_name FROM student_details WHERE first_name LIKE '_a%'; The output would be similar to: first_name last_name Rahul Sharma Copying rows from another table: INSERT INTO table_to_ins(col1,col2,..) SELECT col1,col2,.. FROM another_table WHERE condition; [ Note: This statement will copy the contents from other table only if it has the same field types. ] IS NULL and IS NOT NULL:SELECT column_name(s) FROM table_name IS NULL; //displays the columns having null values. SELECT column_name(s) FROM table_name IS NOT NULL; //displays the columns having values. Substitution Condition [&]:SELECT * FROM table WHERE column_name='&value'; //This line will asks the user to enter some specific value and displays the columns which will have the same value in that specified column. SELECT * FROM table WHERE column_name='&&value'; //Using the '&&' symbol we can recall the past substitution query on the same field. [ Note: & is used to create a temporary substitution variable that will prompt you for a value every time it is referenced. Example :

&& is used to create a permanent substitution variable. Once you have entered a value (defined the variable) its value will used every time the variable is referenced. Example :

FUNCTIONS
Two types of functions are there: Single Row Functions-one result per row. Multi Row Functions-one result per set of rows.

SINGLE ROW FUNCTIONS :- [Also known as SQL Scalar functions]


Number functions Character functions Date functions Conversion functions

1) Numeric Functions :
Numeric functions are used to perform operations on numbers. They accept numeric values as input and return numeric values as output. Few of the Numeric functions are:

These functions can be used on database columns. For Example:We can use ROUND to round off the value to the nearest integer. SELECT ROUND (value) FROM dual; //If value is 5.52 It will rounds the value to 5. //Dual is a dummy table which is used to check the operations and conditions

2) Character or Text Functions:


Character or text functions are used to manipulate text strings. They accept strings or characters as input and can return both character and number values as output. Few of the character or text functions are as given below:
Function Name Return Value LOWER (string_value) UPPER (string_value) INITCAP (string_value) LTRIM (string_value, trim_text) RTRIM (string_value, trim_text) All the letters in 'string_value' is converted to lowercase. All the letters in 'string_value' is converted to uppercase. All the letters in 'string_value' is converted to mixed case. All occurrences of 'trim_text' is removed from the left of 'string_value'. All occurrences of 'trim_text' is removed from the right of'string_value' . RTRIM ('Good Morning', ' Morning') Good LTRIM ('Good Morning', 'Good) Morning Examples LOWER('Good Morning') UPPER('Good Morning') INITCAP('GOOD MORNING') Return Value good morning GOOD MORNING Good Morning

TRIM (trim_text FROM string_value) SUBSTR n) LENGTH (string_value) LPAD pad_value) RPAD pad_value)

All occurrences of 'trim_text' from the left and right of 'string_value' ,'trim_text' can also be only one character long . Returns 'n' number of characters Morning 'm'position. Number of characters in 'string_value'in returned. Returns 'string_value' left-padded **Good whole string will be of 'n' characters. Returns 'string_value' right-padded Good** whole string will be of 'n' characters. LENGTH ('Good Morning') 12 TRIM ('o' FROM 'Good Morning') Gd Mrning

(string_value, m, from'string_value' starting from the SUBSTR ('Good Morning', 6, 7)

(string_value, n, with'pad_value' . The length of the LPAD ('Good', 6, '*')

(string_value, n, with 'pad_value' . The length of the RPAD ('Good', 6, '*')

3) Date Functions :
These are functions that take values that are of data type DATE as input and return values of data types DATE, except for the MONTHS_BETWEEN function, which returns a number as output. Few date functions are as given below:
Function Name ADD_MONTHS (date, n) MONTHS_BETWEEN (x1, x2) Return Value Returns a date value after adding 'n'months to the date 'x'. Returns the number of months between dates x1 and x2. Returns the date 'x' rounded off to ROUND (x, date_format) the nearest century, year, month, date, hour, minute, or second as specified by the 'date_format'. Returns the date 'x' lesser than or equal to the nearest century, year, TRUNC (x, date_format) month, date, hour, minute, or second as specified by the 'date_format'. Returns the next date of NEXT_DAY (x, week_day) the 'week_day'on or after the date 'x' occurs. NEXT_DAY ('01-Jun-08', 'Wednesday') 04-JUN-08 Examples ADD_MONTHS ('16-Sep81', 3) MONTHS_BETWEEN ('16Sep-81', '16-Dec-81') Return Value 16-Dec-81 3

It is used to determine the number LAST_DAY (x) of days remaining in a month from LAST_DAY ('01-Jun-08') the date 'x' specified. SYSDATE Returns the systems current date and time. Returns the date and time in zone2 NEW_TIME (x, zone1, zone2) if date 'x' represents the time in zone1. NEW_TIME ('01-Jun-08', 'IST', 'EST') 31-May-08 30-Jun-08

4) Conversion Functions :
These are functions that help us to convert a value in one form to another form. For Ex: a null value into an actual value, or a value from one data type to another data type like NVL, TO_CHAR, TO_NUMBER, TO_DATE. Few of the conversion functions available in oracle are:
Function Name Return Value Converts Numeric and Date values to a TO_CHAR (x, [y]) character string value. It cannot be used for calculations since it is a string value. Converts a valid Numeric and Character TO_DATE (x, [ date_format]) values to a Date value. Date is formatted to the format specified by 'date_format'. If 'x' is NULL, replace it NVL (x, y) with 'y'. 'x' and 'y'must be of the same datatype. DECODE (a, b, c, d, e, default_value) Checks the value of 'a', if a = b, then returns'c'. If a = d, then returns 'e'. Else, returnsdefault_value. NVL (null, 1) 1 Examples TO_CHAR (3000, '$9999') TO_CHAR (SYSDATE, 'Day, Month YYYY') TO_DATE ('01-Jun08') Return Value $3000 Monday, June 2008

01-Jun-08

Some Format models for both TO_CHAR and TO_DATE:


DD for day of the month. (01,02,20....) DAY for the day spelled out. (MONDAY) MM for month of the year (12). MONTH for month spelled out. YY for last 2 digits of the year. YYYY for 4 digits of the year. YEAR for the spelled out. Q for quarter of the year. HH for hour of the day.(11 Hrs) HH24 for hour of the day.(22 Hrs) MI for minute of the hour. SS for second of the minute. AM for both AM or PM. TH to add suffixes like..1st,2nd or th.. FM to remove blanks from end of a month. NULLIF- returns a NULL value if both parameters are equal in value. If not, the first value will be returned. SYX- SELECT NULLIF(1, 2) FROM dual; SQRT-It is used to find the square root of a number. SYX- SQRT(number_value);

[ Note :PSEUDO COLUMNS: Not an actual column in any table. Can be used like a column in SQL. Similar to a function with no arguments. Some of them are: SYSDATE,UID,ROWID,ROWNUM,USER,NULL.]

MULTI-ROWS Functions :- [Also known as SQL aggregate functions]


SQL aggregate functions return a single value, calculated from values in a column. Some useful aggregate functions are:

AVG() - Returns the average value COUNT() - Returns the number of rows FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum

An Example syntax to use this: SELECT MAX(column_name) FROM table_name; // In the same way you can declare others according to their usage. [ Note: NESTING AGGREGATE FUNCTIONS-We can also nest two or more Aggregate Functions. //EX- SELECT field_name,SUM(MAX(value_field)) FROM table_name GROUP BY field_name;]

The GROUP BY Statement :The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. SYNTAX :SELECT column_name, aggregate function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name; EX - SELECT field_name, MAX(value_field) FROM table_name GROUP BY field_name; [ Notes: You can use aggregate functions without GROUP BY Statement but you cannot use GROUP BY statement without any aggregate functions in it. And in GROUP BY statement you can also more than one columns in it.]

The HAVING Clause :The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.

SYNTAX :SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value; EX- SELECT Customer, SUM(OrderPrice) FROM Orders WHERE Customer='Hansen' OR Customer='Jensen' GROUP BY Customer HAVING SUM(OrderPrice)>1500; The result-set will look like this:
Customer Hansen Jensen SUM(OrderPrice) 2000 2000

[ NOTE: WHERE Clause is used to apply condition for a single row in table but HAVING is used for some bunch of rows.]

CONSTRAINTS :[ Note: Syntax given here are just examples]


Constraints enforce rules at the table level. Constraints prevent the deletion of a table if there are dependencies. The following constraint types are valid: NOT NULL-allows duplicate values but not the null values.//In the case of NOT NULL you can directly give NOT NULL next to the field without any keywords. UNIQUE-no duplicate values allowed but null value is allowed.
PRIMARY KEY-no duplicate values allowed & null values are not allowed.

FOREIGN KEY-This is used to accept the primary key values of some other table with the reference function. It allows the duplicate values but no null values are allowed. CHECK-this is used to check for the given values if they are not entered then it will show the error message of entered wrong value. //This should be used with the combination of IN('',''); command. Eg- SYNTAX : CREATE TABLE table_name (emp_id number(6) CONSTRAINT constrain_name CHECK(emp_id in(10,20,30)),first varchar2(10)); Example containing other constraints: [Here it is done in COLUMN LEVEL] CREATE TABLE table_name (emp_id number(6) CONSTRAINT constrain_name CHECK(emp_id in(10,20,30)),emp_salary number(10) NOT NULL ,emp_code number(6) CONSTRAINT constrain_name PRIMARY KEY, referral_code number(10) CONSTRAINT constrain_name UNIQUE);

DEFINING CONSTRAINS :Constraints are defined in two ways they are:


[COLUMN LEVEL]

CREATE TABLE table_name (emp_id number(6) CONSTRAINT constrain_name PRIMARY KEY,first varchar2(10)); //Level of syntax declared next to the field.
[TABLE LEVEL]

CREATE TABLE table_name (emp_id number(6) ,first varchar2(10),CONSTRAINT constrain_name PRIMARY KEY(emp_id)); //General level of syntax declared at last. DEFINING FOREIGN KEY CONSTRAINS :Declaration of Syntax: [COLUMN LEVEL] o First create a primary key table: CREATE TABLE prim_table (emp_id number(6) CONSTRAINT prim_name PRIMARY KEY,emp_name varchar2(10));
o

Then create a foreign key table: CREATE TABLE forn_table (emp_id number(6) CONSTRAINT forn_name REFERENCES prim_table(emp_id),dept_name varchar2(10));

Declaration of Syntax: [TABLE LEVEL] o First create a primary key table: CREATE TABLE prim_table (emp_id number(6),emp_name varchar2(10), CONSTRAINT prim_name PRIMARY KEY(emp_id));
o

Then create a foriegn key table: CREATE TABLE forn_table (emp1_id number(6),dept_name varchar2(10),CONSTRAINT forn_name FORIEGN KEY(emp1_id)REFERENCES prim_table(emp_id));

KEYWORDS IN FOREIGN KEY CONSTRAINTS : FORIEGN KEY REFERENCES ON CASCADE DELETE-Deletes the child row when it is deleted in parent table. ON DELETE SET NULL-conv

DISPLAY DATA FROM MULTIPLE TABLES USING JOINS

SQL JOIN
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables. Different SQL JOINs
JOIN: Return rows when there is at least one match in both tables SYX : SELECT table1.columns,table2.columns FROM table1_name NATURAL table2_name;

JOIN

EX

LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table FULL JOIN: Return rows when there is a match in one of the tables

You might also like