imp sql commands

Upload: rajesh

Post on 30-May-2018

247 views

Category:

Documents


1 download

TRANSCRIPT

  • 8/9/2019 Imp SQL Commands

    1/36

    A table is uniquely identified by its name and consists of rows that contain thestored information, each row containing exactly one tuple (or record). A table canhave one or more columns. A column is made up of a column name and a datatype, and it describes an attribute of the tuples. The structure of a table, alsocalled relation schema, thus is defined by its attributes. The type of information to

    be stored in a table is defined by the data types of the attributes at table creationtime.

    SQL uses the terms table, row, and column for relation, tuple, and attribute,respectively. A table can have up to 254 columns which may have different orsame data types and sets of values (domains), respectively.

    Before creation of the database we will find out the Tables, Table attributes anddata types of the attributes. We will take the example of School ManagementSystem Database. This includes the details about the teachers, courses,students and marks.

    The following are SQL components:-

    1.DDL (Data Definition Language) :- DDL is used to define, modify and delete theschema (structure of the database objects).

    Examples: - CREATE, ALTER, DROP, TRUNCATE.

    2. DML (Data Manipulation Language):- DML is used to operate on the data in the

    database rather than the schema. The common operations are: Fetch the data according

    the user requirements and Insertion, Deletion and updating of the data. for example:-SELECT, INSERT, UPDATE, AND DELETE.

    3. DCL (Data Control Language):-DCL is used to give and take the data accesspermissions and rights to the different users.for example : - GRANT, REVOKE

  • 8/9/2019 Imp SQL Commands

    2/36

    Transaction control statements Transaction Control Statements are used to control the

    overall transaction of the data. for example : - SET TRANSACTION, COMMIT,ROLLBACK

    SQL Objects: An Overview

    Tables: - Tables are logical structures maintained by the database manager. Tables are

    made up of columns and rows. The rows are not necessarily ordered within a table (orderis determined by the application program). At the intersection of every column and row is

    a specific data item called a value. A column is a set of values of the same type or one of

    its subtypes. A row is a sequence of values arranged so that the nth value is a value of thenth column of the table.

    Views: - A view provides an alternative way of looking at the data in one or more tables.

    It is a named specification of a result table. The specification is a SELECT statement that

    is executed whenever the view is referenced in an SQL statement.

    Aliases: - An alias is an alternative name for a table or view. It can be used to reference atable or view in those cases where an existing table or view can be referenced. An alias

    cannot be used in all contexts. For example, it cannot be used in the check condition of acheck constraint.

    Indexes: - An index is an ordered set of pointers to rows of a base table. Each index is

    based on the values of data in one or more table columns. An index is an object that isseparate from the data in the table. When an index is created, the database manager builds

    this structure and maintains it automatically. Indexes are used by the database manager

    to: Improve performance. In most cases, access to data is faster than without an index. Anindex cannot be created for a view. However, an index created for a table on which aview is based can sometimes improve the performance of operations on the view. Ensure

    uniqueness. A table with a unique index cannot have rows with identical keys.

  • 8/9/2019 Imp SQL Commands

    3/36

    Queries: - A query is a component of certain SQL statements that specifies a (temporary)

    result table.

    The following are the data types used in SQL: -

    Character Data Types in SQL: -

    CHAR( size)[BYTE | CHAR]Fixed-length character data of length size bytes. Maximum

    size is 2000 bytes. Default and minimum size is 1 byte. BYTE and CHAR have the same

    semantics as for VARCHAR2.

    NCHAR( size) Fixed-length character data of length size characters. Maximum size is

    determined by the national character set definition, with an upper limit of 2000 bytes.

    Default and minimum size is 1 character.

    VARCHAR2( size) [BYTE | CHAR]Variable-length character string having maximum

    length size bytes or characters. Maximum size is 4000 bytes, and minimum is 1 byte or 1

    character. You must specify size for VARCHAR2. BYTE indicates that the column willhave byte length semantics; CHAR indicates that the column will have character

    semantics.

    NVARCHAR2( size) Variable-length character string having maximum length size

    characters. Maximum size is determined by the national character set definition, with anupper limit of 4000 bytes. You must specify size for NVARCHAR2.

    Numeric Data Types in SQL: -

    NUMBER( p,s) Number having precision p and scale s. The precision p can range from 1to 38. The scale s can range from -84 to 127.

  • 8/9/2019 Imp SQL Commands

    4/36

    LONGCharacter data of variable length up to 2 gigabytes, or 2 31 -1 bytes.

    Date, Time and Interval Data Types: -

    DATEValid date range from January 1, 4712 BC to December 31, 9999 AD. 180

    TIMESTAMP ( fractional_ seconds_precision)Year, month, and day values of date, as

    well as hour, minute, and second values of time, where fractional_seconds_precisionis

    the number of digits in the fractional part of the SECOND datetime field. Acceptedvalues of fractional_ seconds_precision are 0 to 9. The default is 6.

    TIMESTAMP ( fractional_ seconds_precision) WITH TIME ZONEAll values of

    TIMESTAMP as well as time zone displacement value, where fractional_seconds_precisionis the number of digits in the fractional part of the SECOND datetime

    field. Accepted values are 0 to 9. The default is 6. 231

    TIMESTAMP ( fractional_ seconds_precision) WITH LOCAL TIME ZONEAll values

    of TIMESTAMP WITH TIME ZONE, with the following exceptions: n Data isnormalized to the database time zone when it is stored in the database. n When the data is

    retrieved, users see the data in the session time zone.

    INTERVAL YEAR ( year_precision) TO MONTHStores a period of time in years andmonths, where year_precision is the number of digits in the YEAR datetime field.

    Accepted values are 0 to 9. The default is 2.

    INTERVAL DAY (day_ precision) TO SECOND ( fractional_ seconds_precision) Stores

    a period of time in days, hours, minutes, and seconds, where n day_precision is themaximum number of digits in the DAY datetime field. Accepted values are 0 to 9. The

    default is 2. n fractional_seconds_precision is the number of digits in the fractional part

    of the SECOND field. Accepted values are 0 to 9. The default is 6.

  • 8/9/2019 Imp SQL Commands

    5/36

    Raw and Long Raw Data Types: -

    RAW( size) Raw binary data of length size bytes. Maximum size is 2000 bytes. You must

    specify size for a RAW value.

    LONG RAWRaw binary data of variable length up to 2 gigabytes.

    RowID Data Types: -

    ROWIDBase 64 string representing the unique address of a row in its table. Thisdatatype is primarily for values returned by the ROWID pseudocolumn.

    UROWID [( size)]Base 64 string representing the logical address of a row of an index-

    organized table. The optional size is the size of a column of type UROWID. The

    maximum size and default is 4000 bytes.

    Large Object Data Types (LOB's): -

    CLOB A character large object containing single-byte characters. Both fixed-width and

    variable-width character sets are supported, both using the CHAR database character set.Maximum size is 4 gigabytes.

    NCLOB A character large object containing Unicode characters. Both fixed-width and

    variable-width character sets are supported, both using the NCHAR database character

    set. Maximum size is 4 gigabytes. Stores national character set data.

  • 8/9/2019 Imp SQL Commands

    6/36

    BLOB A binary large object. Maximum size is 4 gigabytes.

    BFILEContains a locator to a large binary file stored outside the database. Enables byte

    stream I/O access to external LOBs residing on the database server. Maximum size is 4gigabytes.

    CREATE TABLE: - It is used to create an empty table in the database.

    Syntax: -

    create table (

    [not null] [unique] [],

    . . . . . . . . .

    [not null] [unique] [],

    []

    );

    Examples: -

    Creation of Teacher Table: -

    create table Teacher (TeacherID Number(10) ,

    TeacherName Varchar2(30),

    Qualification Varchar2(30),Subject Varchar2(30),

    ContactNumber Number(10) );

    In the above example a table will be created with the name Teacher and TeacherID,TeacherName, Qualification, Subject and ContactNumber fields. This way we create all

    the tables discussed in the previous section

  • 8/9/2019 Imp SQL Commands

    7/36

    It is possible to modify the structure of a table (the relation schema) even if rowshave already been inserted into the table.

    Adding the Column to the Table: - A column can be added using the alter tablecommand. Following is the syntax for adding the column to the table.

    Syntax: - alter table add( data type [][]);

    If more than one column should be added at one time, respective add clauses

    need to be separated by colons.

    A table constraint can be added to a table using

    alter table add ();

    (Note that a column constraint is a table constraint, too. not null and primary keyconstraints can only be added to a table if none of the specified columns containsa null value.)

    Example: - Suppose you want to add a new column Contact_Number to theStudent table in the previous example.

    You can add the column using the following statement: -

    alter table Student add(Contact_Number Number(10));

  • 8/9/2019 Imp SQL Commands

    8/36

    Modifying the Column of the Table: - A column can be modified using the altertable command. Following is the command for modifying the column attributes: -

    Syntax: - alter table modify( [] [] []);

    Example: - If you want to change the size of TeacherName in the Teacher table.You can do it with the following statement:-

    alter table Teacher modify(TeacherName varchar2(35));

    Deleting a Table: - A table and its rows can be deleted by issuing the drop tablecommand. Following is the syntax for deleting a table.

    Syntax: - drop table table name [cascade constraints];

    Example: - If you want to delete the Marks table. You can delete it using thefollowing statement:-

    drop table Marks;

    Updating the Table: - For modifying attribute values of (some) tuples in a table, we use

    the update statement. The following is the syntax for Update:

    Syntax: - update set = , . . . , = [where ];

    An expression consists of either a constant (new value), an arithmetic or stringoperation, or an SQL query. Note that the new value to assign to column i mustbe the matching data type. An update statement without a where clause resultsin changing respective attributes of all tuples in the specified table. Typically,however, only a (small) portion of the table requires an update.

  • 8/9/2019 Imp SQL Commands

    9/36

    Constraints

    Constraints are the special elements of SQL which are used to enforce thestandards defined by the organization. The definition of a table may include thespecification of integrity constraints. There are two types of constraints:

    Column Constraints: - These are associated with a single column. However,any column constraint can also be formulated as a table constraint.

    Table Constraints: - These are associated with more than one column.

    Further Constraints can be divided as: -

    1. Integrity Constraints 2. Check Constraints 3. Foreign Key Constraints

    The specification of a constraint has the following form:

    [] primary key | unique | not null

    (A constraint can be named. It is advisable to name a constraint in order to getmore meaningful information when this constraint is violated due to, e.g., an

    insertion of a tuple that violates the constraint. The information will be providedwith the name of the constraints so that it is easier to find the violation.)

    Integrity Constraints: - We have three types of integrity constraints: not nullconstraints, primary keys, and unique constraints. Probably the most importanttype of integrity constraints in a database is primary key constraints. A primarykey constraint enables a unique identification of each tuple in a table. Based on aprimary key, the database system ensures that no duplicates appear in a table.

    Example:

    Check Constraints: - Often columns in a table must have values that are withina certain range or that satisfy certain conditions. Check constraints allow users torestrict possible attribute values for a column to admissible ones. They can bespecified as column constraints or table constraints. The syntax for a checkconstraint is

    [] check()

  • 8/9/2019 Imp SQL Commands

    10/36

    If a check constraint is specified as a column constraint, the condition can onlyrefer that column.

    Example:

    If a check constraint is specified as a table constraint, condition can refer to allcolumns of the table. It is not allowed to refer to columns of other tables or toformulate queries as check conditions. Furthermore, the functions sysdate anduser cannot be used in a condition. In principle, thus only simple attributecomparisons and logical connectives such as and, or, and not are allowed. Acheck condition, however, can include a not null constraint Example: Thedatabase system automatically checks the specified conditions each time adatabase modification is performed on this relation.

    Foreign Key Constraints: - A foreign key constraint (or referential integrityconstraint) can be specified as a column constraint or as a table constraint:

    [] [foreign key ()] references[()] [on delete cascade]

    This constraint specifies a column or a list of columns as a foreign key of thereferencing table. The referencing table is called the child-table, and thereferenced table is called the parent-table. In other words, one cannot define areferential integrity constraint that refers to a table R before that table R has beencreated. The clause foreign key has to be used in addition to the clausereferences if the foreign key includes more than one column. In this case, theconstraint has to be specified as a table constraint. The clause references

    defines which columns of the parent-table are referenced. If only the name of theparent-table is given, the list of attributes that build the primary key of that table isassumed.

    Example:

    In order to satisfy a foreign key constraint, each row in the child-table has tosatisfy one of the following two conditions: " The attribute value (list of attributevalues) of the foreign key must appear as a primary key value in the parent-table,or " The attribute value of the foreign key is null (in case of a composite foreignkey, at least one attribute value of the foreign key is null)

    Example:

    Disabling and Enabling Constraints: - If a constraint is defined within thecreate table command or added using the alter table command the constraint isautomatically enabled. A constraint can be disabled using the command

  • 8/9/2019 Imp SQL Commands

    11/36

    alter table disable | primary key |unique[] [cascade];

    To disable a primary key, one must disable all foreign key constraints thatdepend on this primary key. The clause cascade automatically disables foreign

    key constraints that depend on the (disabled) primary key.

    Example:

    In order to enable an integrity constraint, the clause enable is used instead ofdisable. A constraint can only be enabled successfully if no tuple in the tableviolates the constraint. Otherwise an error message is displayed. Note that forenabling/disabling an integrity constraint it is important that you have named theconstraints.

    INSERT INTO: - It is used to insert records in the table.

    Syntax: -

    insert into [()]values ();

    Examples: -

    Insert data in Teacher Table: -

    Insert into Teacher (TeacherID, TeacherName, Qualification, Subject,

    ContactNumber)Values(1, "Harris", "M.Sc. (Math)", "Math", 4235678);

    OR

    Insert into Teacher Values (1, "Harris", "M.Sc. (Math)", "Math", 4235678);

    In the above examples data will be inserted in the corresponding fields. And there will beone tuple (row) in the table. Similarly you can insert more tuples in the table. As you can

    see the components in the [ ] brackets are optional and we can insert the data without

    giving the attributes.

    Select: - Select is used to fetch the data from the tables in the database.

    Following is the syntax for using the select statement.

    Syntax: -

    SELECT FROM ;

  • 8/9/2019 Imp SQL Commands

    12/36

    Example: -If you want to see Teacher Name from the Teacher Table:-

    Select Teacher_Name from Teacher;

    The above query will fetch the names of all the teachers in the teacher table.

    To fetch all the details of the teachers we will use the following query: -

    Select * from Teacher;

    The above query will display all the details of the teachers. Here '*' refers to allthe columns.

    To fetch the details of more than one column (not all the columns), we will usedelimeter (,) between the column names.

    For example: -

    Select Teacher_Name, Qualification from Teacher; will display the TeacherNames and their qualifications.

    Where Clause: - Where clause is used to fetch the data according according tothe conditions given by the user with thehelp of operators. The following is the syntax for using where: -

    Syntax: -SELECT

    FROMWHERE

    Example: -If you want to see the ID of the students who secured percentage of marks equalto 65%.

    Select Student_ID from Marks where MarksPercentage = 65;Similarly we can use the different operators with where clause: -

    Select Student_ID from Marks where MarksPercentage > 65;

    Select Student_ID from Marks where MarksPercentage < 65;

    Select Student_ID from Marks where MarksPercentage < > 65;

    Order By: - It is used to fetch the data in the given order (Ascending orDescending).The following is the syntax for order by: -

  • 8/9/2019 Imp SQL Commands

    13/36

    Syntax: -SELECT FROM [WHERE ]ORDER BY [ASC, DESC]

    Example: -If you want to see the details of the students in ascending order according to thename.

    Select * from Student order by StudentName;

    In the above example we have not mentioned the type of the ordering becauseby default it is ascending order but forthe descending order we have to specify the order: -

    Select * from Student order by StudentName Desc; will display the data in the

    descending

    ORDER BY clause is used to order the data sets retrieved from a SQL database.The ordering of the selected data can be done by one or more columns in atable. If we want to sort our Users table by the FirstName column, we'll have touse the following ORDER BY SQL statement:

    SELECT * FROM Users ORDER BY FirstName;

    The result of the ORDER BY statement above will be the following:

    FirstName LastName DateOfBirth Email City

    David Stonewall 01/03/1954 [email protected]

    Francisco

    John Smith 12/12/1969john.smith@john-

    here.comNew York

    Paul O'Neil 09/17/1982paul.oneil@pauls-

    email.comNew York

    Stephen Grant 03/03/1974 [email protected]

    Susan Grant 03/03/1970

    susan.grant@sql-

    tutorial.com

    Los

    Angeles

    As you can see the rows are ordered alphabetically by the FirstName column.You can use ORDER BY to order the retrieved data by more than one column.For example, if you want to order by both LastName and City columns, youwould do it with the following ORDER BY statement:

  • 8/9/2019 Imp SQL Commands

    14/36

    SELECT * FROM Users ORDER BY LastName, DateOfBirth;

    Here is the result of this ORDER BY statement:

    FirstName

    LastName DateOfBirth Email City

    Susan Grant 03/03/1970susan.grant@sql-

    tutorial.com

    Los

    Angeles

    Stephen Grant 03/03/1974 [email protected]

    Angeles

    Paul O'Neil 09/17/1982paul.oneil@pauls-

    email.com

    New York

    John Smith 12/12/1969john.smith@john-

    here.comNew York

    David Stonewall 01/03/1954 [email protected]

    Francisco

    When using ORDER BY with more than one column, you need to separate thelist of columns following ORDER BY with commas. What will happen if wereverse the order of the columns specified after the ORDER BY statement like inthe statement below?

    SELECT * FROM Users ORDER BY DateOfBirth, LastName;

    This ORDER BY statement will return the same results as the one with thereversed columns order, but they will be ordered differently. Here is the result:

    FirstName LastName DateOfBirth Email City

    David Stonewall 01/03/1954 [email protected]

    Francisco

    John Smith 12/12/[email protected]

    New York

    Susan Grant 03/03/1970susan.grant@sql-

    tutorial.com

    Los

    Angeles

    Stephen Grant 03/03/1974 [email protected]

    Angeles

    Paul O'Neil 09/17/1982paul.oneil@pauls-

    email.comNew York

  • 8/9/2019 Imp SQL Commands

    15/36

    The ORDER BY clause first sorts the retrieved data by the first column, then thenext one, and so forth. In all the ORDER BY examples so far, we were sortingalphabetically for character columns (FirstName, LastName) and from earlier to

    later date for the DateOfBirth column. What do we do if we want to order our dataalphabetically but this time backwards? In order to accomplish that we need touse the DESC SQL keyword:

    SELECT * FROM Users ORDER BY FirstName DESC;

    Here is the result:

    FirstName LastName DateOfBirth Email City

    Susan Grant 03/03/1970susan.grant@sql-

    tutorial.com

    Los

    Angeles

    Stephen Grant 03/03/1974 [email protected]

    Paul O'Neil 09/17/1982paul.oneil@pauls-

    email.comNew York

    John Smith 12/12/1969john.smith@john-

    here.comNew York

    David Stonewall 01/03/1954 [email protected]

    CONCAT: - It returns char1 concatenated with char2. Both char1 and char2 can be any

    of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.

    The string returned is in the same character set as char1. Its datatype depends on thedatatypes of the arguments. In concatenations of two different datatypes, Oracle returns

    the datatype that results in a lossless conversion.

    Example: - This example uses nesting to concatenate three character strings:

    SELECT CONCAT(CONCAT(last_name, '''s job category is '), job_id) "Job" FROMemployees WHERE employee_id = 152;

    Job

    ------------------------------------------------------

    Hall's job category is SA_REP

  • 8/9/2019 Imp SQL Commands

    16/36

    INITCAP: - It returns char, with the first letter of each word in uppercase, all other

    letters in lowercase. Words are delimited by white space or characters that are not

    alphanumeric. char can be of any of the datatypes CHAR, VARCHAR2, NCHAR, orNVARCHAR2. The return value is the same datatype as char.

    Example: - The following example capitalizes each word in the string: SELECTINITCAP(the soap) "Capitals" FROM DUAL;

    Capitals

    ---------

    The Soap

    Note: This function does not support CLOB data directly. However, CLOBs can bepassed in as arguments through implicit data conversion.

    LOWER: - It returns char, with all letters lowercase. char can be any of the datatypesCHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is

    the same datatype as char.

    Example: - The following example returns a string in lowercase: SELECT

    LOWER(MR. SCOTT MCMILLAN) "Lowercase" FROM DUAL; Lowercase

    --------------------

    mr. scott mcmillan

    LPAD: - It returns char1, left-padded to length n with the sequence of characters in

    char2; char2 defaults to a single blank. If char1 is longer than n, then this function returns

    the portion of char1 that fits in n. Both char1 and char2 can be any of the datatypesCHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned

    is of VARCHAR2 datatype and is in the same character set as char1. The argument n is

    the total length of the return value as it is displayed on your terminal screen.

    Example: - The following example left-pads a string with the characters "*" and ".":

    SELECT LPAD(Page 1,15,*.) from dual;

    LTRIM: - It removes characters from the left of char, with all the leftmost characters that

    appear in set removed; set defaults to a single blank. If char is a character literal, then you

    must enclose it in single quotes. Oracle begins scanning char from its first character andremoves all characters that appear in set until reaching a character not in set and then

    returns the result. Both char and set can be any of the datatypes CHAR, VARCHAR2,

  • 8/9/2019 Imp SQL Commands

    17/36

    NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2

    datatype and is in the same character set as char.

    Example: - The following example trims all of the left-most xs and ys from a string:

    SELECT LTRIM(xyxXxyLAST WORD,xy) "LTRIM example" FROM DUAL;

    LTRIM example

    ------------

    XxyLAST WORD

    REPLACE: - It returns char with every occurrence of search_string replaced with

    replacement_string. If replacement_string is omitted or null, then all occurrences of

    search_string are removed. If search_string is null, then char is returned. Both

    search_string and replacement_string, as well as char, can be any of the datatypes CHAR,VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of

    VARCHAR2 datatype and is in the same character set as char. REPLACE lets yousubstitute one string for another as well as to remove character strings.

    Example: - The following example replaces occurrences of "J" with "BL":

    SELECT REPLACE(JACK and JUE,J,BL) "Changes" FROM DUAL;

    Changes

    --------------

    BLACK and BLUE

    RPAD: - It returns char1, right-padded to length n with char2, replicated as many times

    as necessary; char2 defaults to a single blank. If char1 is longer than n, then this function

    returns the portion of char1 that fits in n. Both char1 and char2 can be any of the

    datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. Thestring returned is of VARCHAR2 datatype and is in the same character set as char1. The

    argument n is the total length of the return value as it is displayed on your terminal

    screen. In most character sets, this is also the number of characters in the return value.

    Example: - The following example right-pads a name with the letters "ab" until it is 12characters long:

    SELECT RPAD(MORRISON,12,ab) "RPAD example" FROM DUAL;

    RPAD example

  • 8/9/2019 Imp SQL Commands

    18/36

    -----------------

    MORRISONabab

    RTRIM: - It returns char, with all the rightmost characters that appear in set removed;

    setdefaults to a single blank. If char is a character literal, then you must enclose it insingle quotes. RTRIM works similarly to LTRIM. Both char and set can be any of the

    datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The

    string returned is of VARCHAR2 datatype and is in the same character set as char.

    Example: - The following example trims the letters "xy" from the right side of a string:

    SELECT RTRIM(BROWNINGyxXxy,xy) "RTRIM example" FROM DUAL;

    RTRIM examp

    -----------

    BROWNINGyxX

    SUBSTR: - The "substring" functions return a portion of string, beginning at characterposition, substring_length characters long. SUBSTR calculates lengths using characters

    as defined by the input character set. string can be any of the datatypes CHAR,

    VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is the same

    datatype as string. Floating-point numbers passed as arguments to SUBSTR are

    automatically converted to integers.

    Example: - The following example returns several specified substrings of "ABCDEFG":

    SELECT SUBSTR(ABCDEFG,3,4) "Substring" FROM DUAL;

    Substring

    ---------

    CDEF

    SELECT SUBSTR(ABCDEFG,-5,4) "Substring" FROM DUAL;

    Substring

    ---------

    CDEF

  • 8/9/2019 Imp SQL Commands

    19/36

    TRIM: - It enables you to trim leading or trailing characters (or both) from a character

    string. If trim_character or trim_source is a character literal, then you must enclose it in

    single quotes. Both trim_character and trim_source can be any of the datatypes CHAR,VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of

    VARCHAR2 datatype and is in the same character set as trim_source.

    Example: - This example trims leading and trailing zeroes from a number:

    SELECT TRIM (0 FROM 0009872348900) "TRIM Example" FROM DUAL;

    TRIM Example

    ------------

    98723489

    UPPER: - It returns char, with all letters uppercase. char can be any of the datatypesCHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is

    the same datatype as char.

    Example: - The following example returns a string in uppercase:

    SELECT UPPER(Large) "Uppercase" FROM DUAL;

    Uppercase

    -----

    LARGE

    INSTR: - The "in string" functions search string for substring. The function returns aninteger indicating the position of the character in string that is the first character. INSTR

    calculates strings using characters as defined by the input character set. Both string and

    substring can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2,

    CLOB, or NCLOB. The value returned is of NUMBER datatype. The default values ofboth position and occurrence are 1, meaning Oracle begins searching at the first character

    of string for the first occurrence of substring. The return value is relative to the beginning

    of string, regardless of the value of position, and is expressed in characters. If the search

    is unsuccessful (if substring does not appear occurrence times after the position characterof string), then the return value is 0.

    Example: - The following example searches the string "CORPORATE FLOOR",

    beginning with the third character, for the string "OR". It returns the position inCORPORATE FLOOR at which the second occurrence of "OR" begins:

    SELECT INSTR(CORPORATE FLOOR,OR, 3, 2) "Instring" FROM DUAL;

  • 8/9/2019 Imp SQL Commands

    20/36

    Instring

    ----------

    14

    LENGTH: - The "length" functions return the length of char. LENGTH calculates length

    using characters as defined by the input character set. char can be any of the datatypesCHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is

    of datatype NUMBER. If char has datatype CHAR, then the length includes all trailing

    blanks. If char is null, then this function returns null.

    Example: - The following example uses the LENGTH function using a single-byte

    database character set.

    SELECT LENGTH(CANDIDE) "Length in characters" FROM DUAL;

    Length in characters

    --------------------

    7

    The SQL AND clause is used when you want to specify more than one conditionin your SQL WHERE clause, and at the same time you want all conditions to betrue. For example if you want to select all customers with FirstName "John" andLastName "Smith", you will use the following SQL expression:

    SELECT * FROM Customers WHERE FirstName = 'John' AND LastName ='Smith'

    The result of the SQL query above is:

    FirstName LastName Email DOB Phone

    John Smith [email protected] 2/4/1968 626 222-2222

    The following row in our Customer table, satisfies the second of the conditions(LastName = 'Smith'), but not the first one (FirstName = 'John'), and that's whyit's not returned by our SQL query:

    FirstName LastName Email DOB Phone

    James Smith [email protected] 20/10/1980 416 323-8888

  • 8/9/2019 Imp SQL Commands

    21/36

    SQL OR

    The SQL OR statement is used in similar fashion and the major differencecompared to the SQL AND is that OR clause will return all rows satisfying any ofthe conditions listed in the WHERE clause. If we want to select all customers

    having FirstName 'James' or FirstName 'Paula' we need to use the following SQLstatement:

    SELECT * FROM Customers WHERE FirstName = 'James' OR FirstName ='Paula';

    The result of this query will be the following:

    FirstName LastName Email DOB Phone

    Paula Brown [email protected] 5/24/1978416 323-

    3232

    James Smith [email protected] 20/10/1980416 323-8888

    You can combine AND and OR clauses anyway you want and you can useparentheses to define your logical expressions. Here is an example of such aSQL query, selecting all customers with LastName 'Brown' and FirstName either'James' or 'Paula':

    SELECT * FROM Customers WHERE (FirstName = 'James' OR FirstName ='Paula') AND LastName = 'Brown';

    The result of the SQL expression above will be:

    FirstName LastName Email DOB Phone

    Paula Brown [email protected] 5/24/1978 416 323-3232

    SQL IN

    The SQL IN clause allows you to specify discrete values in your SQL WHEREsearch criteria. THE SQL IN syntax looks like this:

    SELECT Column1, Column2, Column3, FROM Table1 WHERE Column1 IN(Valu1, Value2, ) ;

    Lets use the EmployeeHours table to illustrate how SQL IN works:

    Employee Date Hours

  • 8/9/2019 Imp SQL Commands

    22/36

    John Smith 5/6/2004 8

    Allan Babel 5/6/2004 8

    Tina Crown 5/6/2004 8

    John Smith 5/7/2004 9

    Allan Babel 5/7/2004 8

    Tina Crown 5/7/2004 10

    John Smith 5/8/2004 8

    Allan Babel 5/8/2004 8

    Tina Crown 5/8/2004 9

    Consider the following SQL query using the SQL IN clause:

    SELECT * FROM EmployeeHours WHERE Date IN ('5/6/2004', '5/7/2004');

    This SQL expression will select only the entries where the column Date hasvalue of '5/6/2004' or '5/7/2004', and you can see the result below:

    Employee Date Hours

    John Smith 5/6/2004 8

    Allan Babel 5/6/2004 8

    Tina Crown 5/6/2004 8

    John Smith 5/7/2004 9

    Allan Babel 5/7/2004 8

    Tina Crown 5/7/2004 10

    We can use the SQL IN statement with another column in our EmployeeHourstable:

    SELECT * FROM EmployeeHours WHERE Hours IN (9, 10);

    The result of the SQL query above will be:

    Employee Date Hours

    John Smith 5/7/2004 9

    Tina Crown 5/7/2004 10

    Tina Crown 5/8/2004 9

    SQL BETWEEN

  • 8/9/2019 Imp SQL Commands

    23/36

    The SQL BETWEEN keyword define a range of data between 2 values. The SQLBETWEEN syntax looks like this:

    SELECT Column1, Column2, Column3, FROM Table1 WHERE Column1BETWEEN Value1 AND Value2 ;

    The values defining the range for SQL BETWEEN clause can be dates, numbersor just text. It gives you the ability to specify a range in your search criteria. Weare going to use the Customers table to show how SQL BETWEEN works:

    FirstName LastName Email DOB Phone

    John Smith [email protected] 2/4/1968626 222-2222

    Steven Goldfish [email protected] 4/4/1974323 455-

    4545

    Paula Brown [email protected] 5/24/1978 416 323-3232

    James Smith [email protected] 20/10/1980416 323-

    8888

    Consider the following SQL BETWEEN statement:

    SELECT * FROM Customers WHERE DOB BETWEEN '1/1/1975' AND'1/1/2004' ;

    The SQL BETWEEN statement above will select all Customers having DOB

    column between '1/1/1975' and '1/1/2004' dates. Here is the result of this SQLexpression:

    FirstName LastName Email DOB Phone

    Paula Brown [email protected] 5/24/1978416 323-

    3232

    James Smith [email protected] 20/10/1980416 323-8888

    ABS: - It returns the absolute value of n.

    Syntax:: - ABS ( n )

    Example: - The following example returns the absolute value of -15:

    SELECT ABS(-15) "Absolute" FROM DUAL;

  • 8/9/2019 Imp SQL Commands

    24/36

    Absolute

    ----------

    15

    ACOS: - It returns the arc cosine of n. The argument nmust be in the range of -1 to 1, and

    the function returns values in the range of 0 to p, expressed in radians.

    Syntax: - ACOS ( n )

    Example: - The following example returns the arc cosine of .3:

    SELECT ACOS(.3) "Arc_Cosine" FROM DUAL;

    Arc_Cosine

    ----------

    1.26610367

    ASIN: - It returns the arc sine of n. The argument n must be in the range of -1 to 1, andthe function returns values in the range of -p/2 to p/2 and are expressed in radians.

    Syntax: - ASIN ( n )

    Example: - The following example returns the arc sine of .3:

    SELECT ASIN(.3) "Arc_Sine" FROM DUAL;

    Arc_Sine

    ---------- .

    304692654

    ATAN: - It returns the arc tangent of n. The argument n can be in an unbounded range,

    and the function returns values in the range of -p/2 to p/2 and are expressed in radians.

    Syntax: - ATAN ( n )

    Example: - The following example returns the arc tangent of .3:

    SELECT ATAN(.3) "Arc_Tangent" FROM DUAL;

  • 8/9/2019 Imp SQL Commands

    25/36

    Arc_Tangent

    ---------- .

    291456794

    CEIL: - It returns smallest integer greater than or equal to n.

    Syntax: - CEIL ( n )

    Example: - The following example returns the smallest integer greater than or equal to15.7:

    SELECT CEIL(15.7) "Ceiling" FROM DUAL;

    Ceiling

    ----------

    16

    COS: - It returns the cosine of n (an angle expressed in radians).

    Syntax: - COS ( n )

    Example: - The following example returns the cosine of 180 degrees:

    SELECT COS(180 * 3.14159265359/180) "Cosine of 180 degrees" FROM DUAL;

    Cosine of 180 degrees

    ---------------------

    -1

    EXP: - It returns e raised to the nth power, where e = 2.71828183 ...

    Syntax: - EXP ( n )

    Example: - The following example returns e to the 4th power:

    SELECT EXP(4) "e to the 4th power" FROM DUAL;

    e to the 4th power

    ------------------

  • 8/9/2019 Imp SQL Commands

    26/36

    54.59815

    FLOOR: - It returns largest integer equal to or less than n.

    Syntax: - FLOOR ( n )

    Example: - The following example returns the largest integer equal to or less than 15.7:

    SELECT FLOOR(15.7) "Floor" FROM DUAL;

    Floor

    ----------

    15

    POWER: - It returns m raised to the nth power. The base m and the exponent n can beany numbers, but if m is negative, then n must be an integer.

    Syntax: - POWER ( m , n )

    Example: - The following example returns 3 squared:

    SELECT POWER(3,2) "Raised" FROM DUAL;

    Raised

    ----------

    9

    ROUND (number): - It returns number rounded to integer places right of the decimal

    point. If integer is omitted, then number is rounded to 0 places. integer can be negative toround off digits left of the decimal point. integer must be an integer.

    Syntax: - ROUND ( number , integer )

    Example: - The following example rounds a number to one decimal point:

    SELECT ROUND(15.193,1) "Round" FROM DUAL;

    Round

    ----------

    15.2

  • 8/9/2019 Imp SQL Commands

    27/36

    The following example rounds a number one digit to the left of the decimal point:

    SELECT ROUND(15.193,-1) "Round" FROM DUAL;

    Round

    ----------

    20

    SIGN: - It returns -1 if n0, then SIGNreturns 1.

    Syntax: - SIGN ( n )

    Example: - The following example indicates that the functions argument (-15) is

  • 8/9/2019 Imp SQL Commands

    28/36

    SELECT SQRT(26) "Square root" FROM DUAL;

    Square root

    -----------

    5.09901951

    TAN: - It returns the tangent of n (an angle expressed in radians).

    Syntax: - TAN ( n )

    Example: - The following example returns the tangent of 135 degrees:

    SELECT TAN(135 * 3.14159265359/180) "Tangent of 135 degrees" FROM DUAL;

    Tangent of 135 degrees

    ----------------------

    - 1

    TRUNC (number): - The TRUNC (number) function returns n truncated to m decimalplaces. If m is omitted, then n is truncated to 0 places. m can be negative to truncate

    (make zero) m digits left of the decimal point.

    Syntax: - TRUNC ( n , m )

    Example: - The following example truncate numbers:

    SELECT TRUNC(15.79,1) "Truncate" FROM DUAL;

    Truncate

    ----------

    15.7

    SELECT TRUNC(15.79,-1) "Truncate" FROM DUAL;

    Truncate

    ----------

    10

  • 8/9/2019 Imp SQL Commands

    29/36

    Subqueries are similar to SELECT chaining. While SELECT chaining combinesSELECTs on the same level in a query, however, subqueries allow SELECTs tobe embedded inside other queries:

    They can take the place of a constant 20 (Scalar Subqueries),

    They can return a list of values for use in a comparison.They can take the place of a constant yet vary based on the row beingprocessed,

    Subqueries are used in the following subquery expressions which return Boolean(true/false) results.

    EXISTS ( subquery )

    The argument of EXISTS is an arbitrary SELECT statement. The subquery isevaluated to determine whether it returns any rows. If it returns at least one row,

    the result of EXISTS is TRUE; if the subquery returns no rows, the result ofEXISTS is FALSE.

    The subquery can refer to variables from the surrounding query, which will act asconstants during any one evaluation of the subquery.

    This simple example is like an inner join on col2, but it produces at most oneoutput row for each tab1 row, even if there are multiple matching tab2 rows:

    SELECT col1 FROM tab1 WHERE EXISTS(SELECT 1 FROM tab2 WHERE col2= tab1.col2);

    Example "Students in Projects":

    SELECT name FROM stud WHERE EXISTS( SELECT 1 FROM assign WHEREstud = stud.id ) ;

    name

    ------

    fred

    john

    lisa

    [ NOT ] IN

  • 8/9/2019 Imp SQL Commands

    30/36

    IN [ NOT ] (scalar form) expression IN = (value[, ...]) The right-hand side of thisform of IN is a parenthesized list of scalar expressions. The result is TRUE if theleft-hand expression's result is equal to any of the right-hand expressions.

    IN [ NOT ] (subquery form) expression IN (subquery) The right-hand side of thisform of IN is a parenthesized subquery, which must return exactly one column.The left-hand expression is evaluated and compared to each row of the subqueryresult. The result of IN is TRUE if any equal subquery row is found.

    Example "Is fred in Project 1? (--Yes)":

    SELECT id, name FROM = stud WHERE id in ( SELECT stud FROM assignWHERE id = 1 ) ;

    id | name

    ----+------

    1 | fred

    ANY and SOME

    expression operator ANY (subquery) expression operator SOME (subquery) Theright-hand side of this form of ANY is a parenthesized subquery, which mustreturn exactly one column. The left-hand expression is evaluated and compared

    to each row of the subquery result using the given operator, which must yield aBoolean result. The result of ANY is TRUE if any true result is obtained.

    SOME is a synonym for ANY.

    ALL

    expression operator ALL (subquery) The right-hand side of this form of ALL is aparenthesized subquery, which must return exactly one column. The left-handexpression is evaluated and compared to each row of the subquery result usingthe given operator, which must yield a Boolean result. The result of ALL is TRUE

    if all rows yield TRUE (including the special case where the subquery returns norows).

    NOT IN is equivalent to ALL.

    Views

  • 8/9/2019 Imp SQL Commands

    31/36

    In SQL, a VIEW is a virtual table based on the result-set of a SELECT statement.A view contains rows and columns, just like a real table. The fields in a view arefields from one or more real tables in the database. You can add SQL functions,WHERE, and JOIN statements to a view and present the data as if the data werecoming from a single table.

    Note: The database design and structure will NOT be affected by the functions,where, or join statements in a view.

    Syntax: -

    CREATE VIEW view_name AS SELECT column_name(s) FROM table_nameWHERE condition

    Note: The database does not store the view data! The database engine recreatesthe data, using the view's SELECT statement, every time a user queries a view.

    Using Views

    A view could be used from inside a query, a stored procedure, or from insideanother view. By adding functions, joins, etc., to a view, it allows you to presentexactly the data you want to the user. The sample database Northwind has someviews installed by default. The view "Current Product List" lists all active products(products that are not discontinued) from the Products table. The view is createdwith the following SQL:

    CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName

    FROM Products WHERE Discontinued=No

    We can query the view above as follows:

    SELECT * FROM [Current Product List]

    Another view from the Northwind sample database selects every product in theProducts table that has a unit price that is higher than the average unit price:

    CREATE VIEW [Products Above Average Price] AS SELECTProductName,UnitPrice FROM Products WHERE UnitPrice>(SELECT

    AVG(UnitPrice) FROM Products)

    We can query the view above as follows:

    SELECT * FROM [Products Above Average Price]

  • 8/9/2019 Imp SQL Commands

    32/36

    Another example view from the Northwind database calculates the total sale foreach category in 1997. Note that this view selects its data from another viewcalled "Product Sales for 1997":

    CREATE VIEW [Category Sales For 1997] AS SELECT DISTINCT

    CategoryName,Sum(ProductSales) AS CategorySales FROM [Product Sales for1997] GROUP BY CategoryName

    We can query the view above as follows:

    SELECT * FROM [Category Sales For 1997] We can also add a condition to thequery.

    Now we want to see the total sale only for the category "Beverages":

    SELECT * FROM [Category Sales For 1997] WHERE

    CategoryName='Beverages'

    Alter Table Statement

    The ALTER TABLE statement is used to add, delete, or modify columns in an existingtable.

    The alter statement can be used for one of the following reasons:

    1. A column needs some particular constraint or a constraint on a column needs

    to be dropped.2. Data Type or Size of a column needs to be changed.3. A column name of a table needs to be changed or table name itself needs to

    be changed.4. Some columns need to be dropped or added to the table.

    Here we cant drop the table because the table is already loaded and its data isreferred by some other object.

    To overcome these issues alter table command is useful. Before looking into thoseAlter table commands let us first create one test table namely employee.

    Create a Dummy Table i.e. Employee

    CREATE TABLE employee ( EMP_ID NUMBER ,EMPLOYEE_NAMEVARCHAR2(30)

    ,AGE NUMBER ,SALARY NUMBER(5) ,JOB_TITLE VARCHAR2(30)

    );

  • 8/9/2019 Imp SQL Commands

    33/36

    Insert Records into Dummy Table i.e. Employee

    INSERT INTO employee VALUES(101,'John',25,20000,'Marketing Executive') ;

    INSERT INTO employee VALUES(102,'Smith',28,12000,'Service Technician') ;

    INSERT INTO employee VALUES(103,'Jackson',23,15000,'Manager') ;

    INSERT INTO employee VALUES(104,'Scott',30,11000,'Developer') ;

    INSERT INTO employee VALUES(105,'Herison',26,13000,'Purchage Officer') ;

    Select * from employee;

    Fetch the Data from Dummy Table i.e. Employee

    EMP_ID EMPLOYEE_NAME AGE SALARY JOB_TITLE

    105 Harrison 26 13,000 Purchase Officer

    104 Scott 30 11,000 Developer

    103 Jackson 23 15,000 Manager

    102 Smith 28 12,000 Service Te

    101 John 25 20,000 Executive

  • 8/9/2019 Imp SQL Commands

    34/36

    [-] To add a constraint to a table column

    Syntax: ALTER TABLE MODIFY ;

    Example ALTER TABLE employee MODIFY emp_id NOT NULL;

    [-] To drop a constraint on a table column

    Syntax: ALTER TABLE DROP CONSTRAINT ;

    (without quotes)

    Example: ALTER TABLE employee DROP CONSTRAINT SYSC120000;

    Note:

    1. All the system defined constraints starts with 'SYS_.'.

    2. If constraint name is not known then first find out the name ofconstraint on a column.

    Syntax:

    SELECT * FROM all_constraints WHERE table_name =UPPER(&table_name)

    Example:

    SELECT * FROM all_constraints WHERE table_name =UPPER('employee') ;

    [-] To drop a column from a table

    Syntax: ALTER TABLE

    DROP () ;

    Example:

    ALTER TABLE employee DROP (emp_name, emp_address) ;

    [-] To add a new column to a table

    Syntax: ALTER TABLE ADD ;

    Example: ALTER TABLE employee ADD emp_name VARCHAR2(15) ;

    [-] To change the column name of a table

  • 8/9/2019 Imp SQL Commands

    35/36

    Syntax: ALTER TABLE

    RENAME COLUMN TO ;

    Example:

    ALTER TABLE employee RENAME COLUMN emp_id TO employee_id ;

    [-] To rename an existing table name

    Syntax: RENAME TO ;

    Example: RENAME employee TO employee1;

    There is one more syntax for this

    Syntax: ALTER TABLE RENAME TO ;

    Example: ALTER TABLE employee RENAME TO employee1;

    [-] To change the data type of a column

    Syntax: ALTER TABLE

    MODIFY ;

    Example: ALTER TABLE employee MODIFY employee_name VARCHAR2(20) ;

    Note:

    1. DATA TYPE of a column can not be changed until the column is having valuespopulated i.e. to change the DATA TYPE column should not have NULL valuesfor all the records

    2. Column SIZE always can be reduced to the maximum size of data present inthat column.

    3. There is no restriction on increase in SIZE of a column.

    Joins

    Joins are used to retrieve data from two or more tables with relevant conditions whichuses the primary key for the table for referencing. Join operation takes two tables as

    input and return another table as output. When ever we perform a JOIN, we mustspecify one column that is common in both the tables that are participating in the

    JOIN. Here we can use multiple joins in the same SQL statement to query data fromas many tables as we like to join.

    The join return rows when there is at least one match i.e. column in the participatedtables.

    There are 4 types of Joins

  • 8/9/2019 Imp SQL Commands

    36/36

    1] Inner Join

    2] Outer Join

    2.1] Left Outer Join

    2.2] Right Outer Join

    2.3] Full Outer Join

    3] Cartesian Join

    4] Self Join