Sql smart reference_by_prasad


Published on

SQL Commands

  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Sql smart reference_by_prasad

  2. 2. 2 STRUCTURED QUERY LANGUAGE (SQL) STRUCTURED QUERY LANGUAGE (SQL)SQL: it is a set of commands that lets to access a relation database. It is a standardinterference for many relational databases. it has several simple commands for datadefinition , access and manipulation. It is set oriented. i.e. user can performcommand on a group of data rows or one row . SQL is a non-procedural. To accessdata user need only to name the table and the columns .No need of a describingmethod.SQL HISTORY: SQL begin with a paper published in 1970 by E.F.CODD, amathematician working at IBM Research Laboratory in San Josc, California. In thispaper “A relational model of data for large shared data banks”.CODD formulated the principle of relational system for managing a database anddescribing relational algebra for organizing data into tables. Two years later Chamberlin and others developed a version of language,SEQEL/2 and shortly after that IBM built a prototype system called ‘Sys R’ thatimplemented most of its features. Around 1980the name was changed to SQL.ADVANTAGES OF SQL:- 1. Acceptance: The American National Standard Institute (ANSI) has approved SQL.The International Standard Organization (ISO) and the department of defense also supports SQL.A version of SQL is available in most of companies. 2. Powerful: SQL is complete database language. So user can use it for data defining or definition, data control, transaction management. SQL commands are simple to use in three basic forms, but they have the flexibility to do complex operations. 3. Ease of Use: People can easily access and manipulate data without being involved with the physical organization and storage complexities of the data.CREATION OF DATABASE: A database is collection of logically related data where data is nothing but knownfacts that can be recorded and has implicit meaning. A database can be any size forexample Library database, student database…..etc. To create the databases we use the command called CREATE.In order to communicate with the database, SQL supports the following languages. 1. DDL: Data Definition Language. 2. DML: Data Manipulation Language. <SQL by Prasad>
  3. 3. 3 STRUCTURED QUERY LANGUAGE (SQL) 3. TCL: Transaction Control Language.DDL: It is used to create objects (tables), alter the structure of the objects (tables)and also to drop the objects (tables) created. The concept creating to the DDL isexplained below.TABLE DEFINITION: A table is a unit of storage that holds the data in the rows andcolumns. The DDL used for table definition can be classified into the following form,,COMMANDS IN DDL:1. CREATE TABLE Command2. ALTER Command3. DROP Command4. TRUNCATE Command5. DESC CommandNow consider these Commands one by one; 1. CREATE Command: Syntax;Create table <table name> (column1, column2 …columnn);EX; create table emp (emp_id number(4), name varchar(15), age number(2),salary number(5));Defining a database is nothing but giving a name to an eventual collection ofassociated data. A single database can contains all data associated with oneapplication or with group of related applications. Collecting data into singledatabase allows the user to access the data with one operation. In database the data is stored in the form of rows and columns i.e. nothing buttables (relational model). A database contains one or more tables. Each table has aname & contains a specific number of columns (vertical) & unordered rows(horizontal). Each column in arrow is related in some way to the other column in thesame row.Foe Example: consider the below table.Cust_no contact credit ------------- Columns1564 john 30001243 smith 15001345 joe 20001123 jack 2500 ------------ RowsFig: cust table <SQL by Prasad>
  4. 4. 4 STRUCTURED QUERY LANGUAGE (SQL)Each column has a name & a datatype. Each column contains a data value at theintersection of row & a column.In a table, i) We should specify unique column name ii) We should specify proper data type along with is width.Rules For creating a table. 1. While naming the table first letter should be alphabet. 2. Oracle reserved words cannot be used to name a table. 3. Maximum length for table is 30 characters. 4. Two different tables should not have the same name. 5. Underscore (_), minus(-),numerals & letters are allowed but not blank space & single quotes 2. ALTER Command: In some situations, there may be need to change the structure of the table. This change could be either to modify an existing attribute characteristic or probably to add a new attribute character. Syntax;Alter table <table_name> modify <column_definition>;EX: alter table emp modify (ename varchar(20));IN this alter command the length of the field name changed to 20 from 15. We candecrease the length of an existing column datatype provided the table is empty. Nosuch conditions are imposed while increase the length of an existing column.Alter table <table_name> add(column_definition);To above command adds new column to an existing table.Ex; alter table emp add(address varchar(30));This command adds a new field called ‘address’ to the emp table. 3. TRUNCATE Command: <SQL by Prasad>
  5. 5. 5 STRUCTURED QUERY LANGUAGE (SQL) If there is no further use of records stored in a table & structure has to be retained then the records alone can be deleted, which can done through the Command called ‘truncate’. Syntax; Truncate table <table_name>; Ex; truncate table emp; This deletes the all the rows of the emp table but not the structure of the table. 4. DESC Command or VIEW Command: If the user wants to view the str (structure) of the table or the description of the table then following command helps to achieve the same. Syntax: desc <table_name>; Ex; desc emp; This command list the column of the emp table along with their datatypes or it gives the description of the table. 5. DROP Command: This command is used to delete the entire table i.e. entirely remove from database. In other words this command erases the all contents of the table and table name which was specified. Syntax: drop table <table_name>; Ex; drop table emp; Where it deletes the table emp from database.********************************************************************************************** DML (Data Manipulation Language): DML Commands are most frequently used SQL Commands They are used to query & manipulate existing objects like tables.COMMANDS IN DML:1. INSERT Command2. SELECT Command3. UPDATE Command4. DELETE CommandNow consider these Commands one by one; 1. INSERT Command: Once creation of the table is completed, it remains a skeletal structure unless it is populated with rows. The insert command is used to add one or more rows to a table. While using this command the values are separated by comma’s & datatypes <SQL by Prasad>
  6. 6. 6 STRUCTURED QUERY LANGUAGE (SQL) varchar2,char,date,long,number are enclosed in single quotes. The values must be entered in the same order as they are defined in the table. Syntax: insert into <table_name> values (value_list); Ex: insert into emp values(123,‘prasad’,22,15000); The above command inserts one row with the values 123,‘prasad’,22,15000 into the table emp. Here we are inserting the values for one row at a time. This is called SINGLE INSERTION. MULTIPLE INSERTION of rows is also possible with the below syntax. Insert into emp values(&emp_id,‘&name’,&age,&salary); Using this insertion statement we can insert any number of rows into the table. Multiple is nothing but using the single insert command we can insert any number of rows into the table.  In some cases, we don’t want to enter the value for one or two columns in the table. To do this we can simply enter the value as ‘NULL’ for the specified column.  Inserting data value into the tables into the table is same as inserting the character values, i.e. by enclosing it within single quotes. Ex: insert into emp values(123,‘prasad’,22,15000); 2. SELECT Command: SELECT supports the data retrieval. Data retrieval allows a user or an application program to retrieve stored data from the database & use it. The select statement retrieves data from a database & returns it to you in the form of query result. Using ‘select’ we can view the current into in the tables. With the ‘select’ statement we can do the following, Displaying the entire Column from a table:  Display calculated information from tables, like avg or sum of column. Values(computed fields)  Combine information from two or more tables. SET OPERATORS: The general form of ‘select’ statement is,, Syntax: Select <column_name> from <table_name>; Ex: select name from emp; The above statement is interpreted as,SELECT(What):-- One or more column may be selected from a table. If you select more than one column then the column_name must be separated by Comma’s. <SQL by Prasad>
  7. 7. 7 STRUCTURED QUERY LANGUAGE (SQL)FROM(Where):-- Table name from which the columns are to be selected. a) Displaying all the columns from a table: ‘Select’ & ‘from’ are the two mandatory words in ‘select’ query. A special ‘select’ qualifies is asterisk (*) which is used if the user wishes to select all the columns from a table. Syntax: select * from <table_name>; Ex: select * from emp; This select statement will display all rows of the table emp. Controlling Column Order: The order in which the column names are specified in select command determines the order in which the columns are displayed. Ex: select emp_id,name,salary from emp; b) Displaying Calculated into from table(Computed fields or Conditional retrieval): This section explains about how one can select specific rows from a table & how to select rows that specify singular or multiple search condition. Ex: Consider that we want to know the salaries of emp who get Rs.10,000 & above. To achieve this we can use ‘where’ clause in the select statement as follows,,, Select name from emp where salary >=10000; The output of the above query will be displays the names of employees who receives the salaries 10000 & above. Syntax: select <column_name> from <table_name> where condition; In where clause we can include Relational operators & logical operators.  Relational Operators: < , > , >= , <= , = , <>  Logical Operators: AND, OR, NOT. Ex: select emp_id,name from emp where name=’prasad’ and salary=15000; Select with distinct clause: Consider name column from emp table, whose values are given below; name aaa bbc bac ccc abc aaa <SQL by Prasad>
  8. 8. 8 STRUCTURED QUERY LANGUAGE (SQL) Some columns in table have been repeated twice. They are called duplicatevalues while displaying the duplicate values must be eliminated. To do this we usethe distinct clause in select command. Syntax: Select distinct <column_name> from <table_name>; Ex; select distinct name from emp; Output: name aaa bbb bac bbc abcNOTE: Duplicate values have been removed with the use of distinct clause.ORDER by clause(Sorting):We have seen the queries that display rows in the order that they have been definedat the time of creation of the table. The order can be controlled in which the rows ofthe table are displayed by using order by clause. In the query with the order byclause one can order the rows in ascending or descending order. The order by clauseby default places the rows in ascending order.Ex; select emp_id,name from emp order by emp_id;If emp_id has values 20 50 30 40Then the Output is below format emp_id name 20 a 30 b 40 c 50 dThis query will sort the values in ascending order because the default order isascending order.Ex: select emp_id,name from emp order by emp_id desc; Output: emp_id name 50 d 40 c <SQL by Prasad>
  9. 9. 9 STRUCTURED QUERY LANGUAGE (SQL) 30 b 20 a 3. UPDATE Command: UPDATE modifies the values of one or more columns in selected rows of a table. The table to updated is named in the statement. The where clause selects the rows of the table to modified. The set specifies which columns are to be updated & calculates the new values from them. Syntax: Update <table_name> set <column_name1> = <value1>,<column_name2> = <value2>………where <logical_expression>; UPDATE sets each column name (field) equal to corresponding value in the row selected by the logical expression. Update will change the values on all table rows that specify where condition. For example, suppose if salary has the value of 15000 & want to change (update) it to 20000 then using update command is update emp set salary=20000 where name=’prasad’ ; This statement replaces (updates) the salary to 20000.Where name is the column name of the table emp. 4. DELETE Command: Removing rows from the tables in SQL is easier than inserting them. To delete rows we can use the DELETE Command. Again the Where clause is essential to delete. If we use the delete command without the where clause, the contents of the entire table will be deleted. Syntax: delete from <table_name> where <logical_expression>; To delete the particular row or record we should specify the condition in where clause. Ex: delete from emp where age=22; All the row details of age will be deleted from the table emp. Where emp is the table name & age is the field name.********************************************************************************************** Miscellaneous Commands:-- 1. COPY Command:-- It is used to copy from columns of one table to columns of another table in SQL. <SQL by Prasad>
  10. 10. 10 STRUCTURED QUERY LANGUAGE (SQL) Syntax: Create table <new_table_name> as select column_name from <existing_table_name>; Ex: create table empl as select dept from emplo; 2. LOGICAL OPERATORS:-- a) AND Operator: AND operator is used to select the fields with Where clause for condition testing in SQL results only all the condition satisfies. Ex: select dob,emp_id from emp where name=’prasad’ and salary=15000; b) OR Operator: OR operator is used to select the fields with Where clause for condition testing in SQL results if either of the conditions satisfies. Ex: select * from emp where emp_id=123 or name=’prasad’; c )NOT Operator: NOT operator is used to select the fields with Where clause for condition testing in SQL. Ex: select name from emp where not salary=15000; 3. CHARACTORS FUNCTIONS:-- a) Initcap: -- It is used to display the characters in which the first letter is in Capital letter. Ex: select initcap(‘prasad’) from dual; Output: INITCA ------- Prasad c) LOWER (char):-- It is used to convert all capital lettered characters into small lettered characters in an SQL; Ex: select lower(‘PRASAD’) from dual; Output: LOWER( ------ prasad c) UPPER(char):-- It is used to convert all small lettered characters into capital lettered characters in an SQL; <SQL by Prasad>
  11. 11. 11 STRUCTURED QUERY LANGUAGE (SQL) Ex: select upper(prasad) from dual; Output: UPPER( ------ PRASAD d) LTRIM(char,set):-- Ex: select ltrim(xyz abc,xyz) from dual; Output: LTRI ---- abc e) RTRIM(char,set):--Ex: select rtrim(xyz abc,abc) from dual; Output: RTRI ---- xyz f) TRANSLATE(char,from to)_:-- This command is used to change the particular character into another character. In other words it replaces a old character to a new character.Ex: select translate(JACK,J,B) from dual; Output: TRAN ---- BACKFrom the above example the character ‘J’ is replaced by new character ‘B’ in theoutput.g) LENGTH Command:-- LENGTH Command is used to find the length of the given string in SQL. Ex: select length(‘prasad’) from dual; Output: LENGTH(PRASAD) <SQL by Prasad>
  12. 12. 12 STRUCTURED QUERY LANGUAGE (SQL) ---------------- 6 g) LIKE Command:-- This command is used to select the particular characters from the rows in SQL.Ex: select * from emplo;EMP_N NAME DEPT AGE SALARY----- -------------------- -------------------- --------- ---------101 Sathish.H HOD of CS 48 27000102 Prasad.babu HRD 25 2500099 Basavaraj Finance 24 19000110 Manoj.Kumar Marketing 22 24999234 Salim.Jafer Mess 23 21000123 kenchanagouda Mess 23 219996 rows selected.select * from emplo where dept like %ss;EMP_N NAME DEPT AGE SALARY----- -------------------- -------------------- --------- ---------234 Salim.Jafer Mess 23 21000123 kenchanagouda Mess 23 21999 ---: SET Operators: ---There are situations when we need to combine the results from two or more selectstatements. SQL enables us to handle these requirements by using SET operations.The result of each select statement can be treated as SET & SQL set operations canbe applied on those sets to arrive at a final result. SQL supports the following SEToperations.(1) UNION (2) UNION ALL (3) INTERSECT (4) MINUSSQL statements containing these set operations are called COMPOUND QUARIES.Two selects can be combined into a compound query by a set operation only of theysatisfies the following conditions: ---1) The result Set of both the queries must have the same number of columns. <SQL by Prasad>
  13. 13. 13 STRUCTURED QUERY LANGUAGE (SQL)2) The datatype of each column in the second result set must match the datatype ofits corresponding column in the first result set.These conditions are also referred to as “union compatibility” conditions. Thegeneral syntax of query involving set operation is: --<compound query> {union/union all/intersect/except} <compound query>;To explain the above example we can consider the following query.1) select customer_name from depositor;It displays the set of all customers who have an account at the bank. Wheredepositor is table name & customer_name is column name.Output:CUSTOMER_NAME---------------------Ashok MehraAjay Mehra depositor tablePrem DesaiRohit RoyNalini Deewan2) select customer_name from borrower;It displays the set of all customers who have loan at the bank. Where borrower istable name & customer_name is column name.Output:CUSTOMER_NAME--------------------Manish PatelPrem Desai borrower tableNitish KannaAshok MehraKiran Dixit**********************************************************************************************1) UNION OPERATION:The union operation combines the results of two select statements into one result se& them eliminates any duplicate rows from the result set.Syntax:(select customer_name from depositor) union (select customer_name fromborrower); <SQL by Prasad>
  14. 14. 14 STRUCTURED QUERY LANGUAGE (SQL)The OUTPUT is: --- CUSTOMER_NAME ------------------------- Ashok Mehra Ajay Mehra Prem Desai Rohit Roy Nalini Deewan Manish Patel Nitish Kanna Kiran DixitIt displayed the names of all the customers from both queries eliminating duplicaterows such as Ashok Mehra from both the queries.2) UNION ALL OPERATION:The union all operator returns all the rows selected by either query includingduplicates.Syntax:(select customer_name from depositor) union all (select customer_name fromborrower);The OUTPUT is: --- CUSTOMER_NAME ------------------------- Ashok Mehra Ajay Mehra Prem Desai Rohit Roy Nalini Deewan Manish Patel Prem Desai Nitish Kanna Ashok Mehra Kiran Dixit3) INTERSECT OPERATION:INTERSECT operator returns only rows that are common to both the queries.Syntax: <SQL by Prasad>
  15. 15. 15 STRUCTURED QUERY LANGUAGE (SQL)(select customer_name from depositor) intersect (select customer_name fromborrower);It displays the customer_names which are present in both the queries or tables. Output:-- CUSTOMER_NAME ----------------------------- Ashok Mehra Prem DesaiBy default intersect eliminates the duplicates. If we want to retain (display)duplicates we can use ‘intersect all’ instead of intersect.4) MINUS (EXCEPT) OPERATION:Except returns the rows from the first query that were not present in the record.Syntax:(select customer_name from depositor) minus (select customer_name fromborrower);It displays all the names of customers from the depositors table but not from theborrower table. Output: CUSTOMER_NAME ---------------------------- Ajay Mehra Rohit Roy Nalini DeewanBy default minus eliminates the duplicates. If we want to retain duplicates we canuse ‘minus all’ instead of ‘minus’.************************************************************************************ ********** SORTING (Order by Clause):The order by clause gives us a way of ordering the results. The data is ordered in theway we want it, not the way in which it was entered. The order by clause tells SQLthat we want the specified fields displayed in acending or descending order.Consider the table loan below,BRANCH_NAME AMOUNT----------------------- -------------Abids 7895Ameerpet 127 <SQL by Prasad>
  16. 16. 16 STRUCTURED QUERY LANGUAGE (SQL)Ameerpet 2810Koti 432Punjagutta 1234The above rows are obtained by following query,Select branch_name,amount from loan order by branch_name;We can observe the values of the rows which are displayed in ascending orderbecause by order by clause. We have given the column branch_name & by defaultorder by clause sorts the values in ascending order. For ascending order we mayspecify as ‘asc’ & fro descending order we may specify as ‘desc’ after column name.For example;Select branch_name,amount from loan order by branch_name desc;Output:BRANCH_NAME AMOUNT----------------------- --------------Punjagutta 1234Koti 432Ameerpet 2810Ameerpet 127Abids 7895When ordering the data, we can have multiple sort levelsSelect field_name1,field_name2,field_name3……… order byfield_name1<desc/asc> , field_name 2<desc/asc>, field_name3<desc/asc>………….;Explanation:  By default order by clause orders specified fields in ascending order.  Typing ‘desc’ after the field name in the order by clause tell SQL that we want data in the specified field displayed in descending order ( Z to A & 100 to 1)  The first field name is the primary sort order, the second field name is secondary sort order and so on………Ex: BRANCH_NAME AMOUNT----------------------- -------------Abids 7895Ameerpet 2810 <SQL by Prasad>
  17. 17. 17 STRUCTURED QUERY LANGUAGE (SQL)Ameerpet 127Koti 432Punjagutta 1234********************************************************************************************** BUILT IN FUNCTIONS (AGGRIGATE FUNCTIONS):These functions are also referred to as group functions. They returns a value basedon the values in the column. Aggregate functions perform functions like calculationson a set of values & returns a single value. Aggregate functions are often with thegroup clause of the select statement. All aggregate functions are determinates ,theyreturns the same value anytime they called with a given set of input values.  The select list of a select statement (either a sub query or a parent query)  A having clause.The distance between aggregate functions & normal functions is that aggregatefunctions use entire column of data as their input & produce a single output the‘normal’ operate on each element in the column of data.1) SUM: It returns the sum of all values or only distinct values in the expression sumcan be used with numeric values only. NULL values are ignored. It returns the sumof unique values.Ex: select sum(amount) from loan; Output: SUM(AM ------------ 124982) AVERAGE: The avg function computes the average of a column, NULL values areignored. To find the average of a amount in loan table the query will beEx: select avg(amount) from loan; Output: AVG(AM ---------- 2499.6 <SQL by Prasad>
  18. 18. 18 STRUCTURED QUERY LANGUAGE (SQL)3) MAX: It returns the maximum value in the expression. If we want to find thelargest value in a column, we use max function. To find the maximum amount in theloan relation (table) the query will be as follows,Ex: select max(amount) from loan; Output: MAX(AM ---------- 78954) MIN: It returns the minimum value in the expression. To find the minimumamount in the loan relation (table)the query will be as follows,Ex: select min(amount) from loan; Output: MIN(AM ---------- 1275) COUNT: The function count returns the numbers of rows in a table. To find thenumber of rows in the loan relation (table) the query will be as follows,Ex: select count (*) from loan; Output: COUNT(*) --------- 5********************************************************************************************** JOINS (Multi table queries):The process of forming rows from two or more tables by comparing the contents ofrelated columns are called joining tables. The resulting table is called a join betweenthe tables. The different types of joins that can be made between tables are asfollows.1) Simple join a) Equi join b) non-eque join2) Self join3) Outer join. <SQL by Prasad>
  19. 19. 19 STRUCTURED QUERY LANGUAGE (SQL)Joins are foundation of multi-table query processing in SQL.a) Equi joins: A join based on an exact match between two columns is called equijoins. This is because the comparison operator in the join condition is ‘=’ (equal).b) Non-equi joins: A non eque joins specify the relationship between columnsbelonging to different tables by making use of the relational operators (>, <, >=, <=,<>).2) Self joins: Joining of table itself is known as self join. In other words it joins onerow in table to another. It can compare each rows of the table to itself & also withthe rows of the same table.3) Outer joins: The outer joins extends the result of simple join. An outer joinreturns all the rows returned by simple join as well as those rows from one tablethat do not match any row from the other table. The symbol ‘+’ represent the outerjoin.********************************************************************************************** TABLE ALIASESTo prevent the ambiguity in a query we include table in the select statement. Tablealiases are used to make a multiple table queries shorter & more readable. As aresult , we give an alias to the table in the ‘from’ clause.The alias can be used instead of table name throughout the query.For example,Select e.dept_no, e.ename,d.dept_no,d.dname from emp e, dept.d wheree.dept_no=d.dept_no; The above example refers to the table alias, where ‘e’ refer to the table emp&‘d’ refer to the table dept.The aliases which are defined in the ‘from’ clause are separate from the table nameby space.********************************************************************************************** INDEXESAn Index is an ordered list of contents of a column or group of columns in a table. Anindex created on a single column of the table is called simple index. When multipletable columns are included in the index is called composite index.Creating the Index for a table: <SQL by Prasad>
  20. 20. 20 STRUCTURED QUERY LANGUAGE (SQL)Simple Index: CREATE INDEX index_file_name ON table_name(column_name);Ex; create index client_ndx on client_master(client_no);Composite Index: CREATE INDEX index_file_name ONtable_name(column_name1,column_name2….n);Ex: Create a composite index on the sales_order_details table for the columnss_order_no and product_no.Create index sales_order_details_ntx onsales_order_details(s_order_no,product_no);The index in the above examples do not enforce uniqueness i.e. the column includedin the index can have duplicate values. To create a unique index, the keywordUNIQUE should be included in the create index command.Syntax: CREATE UNIQUE INDEX index_file_name ON table_name(column_name);For example; create a unique index on table client_master, with the field client_no.SQL> CREATE UNIQUE INDEX client_ndx ON client_master(client_no);When the user defines a primary key or a unique key constraint, Oracleautomatically creates a unique indexes on the primary key column or unique key.Dropping Indexes: An Index can be dropped by the DROP Command.Syntax: DROP INDEX <index_file_name>;Ex: Drop index client_ndx on table client_master can be dropped by the followingquery.SQL> DROP INDEX client_no;When the user drops the primary key, unique key constraints or the table, Oracleautomatically drops the indexes on the primary key column, unique key or tableitself.********************************************************************************************** <SQL by Prasad>