Vous êtes sur la page 1sur 25

Unit-4

Data Base Management System Subject: Basic Computer Engineering Subject Code: BE-205
Faculty: Mr. Shantilal Bhayal. File-Based Systems Collection of application programs that perform services for the end users (e.g. reports). Each program defines and manages its own data. File-Based Processing

Limitations of File-Based Approach


1.Separation and isolation of data Each program maintains its own set of data. Users of one program may be unaware of 2. Data dependence File structure is defined in the program code. 3. Incompatible file formats Programs are written in different languages, and so cannot easily access each others files. 4. Duplication of data

Same data is held by different programs. -- Wasted space and potentially different values programs 5. Fixed Queries/Proliferation of application program Programs are written to satisfy particular functions. Any new requirement needs a new program.

Database: Well organized collection of the following. a. Representations of a set of real world objects, e.g., people, cars, buildings etc. b. Set of desired attributes of these objects, e.g., tall, red, heavy etc. c. Relationship among these objects, e.g., John is skinny but heavier than a truck d. Set of rules for incorporating changes to these objects, e.g., John's weight has increased etc. There are four main types of database organization:

Relational Database: Data is organized as logically independent tables. Relationships among tables are
shown through shared data. The data in one table may reference similar data in other tables, which maintains the integrity of the links among them. This feature is referred to as referential integrity - an important concept in a relational database system. Operations such as select and join can be performed on these tables. This is the most widely used system of database organization. type encounters more errors due to the repetitive nature of data.

Flat Database: Data is organized in a single kind of record with a fixed number of fields. This database Object Oriented Database: Data is organized with similarity to object oriented programming concepts.
An object consists of data and methods, while classes group objects having similar data and methods. network if the one-to-many relationship is violated.

Hierarchical Database: Data is organized with hierarchical relationships. It becomes a complex

Database management system


A software system that enables users to define, create, maintain, and control access to the database. (Database) application program: a computer program that interacts with database by issuing an appropriate request (SQL statement) to the DBMS. A database management system (DBMS) is a software package with computer programs that control the creation, maintenance, and the use of a database. It allows organizations to conveniently develop databases for various applications by database administrators (DBAs) and other specialists

Advantages of DBMS's 1. Control of data redundancy 2. Data consistency 3. More information from the same amount of data 4. Sharing of data 5. Improved data integrity 6. Improved security 7. Enforcement of standards 8. Economy of scale 9. Balance conflicting requirements 10.Improved data accessibility and responsiveness 11.Increased productivity 12.Improved maintenance through data independence 13.Increased concurrency 14.Improved backup and recovery services Disadvantages Database systems are complex, difficult, and time-consuming to design Substantial hardware and software start-up costs Damage to database affects virtually all applications programs Extensive conversion costs in moving form a file-based system to a database system Initial training required for all programmers and users

3. DBMS Architecture Database Management Systems are very complex, sophisticated software applications that provide reliable management of large amounts of data. To better understand general database concepts and the structure and capabilities of a DBMS, it is useful to examine the architecture of a typical database management system. There are two different ways to look at the architecture of a DBMS: the logical DBMS architecture and the physical DBMS architecture. The logical architecture deals with the way data is stored and presented to users, while the physical architecture is concerned with the software components that make up a DBMS. 3.1 Logical DBMS Architecture The logical architecture describes how data in the database is perceived by users. It is not concerned with how the data is handled and processed by the DBMS, but only with how it looks. Users are shielded from the way data is stored on the underlying file system, and can manipulate the data without worrying about where it is located or how it is actually stored. This results in the database having different levels of abstraction. The majority of commercial Database Management Systems available today are based on the ANSI/SPARC generalized DBMS architecture, as proposed by the ANSI/SPARC Study Group on Data Base Management Systems. The ANSI/SPARC architecture divides the system into three levels of abstraction: the internal or physical level, the conceptual level, and the external or view level. The diagram below shows the logical architecture for a typical DBMS.

Figure 3-1 Logical DBMS Architecture The Internal or Physical Level The collection of files permanently stored on secondary storage devices is known as the physical database. The physical or internal level is the one closest to physical storage, and it provides a low-level description of the physical database, and an interface between the operating system's file system and the record structures used in higher levels of abstraction. It is at this level that record types and methods of storage are defined. The Conceptual Level The conceptual level presents a logical view of the entire database as a unified whole, which allows you to bring all the data in the database together and see it in a consistent manner. The first stage in the design of a database is to define the conceptual view, and a DBMS provides a data definition language for this purpose. The External or View Level The external or view level provides a window on the conceptual view which allows the user to see only the data of interest to them. The user can be either an application program or an end user. Any number of external schema can be defined and they can overlap each other.

3.2 Physical DBMS Architecture The physical architecture describes the software components used to enter and process data, and how these software components are related and interconnected .The physical DBMS architecture can be broken down into two parts: the back end and the front end. The back end is responsible for managing the physical database and providing the necessary support and mappings for the internal, conceptual, and external levels described earlier. Other benefits of a DBMS, such as security, integrity, and access control, are also the responsibility of the back end.

The front end is really just any application that runs on top of the DBMS. These may be applications provided by the DBMS vendor, the user, or a third party. The user interacts with the front end, and may not even be aware that the back end exists. Both the back end and front end can be further broken down into the software components that are common to most types of DBMS. These components are examined in detail in the following sections. Applications and Utilities Applications and utilities are the main interface to the DBMS for most users. There are three main sources of applications and utilities for a DBMS: the vendor, the user, and third parties. User applications are generally custom-made application programs written for a specific purpose using a conventional programming language. The most common applications and utilities used with a database can be divided into several well-defined categories. These are:

Command Line Interfaces-these are character-based, interactive interfaces that let you use the full
power and functionality of the DBMS query language directly. They allow you to manipulate the database and perform ad-hoc queries and see the results immediately.

Graphical User Interface (GUI) tools-these are graphical, interactive interfaces that hide the

complexity of the DBMS and query language behind an intuitive, easy to understand, and convenient interface. database is restored to a consistent state if a failure does occur

Backup/Restore Utilities-these are designed to minimize the effects of a database failure and ensure a Load/Unload Utilities-these allow the user to unload a database or parts of a database and reload the
data on the same machine, or on another machine in a different location.

Reporting/Analysis Utilities-these are used to analyze and report on the data contained in the database.
This may include analyzing trends in data, computing values from data, or displaying data that meets some specified criteria, and then displaying or printing a report containing this information.

The Application Program Interface The application program interface (API) is a library of low-level routines which operate directly on the database engine. The API is usually used when creating software applications with a general-purpose programming language such as C++ or Visual Basic. The Query Language Processor The query language processor is responsible for receiving query language statements and changing them from the English-like syntax of the query language to a form the DBMS can understand. The query language processor usually consists of two separate parts: the parser and the query optimizer. The parser receives query language statements from application programs or command-line utilities and examines the syntax of the statements to ensure they are correct. The query optimizer examines the query language statement, and tries to choose the best and most efficient way of executing the query. The DBMS Engine The DBMS engine is the heart of the DBMS, and it is responsible for all of the data management in the DBMS. The DBMS engine usually consists of two separate parts: the transaction manager and the file manager. The transaction manager maintains tables of authorization and currency control information. The file manager is the component responsible for all physical input/output operations on the database. It is concerned with the physical address of the data on the disk, and is responsible for any interaction (reads or writes) with the host operating system.

Data Dictionary
A DBMS component that stores meta data. The data dictionary contains the data definition and its characteristics and entity relationships. This may include the names and descriptions of the various tables and fields within the database. Also included are things like data types and length of data items. The inclusion of primary and foreign key also adds to the consistency of the database being built There are two other types of Data DictionariesActive Data Dictionary- A data dictionary that is automatically updated by the DBMS every time the database is accessed. Passive Data Dictionary- Similar to Active DD however it is not automatically updated and usually requires a batch process to be run. data dictionary, also called the system catalogue. The data dictionary is the repository of all the meta-data relevant to the objects stored in the database also of information concerning the DBMS itself.

Defining meta data.


The term meta data is often defined as data about data. That is, data that provides information about the tables, views, constraints, stored procedures, etc. stored within the database. If we take a table as an example, the dictionary will store information such as: its name when it was created and when it was last accessed the names and data types of its attributes (i.e. structural information) its owner, who may read and write to it (i.e. security information) where the data is stored (i.e. physical information)

Data models
A data model is a collection of concepts that can be used to describe the structure of a database. A collection of tools for describing data ,data relationships ,data semantics,data constraints

Type of Data Model


Hierarchical Data Model The hierarchical data model organizes data in a tree structure. There is a hierarchy of parent and child data segments. This structure implies that a record can have repeating information, generally in the child data segments. Data in a series of records, which have a set of field values attached to it. Advantages 1. Conceptual simplicity 2. Database security and integrity 3. Data independence 4. Efficiency Disadvantages 1. Complex implementation 2. Difficult to manage and lack of standards 3. Lacks structural independence 4. Applications programming and use complexity 5. Implementation limitations Network Data Model The network model (defined by the CODASYL specification) organizes data using two fundamental concepts, called records and sets. Records contain fields. Sets (not to be confused with mathematical sets) define one-tomany relationships between records: one owner, many members. A record may be an owner in any number of sets, and a member in any number of sets. The network model is a variation on the hierarchical model, to the extent that it is built on the concept of multiple branches (lower-level structures) emanating from one or more nodes (higher-level structures), while the model differs from the hierarchical model in that branches can be connected to multiple nodes. The network model is able to represent redundancy in data more efficiently than in the hierarchical model. Advantages 1. Conceptual simplicity 2 .Handles more relationship types 3. Data access flexibility 4. Promotes database integrity 5. Data independence 6.Conformance to standards Disadvantages 1. System complexity 2. Lack of structural independence

Relational Data Model Entity Relationship Model (E-R Model) The process of database design is an iterative process. The ER Model is used at the conceptual design stage of the database design.ER diagram is used to represent this conceptual design. The requirement analysis is modeled in this conceptual design. The ER model is very expressive so that people can easily understand the requirement. The data modeler prepares the ER diagram and is verified with the functional domain experts to ensure that all the requirements are properly incorporated in the conceptual design. The process is repeated until the end users and designers agree that the E-R diagram is a fair representation of the requirement. We can easily map an ER diagram to a relational schema. The basic constructs of ER Model are Entity, Attributes and Relationships. An Entity is an object that exist in the real world and is distinguishable from other entities. Conceptual Design ER Diagram Entities Attributes Relationships

Entities An entity is a thing or object in the real world that is distinguishable from all other objects. For example 'Person' in an organization is an entity. An entity has a set of properties. At the E-R modeling level an entity actually refers to an entity set. In other words, entity in ER model corresponds to a table. Entity Entity Set An entity may be concrete such as a person, book etc or may be abstract such as account,loan etc. The ER model refers to a specific table row as an entity instance or entity occurrence. Collection of similar entities (Entity Set) often corresponds to a table. Each entity set has a key.All entities in an entity set have the same set of attributes. Thus entity set is a set of entities of the same type that share the same properties or attributes. An entity is represented by a rectangle containing the entity name, which is a noun usually written in capital letters. Attributes An entity is represented by a set of attributes. It corresponds to a field in a table.For each attribute there is a set of permitted values called the domain or value set of the attribute. Attributes are represented by ovals and are connected to the entity with a line. Each oval contains the name of the attribute it represents. Relationships A relationship describes an association among entities. In ER model the association among entities is described as one-to-one, one-to-many, many-to-many. Relationships are represented by a diamond connected to the related entities. The relationship name (an active or passive verb), is written inside the diamond.

Data Base Administrator A database administrator (short form DBA) is a person responsible for the design, implementation, maintenance

and repair of an organization's database One of the main reasons for using DBMS is to have a central control of both data and the programs accessing those data. A person who has such control over the system is called a Database Administrator(DBA). The following are the functions of a Database administrator Schema Definition Storage structure and access method definition Schema and physical organization modification. Granting authorization for data access. Routine Maintenance

Schema Definition The Database Administrator creates the database schema by executing DDL statements. Schema includes the logical structure of database table(Relation) like data types of attributes,length of attributes,integrity constraints etc. Storage structure and access method definition Database tables or indexes are stored in the following ways: Flat files,Heaps,B+ Tree etc.. Schema and physical organization modification The DBA carries out changes to the existing schema and physical organization. Granting authorization for data access The DBA provides different access rights to the users according to their level. Ordinary users might have highly restricted access to data, while you go up in the hierarchy to the administrator ,you will get more access rights. Routine Maintenance Some of the routine maintenance activities of a DBA is given below. Taking backup of database periodically. Ensuring enough disk space is available all the time. Monitoring jobs running on the database. Ensure that performance is not degraded by some expensive task submitted by some users. Performance Tuning. Key A key is a single or combination of multiple fields. Its purpose is to access or retrieve data rows from table according to the requirement. The keys are defined in tables to access or sequence the stored data quickly and smoothly. They are also used to create links between different tables.

Candidate key - A candidate key is a field or combination of fields that can act as a

primary key field for that table to uniquely identify each record in that table. Compound key - compound key (also called a composite key or concatenated key) is a key that consists of 2 or more attributes. Primary key - a primary key is a value that can be used to identify a unique row in a table. Attributes are associated with it. Examples of primary keys are Social Security numbers (associated to a specific person) or ISBNs (associated to a specific book). In the relational model of data, a primary key is a candidate key chosen as the main method of uniquely identifying a tuple in a relation. Super key - A super key is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. Equivalently a superkey can also be defined as a set of attributes of a relvar upon which all

attributes of the relvar are functionally dependent. Foreign key - a foreign key (FK) is a field or group of fields in a database record that points to a key field or group of fields forming a key of another database record in some (usually different) table. Usually a foreign key in one table refers to the primary key (PK) of another table. This way references can be made to link information together and it is an essential part of database normalization.

Alternate key - An alternate key is any candidate key which is not selected to be the
primary key

Data independence Data independence is the type of data transparency that matters for a centralized DBMS. It refers to the immunity of user applications to make changes in the definition and organization of data. Physical data independence deals with hiding the details of the storage structure from user applications. The application should not be involved with these issues, since there is no difference in the operation carried out against the data. The data independence and operation independence together gives the feature of data abstraction. There are two levels of data independence. Data Independence Types Data independence has two types: 1. Physical Independence and 2. Logical Independence. With knowledge about the three-schemes architecture the term data independence can be explained as follows: Each higher level of the data architecture is immune to changes of the next lower level of the architecture. Physical Independence: The logical scheme stays unchanged even though the storage space or type of some data is changed for reasons of optimization or reorganization. [The ability to change the physical schema without changing the logical schema is called as Physical Data Independence. Logical Independence: The external scheme may stay unchanged for most changes of the logical scheme. This is especially desirable as the application software does not need to be modified or newly translated. [The ability to change the logical schema without changing the external schema or application programs is called as Logical Data Independence.] SQL Tutorial SQL (Structured Query Language) is used to modify and access data or information from a storage area called database. This beginner sql tutorial website teaches you the basics of SQL and how to write SQL queries. I will be sharing my knowledge on SQL and help you learn SQL better. The sql concepts discussed in this tutorial can be applied to most of database systems. The syntax used to explain the concepts is similar to the one used in Oracle database. SQL Introduction SQL stands for Structured Query Language and can be pronounced as SQL or sequel (Structured English Query Language). It is a query language used for accessing and modifying information in the database. IBM first developed SQL in 1970s. Also it is an ANSI/ISO standard. It has become a Standard Universal Language used by most of the relational database management systems (RDBMS). Some of the RDBMS systems are: Oracle, Microsoft SQL server, Sybase etc. Most of these have provided their own implementation thus

enhancing it's feature and making it a powerful tool. Few of the sql commands used in sql programming are SELECT Statement, UPDATE Statement, INSERT INTO Statement, DELETE Statement, WHERE Clause, ORDER BY Clause, GROUP BY Clause, ORDER Clause, Joins, Views, GROUP Functions, Indexes etc. In a simple manner, SQL is a non-procedural, English-like language that processes data in groups of records rather than one record at a time. Few functions of SQL are: store data modify data retrieve data modify data delete data create tables and other database objects delete data

SQL Commands: SQL commands are instructions used to communicate with the database to perform specific task that work with data. SQL commands can be used not only for searching the database but also to perform various other functions like, for example, you can create tables, add data to tables, or modify data, drop the table, set permissions for users. SQL commands are grouped into four major categories depending on their functionality:

Data Definition Language (DDL) - These SQL commands are used for creating, modifying, and

dropping the structure of database objects. The commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE. Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving, modifying, and deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE. Transaction Control Language (TCL) - These SQL commands are used for managing changes affecting the data. These commands are COMMIT, ROLLBACK, and SAVEPOINT. Data Control Language (DCL) - These SQL commands are used for providing security to database objects. These commands are GRANT and REVOKE. SQL SELECT Statement The most commonly used SQL command is SELECT statement. The SQL SELECT statement is used to query or retrieve data from a table in the database. A query may retrieve information from specified columns or from all of the columns in the table. To create a simple SQL SELECT Statement, you must specify the column(s) name and the table name. The whole query is called SQL SELECT Statement. Syntax of SQL SELECT Statement: SELECT column_list FROM table-name [WHERE Clause] [GROUP BY clause] [HAVING clause] [ORDER BY clause];

table-name is the name of the table from which the information is retrieved. column_list includes one or more columns from which data is retrieved.
The code within the brackets is optional. database table student_details; id first_name last_name age subject 100 Rahul Sharma 10 Science games Cricket

101 Anjali Bhagwat 12 Maths Football 102 Stephen Fleming 09 Science Cricket 103 Shekar Gowda 18 Maths Badminton 104 Priya Chandra 15 Economics Chess NOTE: These database tables are used here for better explanation of SQL commands. In reality, the tables can have different columns and different data. For example, consider the table student_details. To select the first name of all the students the query would be like: SELECT first_name FROM student_details; NOTE: The commands are not case sensitive. The above SELECT statement can also be written as "select first_name from students_details;" You can also retrieve data from more than one column. For example, to select first name and last name of all the students. SELECT first_name, last_name FROM student_details; You can also use clauses like WHERE, GROUP BY, HAVING, ORDER BY with SELECT statement. We will discuss these commands in coming chapters. NOTE: In a SQL SELECT statement only SELECT and FROM statements are mandatory. Other clauses like WHERE, ORDER BY, GROUP BY, HAVING are optional. How to use expressions in SQL SELECT Statement? Expressions combine many arithmetic operators, they can be used in SELECT, WHERE and ORDER BY Clauses of the SQL SELECT Statement. Here we will explain how to use expressions in the SQL SELECT Statement. About using expressions in WHERE and ORDER BY clause, they will be explained in their respective sections. The operators are evaluated in a specific order of precedence, when more than one arithmetic operator is used in an expression. The order of evaluation is: parentheses, division, multiplication, addition, and subtraction. The evaluation is performed from the left to the right of the expression. For example: If we want to display the first and last name of an employee combined together, the SQL Select Statement would be like SELECT first_name || ' ' || last_name FROM employee; Output: first_name || ' ' || last_name --------------------------------Rahul Sharma Anjali Bhagwat Stephen Fleming Shekar Gowda Priya Chandra You can also provide aliases as below. SELECT first_name || ' ' || last_name AS emp_name FROM employee; Output: emp_name -------------

Rahul Sharma Anjali Bhagwat Stephen Fleming Shekar Gowda Priya Chandra SQL Alias SQL Aliases are defined for columns and tables. Basically aliases is created to make the column selected more readable. For Example: To select the first name of all the students, the query would be like: Aliases for columns: SELECT first_name AS Name FROM student_details; or SELECT first_name Name FROM student_details; In the above query, the column first_name is given a alias as 'name'. So when the result is displayed the column name appears as 'Name' instead of 'first_name'. Output: Name ------------Rahul Sharma Anjali Bhagwat Stephen Fleming Shekar Gowda Priya Chandra Aliases for tables: SELECT s.first_name FROM student_details s; In the above query, alias 's' is defined for the table student_details and the column first_name is selected from the table. Aliases is more useful when There are more than one tables involved in a query, Functions are used in the query, The column names are big or not readable, More than one columns are combined together

SQL WHERE Clause The WHERE Clause is used when you want to retrieve specific information from a table excluding other irrelevant data. For example, when you want to see the information about students in class 10th only then you do need the information about the students in other class. Retrieving information about all the students would increase the processing time for the query. So SQL offers a feature called WHERE clause, which we can use to restrict the data that is retrieved. The condition you provide in the WHERE clause filters the rows retrieved from the table and gives you only those rows which you expected to see. WHERE clause can be used along with SELECT, DELETE, UPDATE statements.

Syntax of SQL WHERE Clause: WHERE {column or expression} comparison-operator value Syntax for a WHERE clause with Select statement is: SELECT column_list FROM table-name WHERE condition;

column or expression - Is the column of a table or a expression comparison-operator - operators like = < > etc. value - Any user value or a column name for comparison
For Example: To find the name of a student with id 100, the query would be like: SELECT first_name, last_name FROM student_details WHERE id = 100; Comparison Operators and Logical Operators are used in WHERE Clause. These operators are discussed in the next chapter. NOTE: Aliases defined for the columns in the SELECT statement cannot be used in the WHERE clause to set conditions. Only aliases created for tables can be used to reference the columns in the table. How to use expressions in the WHERE Clause? Expressions can also be used in the WHERE clause of the SELECT statement. For example: Lets consider the employee table. If you want to display employee name, current salary, and a 20% increase in the salary for only those products where the percentage increase in salary is greater than 30000, the SELECT statement can be written as shown below SELECT name, salary, salary*1.2 AS new_salary FROM employee WHERE salary*1.2 > 30000; Output: new_salary ------------------------- ---------Hrithik 35000 37000 Harsha 35000 37000 Priya 30000 360000 NOTE: Aliases defined in the SELECT Statement can be used in WHERE Clause. SQL Logical Operators There are three Logical Operators namely, AND, OR, and NOT. These operators compare two conditions at a time to determine whether a row can be selected for the output. When retrieving data using a SELECT statement, you can use logical operators in the WHERE clause, which allows you to combine more than one condition. Logical Operators OR AND name salary

Description For the row to be selected at least one of the conditions must be true. For a row to be selected all the specified

NOT

conditions must be true. For a row to be selected the specified condition must be false.

"OR" Logical Operator: If you want to select rows that satisfy at least one of the given conditions, you can use the logical operator, OR. For example: if you want to find the names of students who are studying either Maths or Science, the query would be like, SELECT first_name, last_name, subject FROM student_details WHERE subject = 'Maths' OR subject = 'Science' The output would be something like, first_nam last_name subject e ------------- ------------- ---------Anajali Bhagwat Maths Shekar Gowda Maths Rahul Sharma Science Stephen Fleming Science The following table describes how logical "OR" operator selects a row. Column1 Satisfied? YES YES NO NO Column2 Satisfied? YES NO YES NO Row Selected YES YES YES NO

"AND" Logical Operator: If you want to select rows that must satisfy all the given conditions, you can use the logical operator, AND. For Example: To find the names of the students between the age 10 to 15 years, the query would be like: SELECT first_name, last_name, age FROM student_details WHERE age >= 10 AND age <= 15; The output would be something like, first_name last_name age ------------- ------------- -----Rahul Sharma 10 Anajali Bhagwat 12 Shekar Gowda 15 The following table describes how logical "AND" operator selects a row. Column1 Satisfied? YES Column2 Satisfied? YES Row Selected YES

YES NO NO

NO YES NO

NO NO NO

"NOT" Logical 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. For 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' The output would be something like, first_na last_nam games me e ----------- ----------------------------Rahul Sharma Cricket Stephen Fleming Cricket Shekar Gowda Badminton Priya Chandra Chess The following table describes how logical "NOT" operator selects a row. Column1 NOT Column1 Satisfied? Satisfied? YES NO NO YES Nested Logical Operators: Row Selected NO YES

You can use multiple logical operators in an SQL statement. When you combine the logical operators in a SELECT statement, the order in which the statement is processed is 1) NOT 2) AND 3) OR For example: If you want to select the names of the students who age is between 10 and 15 years, or those who do not play football, the SELECT statement would be SELECT first_name, last_name, age, games FROM student_details WHERE age >= 10 AND age <= 15 OR NOT games = 'Football' The output would be something like, first_n last_nam age games ame e --------- ------------ ----- ----------

------ -Rahul Sharma 10 Cricket Priya Chandra 15 Chess In this case, the filter works as follows: Condition 1: All the students you do not play football are selected. Condition 2: All the students whose are aged between 10 and 15 are selected. Condition 3: Finally the result is, the rows which satisfy atleast one of the above conditions is returned. NOTE:The order in which you phrase the condition is important, if the order changes you are likely to get a different resul SQL Comparison Keywords There are other comparison keywords available in sql which are used to enhance the search capabilities of a sql query. They are "IN", "BETWEEN...AND", "IS NULL", "LIKE". Comparision Operators LIKE Description

column value is similar to specified character(s). column value is equal to any one of a IN specified set of values. column value is between two values, BETWEEN...A including the end values specified in the ND range. IS NULL column value does not exist. SQL LIKE Operator The LIKE operator is used to list all rows in a table whose column values match a specified pattern. It is useful when you want to search rows to match a specific pattern, or when you do not know the entire value. For this purpose we use a wildcard character '%'. For example: To select all the students whose name begins with 'S' SELECT first_name, last_name FROM student_details WHERE first_name LIKE 'S%'; The output would be similar to: first_name last_name ------------------------Stephen Fleming Shekar Gowda The above select statement searches for all the rows where the first letter of the column first_name is 'S' and rest of the letters in the name can be any character. There is another wildcard character you can use with LIKE operator. It is the underscore character, ' _ ' . In a search string, the underscore signifies a single character. For example: to display all the names with 'a' second character, SELECT first_name, last_name FROM student_details

WHERE first_name LIKE '_a%'; The output would be similar to: first_name last_name ------------------------Rahul Sharma NOTE:Each underscore act as a placeholder for only one character. So you can use more than one underscore. Eg: ' __i% '-this has two underscores towards the left, 'S__j%' - this has two underscores between character 'S' and 'i'. SQL BETWEEN ... AND Operator The operator BETWEEN and AND, are used to compare data for a range of values. For Example: to find the names of the students between age 10 to 15 years, the query would be like, SELECT first_name, last_name, age FROM student_details WHERE age BETWEEN 10 AND 15; The output would be similar to: first_name ------------Rahul Anajali Shekar last_name ------------Sharma Bhagwat Gowda age -----10 12 15

SQL IN Operator: The IN operator is used when you want to compare a column with more than one value. It is similar to an OR condition. For example: If you want to find the names of students who are studying either Maths or Science, the query would be like, SELECT first_name, last_name, subject FROM student_details WHERE subject IN ('Maths', 'Science'); The output would be similar to: first_nam last_name subject e ------------- ------------- ---------Anajali Bhagwat Maths Shekar Gowda Maths Rahul Sharma Science Stephen Fleming Science You can include more subjects in the list like ('maths','science','history') NOTE:The data used to compare is case sensitive. SQL IS NULL Operator A column value is NULL if it does not exist. The IS NULL operator is used to display all the rows for columns

that do not have a value. For Example: If you want to find the names of students who do not participate in any games, the query would be as given below SELECT first_name, last_name FROM student_details WHERE games IS NULL There would be no output as we have every student participate in a game in the table student_details, else the names of the students who do not participate in any games would be displayed. SQL ORDER BY The ORDER BY clause is used in a SELECT statement to sort results either in ascending or descending order. Oracle sorts query results in ascending order by default. Syntax for using SQL ORDER BY clause to sort data is: SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1 [, column2, .. columnN] [DESC]]; database table "employee"; id name dept age salary location 100 Ramesh Electrical 24 25000 Bangalore 101 Hrithik Electronics 28 35000 Bangalore 102 Harsha Aeronautics 28 35000 Mysore 103 Soumya Electronics 22 20000 Bangalore 104 Priya InfoTech 25 30000 Mangalore For Example: If you want to sort the employee table by salary of the employee, the sql query would be. SELECT name, salary FROM employee ORDER BY salary; The output would be like name salary ------------------Soumya 20000 Ramesh 25000 Priya 30000 Hrithik 35000 Harsha 35000 The query first sorts the result according to name and then displays it. You can also use more than one column in the ORDER BY clause. If you want to sort the employee table by the name and salary, the query would be like, SELECT name, salary FROM employee ORDER BY name, salary; The output would be like: name salary ------------- ------------Soumya 20000

Ramesh 25000 Priya 30000 Harsha 35000 Hrithik 35000 NOTE:The columns specified in ORDER BY clause should be one of the columns selected in the SELECT column list. You can represent the columns in the ORDER BY clause by specifying the position of a column in the SELECT list, instead of writing the column name. The above query can also be written as given below, SELECT name, salary FROM employee ORDER BY 1, 2; By default, the ORDER BY Clause sorts data in ascending order. If you want to sort the data in descending order, you must explicitly specify it as shown below. SELECT name, salary FROM employee ORDER BY name, salary DESC; The above query sorts only the column 'salary' in descending order and the column 'name' by ascending order. If you want to select both name and salary in descending order, the query would be as given below. SELECT name, salary FROM employee ORDER BY name DESC, salary DESC; How to use expressions in the ORDER BY Clause? Expressions in the ORDER BY clause of a SELECT statement. For example: If you want to display employee name, current salary, and a 20% increase in the salary for only those employees for whom the percentage increase in salary is greater than 30000 and in descending order of the increased price, the SELECT statement can be written as shown below SELECT name, salary, salary*1.2 AS new_salary FROM employee WHERE salary*1.2 > 30000 ORDER BY new_salary DESC; The output for the above query is as follows. name salary new_salary ---------- ---------- ------------Hrithik 35000 37000 Harsha 35000 37000 Priya 30000 36000 NOTE:Aliases defined in the SELECT Statement can be used in ORDER BY Clause. SQL GROUP Functions Group functions are built-in SQL functions that operate on groups of rows and return one value for the entire group. These functions are: COUNT, MAX, MIN, AVG, SUM, DISTINCT SQL COUNT (): This function returns the number of rows in the table that satisfies the condition specified in the WHERE condition. If the WHERE condition is not specified, then the query returns the total number of rows

in the table. For Example: If you want the number of employees in a particular department, the query would be: SELECT COUNT (*) FROM employee WHERE dept = 'Electronics'; The output would be '2' rows. If you want the total number of employees in all the department, the query would take the form: SELECT COUNT (*) FROM employee; The output would be '5' rows. SQL DISTINCT(): This function is used to select the distinct rows. For Example: If you want to select all distinct department names from employee table, the query would be: SELECT DISTINCT dept FROM employee; To get the count of employees with unique name, the query would be: SELECT COUNT (DISTINCT name) FROM employee; SQL MAX(): This function is used to get the maximum value from a column. To get the maximum salary drawn by an employee, the query would be: SELECT MAX (salary) FROM employee; SQL MIN(): This function is used to get the minimum value from a column. To get the minimum salary drawn by an employee, he query would be: SELECT MIN (salary) FROM employee; SQL AVG(): This function is used to get the average value of a numeric column. To get the average salary, the query would be SELECT AVG (salary) FROM employee; SQL SUM(): This function is used to get the sum of a numeric column To get the total salary given out to the employees, SELECT SUM (salary) FROM employee; SQL GROUP BY Clause The SQL GROUP BY Clause is used along with the group functions to retrieve data grouped according to one or more columns. For Example: If you want to know the total amount of salary spent on each department, the query would be: SELECT dept, SUM (salary) FROM employee GROUP BY dept;

The output would be like: dept salary ---------------- -------------Electrical 25000 Electronics 55000 Aeronautics 35000 InfoTech 30000 NOTE: The group by clause should contain all the columns in the select list expect those used along with the group functions. SELECT location, dept, SUM (salary) FROM employee GROUP BY location, dept; The output would be like: salary ---------------------- --------------Bangalore Electrical 25000 Bangalore Electronics 55000 Mysore Aeronautics 35000 Mangalore InfoTech 30000 SQL HAVING Clause Having clause is used to filter data based on the group functions. This is similar to WHERE condition but is used with group functions. Group functions cannot be used in WHERE Clause but can be used in HAVING clause. For Example: If you want to select the department that has total salary paid for its employees more than 25000, the sql query would be like; SELECT dept, SUM (salary) FROM employee GROUP BY dept HAVING SUM (salary) > 25000 The output would be like: dept salary ------------------------Electronics 55000 Aeronautics 35000 InfoTech 30000 When WHERE, GROUP BY and HAVING clauses are used together in a SELECT statement, the WHERE clause is processed first, then the rows that are returned after the WHERE clause is executed are grouped based on the GROUP BY clause. Finally, any conditions on the group functions in the HAVING clause are applied to the grouped rows before the final output is displayed. SQL HAVING Clause Having clause is used to filter data based on the group functions. This is similar to WHERE condition but is used with group functions. Group functions cannot be used in WHERE Clause but can be used in HAVING clause. location dept

For Example: If you want to select the department that has total salary paid for its employees more than 25000, the sql query would be like; SELECT dept, SUM (salary) FROM employee GROUP BY dept HAVING SUM (salary) > 25000 The output would be like: dept salary ------------------------Electronics 55000 Aeronautics 35000 InfoTech 30000 When WHERE, GROUP BY and HAVING clauses are used together in a SELECT statement, the WHERE clause is processed first, then the rows that are returned after the WHERE clause is executed are grouped based on the GROUP BY clause. Finally, any conditions on the group functions in the HAVING clause are applied to the grouped rows before the final output is displayed. DCL commands are used to enforce database security in a multiple user database environment. Two types of DCL commands are GRANT and REVOTE. Only Database Administrator's or owner's of the database object can provide/remove privileges on a databse object. SQL GRANT Command SQL GRANT is a command used to provide access or privileges on the database objects to the users. The Syntax for the GRANT command is: GRANT privilege_name ON object_name TO {user_name |PUBLIC |role_name} [WITH GRANT OPTION];

privilege_name is the access right or privilege granted to the user. Some of the access rights are ALL,

EXECUTE, and SELECT. object_name is the name of an database object like TABLE, VIEW, STORED PROC and SEQUENCE. user_name is the name of the user to whom an access right is being granted. user_name is the name of the user to whom an access right is being granted. PUBLIC is used to grant access rights to all users. ROLES are a set of privileges grouped together. WITH GRANT OPTION - allows a user to grant access rights to other users.

For Eample: GRANT SELECT ON employee TO user1;This command grants a SELECT permission on employee table to user1.You should use the WITH GRANT option carefully because for example if you GRANT SELECT privilege on employee table to user1 using the WITH GRANT option, then user1 can GRANT SELECT privilege on employee table to another user, such as user2 etc. Later, if you REVOKE the SELECT privilege on employee from user1, still user2 will have SELECT privilege on employee table. SQL REVOKE Command: The REVOKE command removes user access rights or privileges to the database objects. The Syntax for the REVOKE command is:

REVOKE privilege_name ON object_name FROM {user_name |PUBLIC |role_name} For Eample: REVOKE SELECT ON employee FROM user1;This commmand will REVOKE a SELECT privilege on employee table from user1.When you REVOKE SELECT privilege on a table from a user, the user will not be able to SELECT data from that table anymore. However, if the user has received SELECT privileges on that table from more than one users, he/she can SELECT from that table until everyone who granted the permission revokes it. You cannot REVOKE privileges if they were not initially granted by you.

Vous aimerez peut-être aussi