+ All Categories
Home > Documents > Dbms LabManual 14-15

Dbms LabManual 14-15

Date post: 15-Nov-2015
Category:
Upload: nikita-pawar
View: 7 times
Download: 1 times
Share this document with a friend
26
Saraswati College Of Engineering Computer Engg. Dept. S.E.IV[DBMS]Page 1 Saraswati College Of Engineering, Kharghar Department of Computer Engineering S.E. Database Management Systems(DBMS) -:Lab Manual:- SCOE’s Saraswati College Of Engineering, Kharghar Computer Department
Transcript
  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 1

    Saraswati College Of Engineering, Kharghar

    Department of Computer Engineering

    S.E.

    Database Management

    Systems(DBMS)

    -:Lab Manual:-

    SCOEs

    Saraswati College Of Engineering, Kharghar

    Computer Department

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 2

    Saraswati College of Engineering

    Department of Computer Engineering

    Vision:

    To imprint knowledge to our students in an ambience of knowledge, creativity and

    innovations and nurture them to become ethically rich professional with bright future.

    Mission:

    We believe in bonding and belonging thereby our mission is to provide simulating

    learning environment with a technological orientation to maximize individual

    potential.

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 3

    SARASWATI COLLEGE OF ENGINEERING

    COMPUTER ENGINEERING DEPARTMENT

    Subject :Database Management Systems (DBMS) Class/Sem : SE/IV

    Name of the Laboratory : Engg. Lab Year : 2014-15

    LIST OF EXPERIMENTS

    Experiment

    No. Name of the Experiment

    1. Introduction of Oracle and Basic SQL statement

    2. To study and Perform practical by using restricting sorting conditions and single row functions.

    3. To study and perform practical by multiple tables and group function.

    4. To study and perform practical by using sub queries and commands

    5. To study & perform practical by using DML statement and control transaction.

    6. To study & perform practical by using DDL statement(creating and managing tables constraints)

    7. To study & perform practical by using views& indexes concept.

    8. To study & perform practical by using set operations.

    9. To study & perform practical by using Group By Clause

    H/W Requirement P I and above, RAM 128MB, Printer, Cartridges

    S/W Requirement Oracle 9i-SQL plus

    Subject-Incharge H.O.D.

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 4

    EXPERIMENT NO. 1

    INRODUCTION OF ORACLE AND BASIC SQL STMT

    Aim : To study and perform practical by using basic SQL stmts.

    Resources

    Required

    : Oracle 9i-Sql plus

    Consumables Printer Pages for printouts.

    Theory :

    SQL consist of 2 models

    1. Introduction to Oracle 9i:SQL Basics

    2. Oracle 9i:Advanced SQL

    Oracle 9i features

    Database performance

    Ease of Management

    Scalability

    Availability

    Internet content management

    E-commerce integration

    There are 2 products

    1.Oracle 9i application server

    2.Oracle 9i Database (stores all data)

    SQL[Structured Query Language]:

    1. It is a language for communicating with Oracle Server to access data.

    2. It manipulates data and table definitions in the database.

    1. Rules for SQL

    1. SQL starts with a verb.Example:SELECT stmts.

    2. Each verb is followed by number of clauses.

    Example:FROM,WHERE,HAVING

    3. A Space separates clauses. Example: DROP TABLE EMP;

    4. A; is used to end the SQL stmts

    2.Domain types in SQL-

    - Char (n)- A fixed length character length string with user specified length . Varchar (n)- A variable character length string with user specified maximum length n.

    Int- An integer.

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 5

    Small integer- A small integer.

    Numeric (p, d)-A Fixed point number with user defined precision.

    Real, double precision- Floating point and double precision floating point

    numbers with machine dependent precision.

    Float (n)- A floating point number, with precision of at least n digits.

    Date- A calendar date containing a (four digit) year, month and day of the

    month.

    Time- The time of day, in hours, minutes and seconds Eg. Time 09:30:00.

    Number- Number is used to store numbers (fixed or floating point

    3. SQL Statements:

    1) DDL Commands:Data Definition Language statements

    -It is a set of SQL commands used to create,modify and delete database

    structure but not the data.

    Examples:

    CREATE :To create objects in the database

    Syntax:

    CREATE TABLE tablename (column_name data_ type constraints, );

    ALTER:Alters the structures of the database.

    Syntax:

    ALTER TABLE ADD CONSTRAINT Pkey1 PRIMARY

    KEY (ATTR);

    ALTER TABLE DROP COLUMN ;

    DROP:Delete objects from database.

    Syntax:

    DROP TABLE ;

    TRUNCATE:Remove all records from table,including spaces allocated

    for the records are removed.

    Syntax:

    TRUNCATE TABLE ;

    COMMENT: Add comments to the data dictionary

    GRANT: Gives users access privileges to database.

    REVOKE: Withdraw access privileges given with the GRANT cmd.

    2) DML Commands:Data Manipulation Language statements

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 6

    -It is the area of SQL that allows changing data within the database.

    Examples:

    INSERT: Insert data into a table.

    Syntax:

    INSERT INTO tablename VALUES (value list);

    UPDATE: Updates existing data within a table.

    Syntax:

    UPDATE tablename SET column_name =value [ WHERE condition]

    Example: update emp set sal=20000 where empno=7369;

    DELETE: Deletes all records from a table

    Syntax:

    DELETE FROM tablename WHERE condition

    3) DQL Commands:Data Query Language

    -It is the components of SQL stmts that allows getting data from database.

    Examples:

    SELECT: Retrieve data from database.

    Syntax:

    SELECT * FROM tablename

    Conclusion :

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 7

    EXPERIMENT NO. 2

    SORTING CONDITION

    Aim : To study and Perform practical by using restricting sorting

    conditions

    Resources

    Required

    : Oracle 9i-Sql plus

    Consumables - Printer Pages for printouts.

    Theory :

    Restricting and Sorting Data:

    SQL allows duplicates in relations as well as in the results of SQL expressions we

    want to force the elimination of duplicates, we insert the keyword distinct after

    select, if we want duplicates removed

    Comparison Conditions:

    1. Between Condition:

    The BETWEEN condition allows you to retrieve values within a range.

    Syntax:

    SELECT columns

    FROM tables

    WHERE column1 between value1 and value2;

    Example:

    SELECT *

    FROM suppliers

    WHERE supplier_id between 5000 AND 5010;

    2. IN Condition:

    The arithmetic operator(=) compares a single value to another value. In case a

    value needs to be compared to a list of values the IN predicate is used.The IN

    predicate helps reduce the need to use multiple OR conditions.

    Syntax:

    SELECT columns

    FROM tables

    WHERE column1 IN(value1, value2,value 3);

    Example:

    SELECT FName,LName

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 8

    FROM cust

    WHERE FName IN(hansel,mamta,aruna);

    3. Like Condition: A LIKE condition specifies a test involving pattern matching.

    We describe patterns by using two special characters:

    Percent (%): The % character matches any substring. Underscore ( ): The character matches any character.

    Syntax:

    SELECT columns

    FROM tables

    WHERE column1 LIKE %_; Example:

    List the customers whose name begin with the letters' SELECT FName,LName

    FROM cust

    WHERE FName LIKE Ch%; The % indicates that any number of character can follow the letter Ch.

    Logical operator:

    1. OR operator: The OR condition allows you to create an SQL statement where records are

    returned when any one of the conditions are met. It can be used in any valid SQL

    statement - select, insert, update, or delete.

    Syntax:

    SELECT columns

    FROM tables

    WHERE column1 = 'value1' or column2 = 'value2'

    The OR condition requires that any of the conditions be must be met for the record to

    be included in the result set. In this case, column1 has to equal 'value1' OR column2

    has to equal 'value2'.

    Example:

    SELECT *

    FROM suppliers

    WHERE city = 'New York'

    or city = 'Newark';

    This would return all suppliers that reside in either New York or Newark. Because the

    * is used in the select, all fields from the suppliers table would appear in the result set.

    2. AND Operator:

    The AND operator displays a record if both the first condition and the second

    condition is true.

    Syntax:

    SELECT columns

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 9

    FROM tables

    WHERE column1 = 'value1' and column2 = 'value2'

    Example:

    SELECT *

    FROM EMP

    WHERE EmpTown = 'London' AND EmpAge > 30

    3. NOT Operator:

    If you want to find rows that do not satisfy a condition, you can use the logical

    operator, NOT. NOT results in the reverse of a condition. That is, if a condition is

    satisfied, then the row is not returned.

    Example:

    If you want to find out the names of the students who do not play football, the

    query would be like:

    SELECT first_name, last_name, games

    FROM student_details

    WHERE NOT games = 'Football' ;

    ORDER BY clause:Sorting of data in table The ORDER BY keyword is used to sort the result-set by a specified column.

    The ORDER BY keyword sort the records in ascending order by default.

    If you want to sort the records in a descending order, you can use the DESC keyword

    Syntax:

    SELECT "column_name"

    FROM "table_name"

    [WHERE "condition"]

    ORDER BY "column_name" [ASC, DESC];

    Example:

    SELECT supplier_city

    FROM suppliers

    WHERE supplier_name = 'IBM'

    ORDER BY supplier_city DESC;

    Conclusion :

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 10

    EXPERIMENT NO. 3

    MULTIPLE TABLES ANDGROUPFUNCTION

    Aim : To study and perform practical by multiple tables and group

    function

    Resources

    Required

    : Oracle 9i-Sql plus

    Consumables - Printer Pages for printouts.

    Theory :

    Aggregating Data using Group Function:

    Group Function: It operates on set of rows to give one result per group.

    Types of Group Function:

    1.Avg : return average value of n

    Syntax: Avg ([distinct/all]n)

    2. Min: return minimum value of exp

    Syntax: MIN((distinct/all )expr)

    3.Count : Returns the no of rows where expr is not null

    Syntax: Count ([distinct/all)expr]

    Count (*) Returns the no rows in the table, including duplicates and those

    with nulls.

    4. Max : Return max value of expr Syntax:

    Max ([distinct/all]expr)

    5. Sum : Returns sum of values of n Syntax:

    Sum ([distinct/all]n)

    Conclusion :

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 11

    EXPERIMENT NO. 4

    SUBQUERIES AND COMMANDS

    Aim : To study and Perform practical by using subqueries and commands.

    Resources

    Required

    : Oracle 9i-Sql plus

    Consumables - Printer Pages for printouts.

    Theory :

    Subqueries:

    A subquery is a type of SQL query, where a query is embedded within another query.

    Syntax:

    SELECT select_list

    FROM table_name

    WHERE column_name operator (SELECT select_list

    FROM table_name

    )

    In the syntax, observe a second SELECT statement written in the WHERE clause, on

    the right hand side of the WHERE condition. This SELECT statement is enclosed in

    parentheses. This sub query is called the inner query and is executed once to return a

    value that is used by the main (outer) query. Sub queries can be different in different

    places in a SELECT statement, such as the WHERE clause, HAVING clause, FROM

    clause, SELECT column list etc.

    The query to retrieve the details of employees who belong to the same department as

    Alexander Khoo is :

    SELECT *

    FROM EMPLOYEES

    WHERE DEPARTMENT_ID = (SELECT DEPARTMENT_ID

    FROM EMPLOYEES

    WHERE FIRST_NAME='Alexander' AND

    LAST_NAME='Khoo')

    Types of Subquery:

    1. Single Row Subquery. 2. Multiple Row Subquery

    1.Single Row Subquery:

    A single-row subquery is one where the subquery returns only one value. In such a

    subquery you must use a single-row operator such as:

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 12

    Operator Description

    = Equal To

    Not Equal To

    > Greater Than

    >= Greater Than Equal To

    < Less Than

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 13

    EXPERIMENT NO. 5

    CONTROL TRANSACTION STATEMENT

    Aim : To study and Perform practical by using DML statement and

    control transaction.

    Resources

    Required

    : Oracle 9i-Sql plus

    Consumables - Printer Pages for printouts.

    Theory :

    Transaction Control Statements

    A transaction is a sequence of one or more SQL statements that Oracle Database

    treats as a unit: either all of the statements are performed, or none of them are.

    The basic transaction control statements are:

    SAVEPOINT, which marks a savepoint in a transactiona point to which you can later roll back. Savepoints are optional, and a transaction can have

    multiple savepoints.

    COMMIT, which ends the current transaction, makes its changes permanent,

    erases its savepoints, and releases its locks.

    ROLLBACK, which rolls back (undoes) either the entire current transaction or

    only the changes made after the specified savepoint.

    1. Committing Transactions

    Committing a transaction makes its changes permanent, erases its savepoints, and

    releases its locks.

    Before you commit a transaction:

    Your changes are visible to you, but not to other users of the database

    instance.

    Your changes are not finalyou can undo them with a ROLLBACK statement.

    After you commit a transaction:

    Your changes are visible to other users, and to their statements that run after

    you commit your transaction.

    Your changes are finalyou cannot undo them with a ROLLBACK statement.

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 14

    Example: Committing a Transaction

    Before transaction:

    SELECT * FROM REGIONS

    ORDER BY REGION_ID;

    Result:

    REGION_ID REGION_NAME

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

    1 Europe

    2 Americas

    3 Asia

    4 Middle East and Africa

    Transaction (add row to table):

    INSERT INTO regions (region_id, region_name) VALUES (5, 'Africa');

    Result:

    1 row created.

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 15

    Check that row was added:

    SELECT * FROM REGIONS

    ORDER BY REGION_ID;

    Result:

    REGION_ID REGION_NAME

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

    1 Europe

    2 Americas

    3 Asia

    4 Middle East and Africa

    5 Africa

    Commit transaction:

    COMMIT;

    Result:

    Commit complete.

    2. Rolling Back Transactions Rolling back a transaction undoes its changes. You can roll back the entire current

    transaction, or you can roll it back only to a specified savepoint

    To roll back the current transaction only to a specified savepoint, you must use the

    ROLLBACK statement with the TOSAVEPOINT clause.

    Rolling back the entire current transaction:

    Ends the transaction

    Reverses all of its changes

    Erases all of its savepoints

    Releases any transaction locks

    Example:Rolling Back an Entire Transaction

    Before transaction:

    SELECT * FROM REGIONS

    ORDER BY REGION_ID;

    Result:

    REGION_ID REGION_NAME

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

    1 Europe

    2 Americas

    3 Asia

    4 Middle East and Africa

    5 Africa

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 16

    Transaction (change table):

    UPDATE REGIONS

    SET REGION_NAME = 'Middle East'

    WHERE REGION_NAME = 'Middle East and Africa';

    Result:

    1 row updated.

    Check change:

    SELECT * FROM REGIONS

    ORDER BY REGION_ID;

    Result:

    REGION_ID REGION_NAME

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

    1 Europe

    2 Americas

    3 Asia

    4 Middle East 5 Africa

    Roll back transaction:

    ROLLBACK; Result:

    Rollback complete.

    Check rollback:

    SELECT * FROM REGIONS

    ORDER BY REGION_ID;

    Result:

    REGION_ID REGION_NAME

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

    1 Europe

    2 Americas

    3 Asia

    4 Middle East and Africa 5 Africa

    Conclusion :

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 17

    EXPERIMENT NO. 6

    TABLE CONSTRAINTS

    Aim : To study & perform practical by using DDL statement(creating and

    managing tables constraints)

    Resources

    Required

    : Oracle 9i-Sql plus

    Consumables - Printer Pages for printouts.

    Theory :

    Constraints:

    Constraints enforce rules at the table level.

    Constraints can be defined in two ways

    1) The constraints can be specified immediately after the column definition. This

    is called column-level definition.

    2) The constraints can be specified after all the columns are defined. This is called

    table-level definition

    Types of Constraints:

    1.Primary Key:

    Primary key is one or more columns is a table used to uniquely

    identity each row in the table. Primary key values must not be null and must be

    unique across the column. A multicolumn primary key is called composite

    primary key.

    Syntax: primary key as a column constraint

    Create table tablename

    (columnname datatype (size) primary key,.)

    Primary key as a table constraint

    Create table tablename

    (columnname datatype (size), columnname datatype( size)

    Primary key (columnname,columnname));

    2.Foreign Key Concept :

    Foreign key represents relationship between tables. A

    foreign key is column whose values are derived from the primary key of the same

    of some other table . the existence of foreign key implies that the table with

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 18

    foreign key is related to the primary key table from which the foreign key is

    derived .A foreign key must have corresponding primary key value in the

    primarykey table to have meaning.

    Foreign key as a column constraint

    Syntax :

    Create table table name

    (columnname datatype (size) references another table name);

    Foreign key as a table constraint:

    Syntax :

    Create table name

    (columnname datatype (size).

    primary key (columnname);

    foreign key (columnname)references table name);

    3.Check Integrity Constraints:

    Use the check constraints when you need to

    enforce integrity rules that can be evaluated based on a logical expression

    following are a few examples of appropriate check constraints.

    A check constraints name column of the client_master so that the name is

    entered in upper case.

    A check constraint on the client_no column of the client _master so that

    no client_no value starts with c

    Syntax:

    Create table tablename

    (columnname datatype(size) CONSTRAINT constraintname)

    Check (expression));

    4. Unique Key:

    This constraint ensures that a column or a group of columns in each row have a

    distinct value. A column(s) can have a null value but the values cannot be

    duplicated.

    Syntax to define a Unique key at column level:

    [CONSTRAINT constraint_name] UNIQUE

    Syntax to define a Unique key at table level:

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 19

    [CONSTRAINT constraint_name] UNIQUE(column_name)

    For Example: To create an employee table with Unique key, the query would be

    like,

    Unique Key at column level:

    CREATE TABLE employee

    ( id number(5) PRIMARY KEY,

    name char(20),

    dept char(10),

    age number(2),

    salary number(10),

    location char(10) UNIQUE

    );

    or

    CREATE TABLE employee

    ( id number(5) PRIMARY KEY,

    name char(20),

    dept char(10),

    age number(2),

    salary number(10),

    location char(10) CONSTRAINT loc_un UNIQUE

    );

    Unique Key at table level:

    CREATE TABLE employee

    ( id number(5) PRIMARY KEY,

    name char(20),

    dept char(10),

    age number(2),

    salary number(10),

    location char(10),

    CONSTRAINT loc_un UNIQUE(location)

    );

    5. Not Null Constraint :

    This constraint ensures all rows in the table contain a definite value for the column

    which is specified as not null. Which means a null value is not allowed.

    Syntax to define a Not Null constraint:

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 20

    [CONSTRAINT constraint name] NOT NULL

    For Example: To create a employee table with Null value, the query would be

    like

    CREATE TABLE employee

    ( id number(5),

    name char(20) CONSTRAINT nm_nn NOT NULL,

    dept char(10),

    age number(2),

    salary number(10),

    location char(10)

    );

    Conclusion :

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 21

    EXPERIMENT NO. 7

    VIEWS AND INDEXES

    Aim:To study & perform practical by using views index concept

    Resources

    Required

    : Oracle 9i-Sql plus

    Consumables - Printer Pages for printouts.

    Theory :

    Indexes-

    An index is an ordered list of content of a column or group of columns in a table.

    An index created on the single column of the table is called simple index. When

    multipletable columns are included in the index it is called composite index.

    Creating an Index for a table:-

    Syntax (Simple)

    CREATE INDEX index_name

    ON tablename(column name);

    Composite Index:-

    CREATE INDEX index_name

    ON tablename(columnname,columnname);

    Dropping Indexes:-

    An index can be dropped by using DROP INDEX

    SYNTAX:-

    DROP INDEX indexfilename;

    Views:-

    Logical data is how we want to see the current data in our database. Physical data

    is how this data is actually placed in our database.

    Views are masks placed upon tables. This allows the programmer to develop a

    method via which we can display predetermined data to users according to our

    desire.

    Views may be created for the following reasons:

    1. The DBA stores the views as a definition only. Hence there is no duplication of

    data.

    2. Simplifies Queries.

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 22

    3. Can be Queried as a base table itself.

    4. Provides data security.

    5.Avoids data redundancy.

    Creation of Views:-

    Syntax:-

    CREATE VIEW viewname AS

    SELECT columnname,columnname

    FROM tablename

    WHERE columnname=expression_list;

    Renaming the columns of a view:-

    Syntax:-

    CREATE VIEW viewname AS

    SELECT newcolumnname.

    FROM tablename

    WHERE columnname=expression_list;

    Selecting a data set from a view-

    Syntax:-

    SELECT columnname, columnname

    FROM viewname

    WHERE search condition;

    Destroying a view-

    Syntax:-

    DROP VIEW viewname;

    Conclusion :

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 23

    EXPERIMENT NO. 8

    SET OPERATIONS

    Aim : To study & perform practical by using set operations.

    Resources

    Required

    : Oracle 9i-Sql plus

    Consumables - Printer Pages for printouts.

    Theory :

    Set Operations:

    Set Operations are used to combine multiple result sets into one single result set.

    Basically there are 3 set operators available in SQL Server.

    1) Union: This is to combine two or more result sets into single with or without

    duplicate.

    2) Except: Takes the data from one result set where there is no matching in

    another.

    3) Intersect: Takes the data from both the result sets which are in common.

    One thing we need to make sure is when you are using set Operations the No. of

    columns should be same with the data type. There is no restriction on the column

    names.

    1.Union Clause:

    The user can put together multiple Queries and combine their output using the

    unionclause . The union clause merges the output of two or more queries into a

    single set ofrows and column.

    The final output of union clause will be

    Output: = Records only in Query one + records only in Query two + A single set

    ofrecords with is common in the both Queries.

    Syntax:

    SELECT columnname, columname

    FROM tablename 1

    UNION

    SELECT columnname, columnname

    From tablename2;

    2.Intersect Clause:

    The use can put together multiple Queries and their output using the

    interest clause.

    The final output of the interest clause will be :

    Output =A single set of records which are common in both Queries

    Syntax:

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 24

    SELECT columnname, columnname

    FROM tablename 1

    INTERSECT

    SELECT columnname, columnname

    FROM tablename 2;

    3.Minus Clause:-

    The user can put together multiple Queries and combine their output= records

    only in Query one.

    Syntax:

    SELECT columnname, columnname

    FROM tablename ;

    MINUS

    SELECT columnname, columnname

    FROM tablename ;

    Conclusion :

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 25

    EXPERIMENT NO. 9

    GROUP BY Clause

    Aim : To study & perform practical by using Group By Clause.

    Resources

    Required

    : Oracle 9i-Sql plus

    Consumables - Printer Pages for printouts.

    Theory :

    GROUP BY Clause:

    The GROUP BY clause can be used in a SELECT statement to collect data across

    multiple records and group the results by one or more columns.

    The syntax for the GROUP BY clause is:

    SELECT column1, column2, ... column_n, aggregate_function (expression)

    FROM tables

    WHERE predicates

    GROUP BY column1, column2, ... column_n;

    aggregate function can be a function such as SUM, COUNT, MIN, or MAX.

    Example:

    We could also use the SUM function to return the name of the department and the

    total sales (in the associated department).

    SELECT department, SUM(sales) as "Total sales"

    FROM order_details

    GROUP BY department;

    Because you have listed one column in your SELECT statement that is not

    encapsulated in the SUM function, you must use a GROUP BY clause. The

    department field must, therefore, be listed in the GROUP BY section.

    Having Clause:

    The HAVING clause is used in combination with the GROUP BY clause. It can

    be used in a SELECT statement to filter the records that a GROUP BY returns.

    Syntax:

    SELECT column1, column2, ... column_n, aggregate_function (expression)

    FROM tables

    WHERE predicates

    GROUP BY column1, column2, ... column_n

  • Saraswati College Of Engineering Computer Engg. Dept.

    S.E.IV[DBMS]Page 26

    HAVING condition1 ... condition_n;

    aggregate_function can be a function such as SUM, COUNT, MIN, or MAX.

    Example:

    We could also use the SUM function to return the name of the department and the

    total sales (in the associated department). The HAVING clause will filter the

    results so that only departments with sales greater than $1000 will be returned.

    SELECT department, SUM(sales) as "Total sales"

    FROM order_details

    GROUP BY department

    HAVING SUM(sales) > 1000;

    Conclusion :


Recommended