Introduction to the Structured Query Language [ SQL ] (Significant Concepts)

Similar documents
(ADVANCED) DATABASE SYSTEMS (DATABASE MANAGEMENTS) PROF. DR. HASAN HÜSEYİN BALIK (6 TH WEEK)

! Define terms. ! Interpret history and role of SQL. ! Write single table queries using SQL. ! Establish referential integrity using SQL

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

SQL STRUCTURED QUERY LANGUAGE

SQL. History. From Wikipedia, the free encyclopedia.

Definition of terms Objectives Interpret history and role of SQL Define a database using SQL data definition iti language Write single table queries u

Module 9: Managing Schema Objects

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

Data about data is database Select correct option: True False Partially True None of the Above

Oracle Database 10g: Introduction to SQL

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Index. Bitmap Heap Scan, 156 Bitmap Index Scan, 156. Rahul Batra 2018 R. Batra, SQL Primer,

Bonus Content. Glossary

RDBMS-Day3. SQL Basic DDL statements DML statements Aggregate functions

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

Database System Concepts and Architecture

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

C Examcollection.Premium.Exam.58q

Chapter 1 SQL and Data

Copyright 2007 Ramez Elmasri and Shamkant B. Navathe Slide 2-1

Business Analytics. SQL PL SQL [Oracle 10 g] P r i n c e S e t h i w w w. x l m a c r o. w e b s. c o m

DATABASE MANAGEMENT SYSTEMS. UNIT I Introduction to Database Systems

CS6312 DATABASE MANAGEMENT SYSTEMS LABORATORY L T P C

Solved MCQ on fundamental of DBMS. Set-1

Relation Databases. By- Neha Tyagi PGT CS KV 5 Jaipur II Shift Jaipur Region. Based on CBSE Curriculum Class -11. Neha Tyagi, PGT CS II Shift Jaipur

B.H.GARDI COLLEGE OF MASTER OF COMPUTER APPLICATION. Ch. 1 :- Introduction Database Management System - 1

Database System Concepts and Architecture. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Sample Question Paper

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

Database System Concepts and Architecture

Relational Database Languages

CGS 3066: Spring 2017 SQL Reference

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)

618 Index. BIT data type, 108, 109 BIT_LENGTH, 595f BIT VARYING data type, 108 BLOB data type, 108 Boolean data type, 109

UNIT-IV (Relational Database Language, PL/SQL)

An Introduction to Structured Query Language

SQL (Structured Query Language)

An Introduction to Structured Query Language

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

Database Management System 9

Oracle Database: Introduction to SQL Ed 2

Course Outline and Objectives: Database Programming with SQL

An Introduction to Structured Query Language

An Introduction to Structured Query Language

CS352 Lecture - Introduction to SQL

Introduction to Computer Science and Business

Subquery: There are basically three types of subqueries are:

SQL: Data De ni on. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 3

Programming the Database

1. Data Model, Categories, Schemas and Instances. Outline

A Unit of SequelGate Innovative Technologies Pvt. Ltd. All Training Sessions are Completely Practical & Real-time

Fundamentals of Information Systems, Seventh Edition

DB Creation with SQL DDL

CS317 File and Database Systems

Copyright 2004 Pearson Education, Inc.

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH

Outline. Textbook Chapter 6. Note 1. CSIE30600/CSIEB0290 Database Systems Basic SQL 2

INTRODUCTION TO DATABASE

Mobile MOUSe MTA DATABASE ADMINISTRATOR FUNDAMENTALS ONLINE COURSE OUTLINE

Oracle SQL & PL SQL Course

Review for Exam 1 CS474 (Norton)

An Introduction to Structured Query Language

Chapter 9: Working with MySQL

Lab # 4. Data Definition Language (DDL)

Relational Database Systems Part 01. Karine Reis Ferreira

The Structured Query Language Get Started

Oracle Database SQL Basics

normalization are being violated o Apply the rule of Third Normal Form to resolve a violation in the model

Slides by: Ms. Shree Jaswal

SQL functions fit into two broad categories: Data definition language Data manipulation language

Concepts of Database Management Seventh Edition. Chapter 4 The Relational Model 3: Advanced Topics

Course Outline. MySQL Database Administration & Design. Course Description: Pre-requisites: Course Content:

Databases and Database Management Systems

Certification Exam Preparation Seminar: Oracle Database SQL

Institute of Aga. Microsoft SQL Server LECTURER NIYAZ M. SALIH

CSIE30600 Database Systems Basic SQL 2. Outline

Basant Group of Institution

Sql Server Syllabus. Overview

Mahathma Gandhi University

Course Outline Faculty of Computing and Information Technology

Table of Contents. Oracle SQL PL/SQL Training Courses

JSPM s Bhivarabai Sawant Institute of Technology & Research, Wagholi, Pune Department of Information Technology

Oracle Database: Introduction to SQL

Chapter-14 SQL COMMANDS

Oracle Syllabus Course code-r10605 SQL

MTA Database Administrator Fundamentals Course

Introduction to Oracle9i: SQL

Assignment Session : July-March

Today Learning outcomes LO2

Introduction To Computers

COMP 3400 Mainframe Administration 1

Brief History of SQL. Relational Database Management System. Popular Databases

Chapter 4: SQL Basics

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

DATABASE CONCEPTS. Dr. Awad Khalil Computer Science & Engineering Department AUC

SQL Interview Questions

Oral Questions and Answers (DBMS LAB) Questions & Answers- DBMS

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Oracle Database: Introduction to SQL/PLSQL Accelerated

Transcription:

Introduction to the Structured Query Language [ SQL ] (Significant Concepts) Learning Objectives This topic is intended to introduce the Structured Query Language (SQL). At the end of the topic it is desired from the reader to be able to: Concisely define each of the following key terms: Relational DBMS (RDBMS) Scalar Aggregate Catalog Vector Aggregate Schema Base TABLE Data Definition Language (DDL) Virtual TABLE Data Manipulation Language(DML) Dynamic View Data Control Language (DCL) Materialized View Referential Integrity Interpret the history and role of SQL in database development. Define a database using the SQL data definition language. Write single-table queries using SQL commands. Establish referential integrity using SQL. 1. Introduction SQL (Pronounced as S-Q-L or sequel ) has become the standard language for creating and querying relational databases. The SQL has been recognized by following institutions: American National Standards Institute (ANSI) Federal Information Processing Standard (FIPS). International Organization for Standardization (ISO) ANSI has accredited the International Committee for Information Technology Standards (INCITS) as a standards development organization; INCITS is working on the next version of the SQL standard to be released. SQL-92 was a major revision and was structured into three levels: Entry, Intermediate, and Full. SQL-99 established core-level conformance, which must be met before any other level of conformance can be achieved; core-level conformance requirements are unchanged in SQL:200n. In addition to fixes and enhancements of SQL-1999, SQL-2003 introduced a new set of SQL/XML standards. Most database management systems claim SQL:1992 compliance and partial compliance with SQL:1999 and SQL:200n. Interpretations of the SQL standard differ from each other, and vendors extend their products capabilities with proprietary features beyond the stated standard. This makes it difficult to port SQL from one vendor s product to another. One must become familiar with the particular version of SQL being used and not expect that SQL code will transfer exactly as written to another vendor s version. Although many of the PC-database packages use a query-by-example (QBE) interface, they also include SQL coding as an option. QBE interfaces use graphic presentations and translate the QBE actions into SQL code before query execution occurs. In Microsoft Access, for example, it is possible to switch back and forth between the two interfaces; a query that has been built using a QBE interface can be viewed in SQL by clicking a button. In client/server architectures, SQL commands are executed on the server, and the results are returned to the client workstation.

The first commercial DBMS that supported SQL was Oracle in 1979. Oracle is now available in mainframe, client/server, and PC-based platforms for many operating systems, including various UNIX, Linux, and Microsoft Windows operating systems. IBM s DB2, Informix, and Microsoft SQL Server are available for this range of operating systems also. 2. Origins Of The SQL Standard The concepts of Relational Database technology were first articulated in 1970, in E. F. Codd s classic paper A Relational Model of Data for Large Shared Data Banks. The first Relational Database Management System (DBMS) available commercially (from IBM). SQL/DS was first available in 1981, running on the DOS/VSE operating system. Purposes of the SQL standard a) To specify the Syntax and Semantics of SQL Data Definition and Manipulation Languages. b) To define the data structures and basic operations for designing, accessing, maintaining, controlling, and protecting an SQL database c) To provide a vehicle for portability of database definition and application modules between conforming DBMSs d) To specify both minimal (Level 1) and complete (Level 2) standards, which permit different degrees of adoption in products e) To provide an initial standard, although incomplete, that will be enhanced later to include specifications for handling such topics as referential integrity, transaction management, user-defined functions, join operators beyond the equi-join, and national character sets. Benefits of the SQL Standard Although most of the vendors provide unique, proprietary features and commands for their SQL database management system; Nevertheless the standard exists and has following benefits: a) Reduced Training Costs An organization can concentrate on one standard language. A large labor pool of Information System (IS) professionals trained in a common language reduces retraining for newly hired employees. b) Productivity Information System professionals can learn SQL thoroughly and become proficient with it from continued use. An organization can afford to invest in tools to help IS professionals become more productive. And because they are familiar with the language in which programs are written, programmers can more quickly maintain existing programs. c) Application Portability Software Applications can be moved from machine to machine when each machine uses SQL. Further, it is economical for the computer software industry to develop off-the-shelf application software when there is a standard language. d) Application Longevity A standard language tends to remain so for a long time; hence there will be little pressure to rewrite old applications. Rather, applications will simply be updated as the standard language is enhanced or new versions of DBMSs are introduced.

e) Reduced Dependence On A Single Vendor When a nonproprietary language is used, it is easier to use different vendors for the DBMS, training and educational services, application software, and consulting assistance; further, the market for such vendors will be more competitive, which may lower prices and improve service. f) Cross-System Communication Different DBMSs and application programs can more easily communicate and cooperate in managing data and processing user programs. On the other hand, a standard can stifle creativity and innovation; one standard is never enough to meet all needs, and an industry standard can be far from ideal because it may be the offspring of compromises among many parties. A standard may be difficult to change (because so many vendors have a vested interest in it), so fixing deficiencies may take considerable effort. Another disadvantage of standards that can be extended with proprietary features is that using special features added to SQL by a particular vendor, may result in the loss of some advantages, such as application portability. Many products are available that support SQL, and they run on machines of all sizes, from small personal computers to large mainframes. The database market is maturing, and the rate of significant changes in products may slow, but they will continue to be SQL based. 3. The SQL Environment With today s relational DBMSs and application generators, the importance of SQL within the database architecture is not usually apparent to the application users; this is so because many users who access database applications have no knowledge of SQL at all. An SQL-based relational database application involves a user interface, a set of TABLEs in the database, and a Relational Database Management System (RDBMS) with an SQL capability. Within the RDBMS, SQL will be used to CREATE the TABLEs, translate user requests, maintain the data dictionary and system catalog, update and maintain the TABLEs, establish security, and carry out backup and recovery procedures. A relational DBMS (RDBMS) is a data management system that implements a relational data model, one where data are stored in a collection of TABLEs, and the data relationships are represented by common values, not links. SQL environment, consistent with SQL-200n standard

The SQL environment includes an instance of an SQL database management system along with the databases accessible by that DBMS and the users and programs that may use that DBMS to access the databases. Each database is contained in a catalog, which describes any object that is a part of the database, regardless of which user CREATEd that object. Each database will have a named schema(s) associated with a catalog. A schema is a collection of related objects, including but not limited to base TABLEs and views, domains, constraints, character sets, triggers, and roles. If more than one user has CREATEd objects in a database, combining information about all users schemas will yield information for the entire database. Each catalog must also contain an information schema, which contains descriptions of all schemas in the catalog, TABLEs, views, attributes, privileges, constraints, and domains, along with other information relevant to the database. The information contained in the catalog is maintained by the DBMS as a result of the SQL commands issued by the users and can be rebuilt without conscious action by the user. It is part of the power of the SQL language that the issuance of syntactically simple SQL commands may result in complex data management activities being carried out by the DBMS software. Users can browse the catalog contents by using SQL SELECT statements. Some definitions related to the SQL Environment a) Relational DBMS (RDBMS) A database management system that manages data as a collection of TABLEs in which all data relationships are represented by common values in elated TABLEs. b) Catalog A set of schemas that, when put together, constitute a description of a database. c) Schema A structure that contains descriptions of objects CREATEd by a user, such as base TABLEs, views, and constraints, as part of a database. d) Data definition language (DDL) Commands used to define a database, including those for creating, ALTERing, and dropping TABLEs and establishing constraints. e) Data manipulation language (DML) Commands used to maintain and query a database, including those for updating, inserting, modifying, and querying data. f) Data control language (DCL) Commands used to control a database, including those for administering privileges and committing (saving) data. Classification of the SQL Commands SQL commands can be classified into three types. a) Data Definition Language (DDL) These commands are used to CREATE, ALTER, and drop TABLEs, views, and indexes. There may be other objects controlled by the DDL, depending on the DBMS. For example, many DBMSs support defining synonyms (abbreviations) for database objects or a field to hold a specified sequence of numbers (which can be helpful in assigning primary keys to rows in TABLEs). In a production database, the ability to use DDL commands will generally be restricted to one or more database administrators in order to protect the database structure from unexpected and unapproved changes. In development or student databases, DDL privileges will be granted to more users.

b) Data Manipulation Language (DML) Many SQL experts consider the DML commands to be the core commands of SQL. These commands are used for updating, inserting, modifying, and querying the data in the database. They may be issued interactively, so that a result is returned immediately following the execution of the statement, or they may be included within programs written in a procedural programming language, such as C, Java, PHP, or COBOL or with a GUI tool (e.g., SQL Assistant with Teradata or MySQL Query Browser). Embedding SQL commands may provide the programmer with more control over timing of report generation, interface appearance, error handling, and database security c) Data Control Language (DCL) These commands help a DBA control the database; they include commands to grant or revoke privileges to access the database or particular objects within the database and to store or remove transactions that would affect the database. Each DBMS has a defined list of Data Types that it can handle. All contain numeric, string, and date/time-type variables. Some also contain graphic data types, spatial data types, or image data types, which greatly increase the flexibility of data manipulation. When a TABLE is CREATEd, the data type for each attribute must be specified. Selection of a particular data type is affected by the data values that need to be stored and the expected uses of the data. A unit price will need to be stored in a numeric format because mathematical manipulations such as multiplying unit price by the number of units ordered are expected. A phone number may be stored as string data, especially if foreign phone numbers are going to be included in the data set. Even though a phone number contains only digits, no mathematical operations, such as adding or multiplying phone numbers make sense with a phone number. And because character data will process more quickly, numeric data should be stored as character data if no arithmetic calculations are expected. Selecting a date field rather than a string field will allow the developer to take advantage of date/time interval calculation functions that cannot be applied to a character field. SQL:200n includes three new data types: BIGINT, MULTISET, and XML. Given the wealth of graphic and image data types, it is necessary to consider business needs when deciding how to store data. For example, color may be stored as a descriptive character field, such as sand drift or beige. But such descriptions will vary from vendor to vendor and do not contain the amount of information that could be contained in a spatial data type that includes exact red, green, and blue intensity values. Such data types are now available in universal servers, which handle data warehouses, and can be expected to appear in RDBMSs as well. It will be necessary to familiarize yourself with the available data types for each RDBMS with which you work to achieve maximum advantage from its capabilities.

Creating TABLEs CREATE TABLE Locations ( Location_ID Number, Lname Varchar2 (50), Address Varchar2 (150) ); CREATE TABLE Departments ( Dept_ID Number, Dname Varchar2(50), Location_ID Number ); CREATE TABLE Employees ( Emp_ID Number, Ename Varchar2(50), Dept_ID Number ); Creating Data Integrity Controls (Constraints) Adding the Primary Key to the Department Table ALTER TABLE Departments Add Constraint Dept_ID_PK Primary Key (Dept_ID); Adding the Foreign Key to the Department Table ALTER TABLE Departments ADD CONSTRAINT Dept_Loc_ID_FK Foreign Key (Location_ID) REFERENCES Locations (Location_ID); Adding the Primary Key to the Employees Table ALTER TABLE Employees ADD CONSTRAINT Emp_ID_PK Primary Key (Emp_ID);

Adding the Foreign Key to the Employees Table ALTER TABLE Employees ADD CONSTRAINT Emp_Dept_ID_FK FOREIGN KEY (Dept_ID) REFERENCES Departments (Dept_ID); Changing (Altering) TABLE Definitions Adding the Salary Column to the Employees Table ALTER TABLE Employees ADD ( Salary Number ); Setting the Salary Column as unused (Not Visible) ALTER TABLE Employees SET UNUSED ( Salary ); Dropping the Columns those are set as unused ALTER TABLE Employees DROP UNUSED Columns; Removing (Dropping) TABLEs Drop Table with name Employees DROP TABLE Employees; Drop Table with name Departments DROP TABLE Departments; Inserting, Updating, and Deleting Data Inserting a Record Only two Attributes or Columns (Dept_ID, Dname) INSERT INTO Departments ( Dept_ID, Dname ) VALUES ( 10, Human_Resource ); Inserting a Record Three Attributes or Columns (Emp_ID, Ename, Dept_ID) INSERT INTO Employees ( Emp_ID, Ename, Dept_ID) VALUES ( 1, Ali, 10);

Inserting a Record Three Attributes or Columns (Emp_ID, Ename, Dept_ID) INSERT INTO Employees ( Emp_ID, Ename, Dept_ID) VALUES ( 2, Safi, 10); Updating a Record in the Employees table, where Emp_ID=1 UPDATE Employees SET Ename = Junaid WHERE Emp_ID = 1; Delete a Record from the Employees table, where Emp_ID=1 Delete From Employees WHERE Emp_ID = 1; Clauses of the SELECT Statement / Processing Single TABLEs Select all attributes in the Employees table (* is used to select all) SELECT * FROM Employees; Selecting on the DISTINCT Employee s ID and Names from the Employees table SELECT DISTINCT Emp_ID, Ename FROM Employees; Selecting Specific attributes / columns (Emp_ID, Ename, Dept_ID) from the Employees table ; Selecting Specific attributes (Emp_ID, Ename, Dept_ID) from the Employees where Emp_ID=2 WHERE Emp_ID = 2; Selecting Specific attributes from the Employees table where Dept_ID is NULL SELECT Emp_ID, Ename FROM Employees; WHERE Dept_ID IS NULL; Selecting Specific attributes from the Employees table, Using the IN Clause. WHERE Emp_ID IN ( 1, 2 );

Selecting Specific attributes from the Employees table, Using the Wild-Characters (%) (it selects all the names those begin with SA) SELECT Ename, Dept_ID FROM Employees WHERE Ename LIKE ' SA% ; Using Expressions Use of the Addition Operator to Select the Salary after Doubling it. SELECT Emp_ID, Salary + Salary AS Double_Salary FROM Employees; Use of the Subtraction and Division Operators to Select the Salary after Deducting half of it. SELECT Emp_ID, Salary - ( Salary / 2 ) AS Half_Salary FROM Employees; Use of the Multiplication Operator to Select the Salary after incrementing it by 50 %. SELECT Emp_ID, Salary * 1.50 AS Salary_Increment FROM Employees; Using Functions Use of the Built-in Single Row functions SELECT Min(Salary), Max(Salary), Avg(Salary) FROM Employees; Use of the GROUP BY clause along with the Built-in Single Row functions SELECT Dept_ID, Min(Salary), Max(Salary) FROM Employees GROUP BY Dept_ID; Using Comparison Operators Use of the comparison operator - Less than or Equal to (< = ) WHERE Emp_ID < = 2 ; Use of the comparison operator - Not Equal to (! = or < > ) SELECT Dept_ID, Dname FROM Departments WHERE Emp_ID! = 2 ;

Using Boolean Operators Use of the Logical (Boolean) operator - AND WHERE Salary > 5000 AND Dept_ID = 10; Use of the Logical (Boolean) operator - OR WHERE Salary > 5000 OR Dept_ID = 10; Use of the Logical (Boolean) operator - NOT WHERE NOT IN ( 10, 20) ; Sorting Results: The ORDER BY Clause SELECT Emp_ID, Ename, Dept_ID FROM Employees WHERE Dept_ID = 10 ORDER BY Emp_ID; Categorizing Results: The GROUP BY Clause SELECT FROM GROUP BY Dept_ID, Sum(Salary), Avg(Salary) Employees Dept_ID; Using the HAVING Clause to Filter the groups according to certain criteria SELECT Dept_ID, Sum(Salary) AS Total_Salary, Avg(Salary) AS Average_Salary FROM Employees GROUP BY Dept_ID HAVING Dept_ID IN ( 10, 20);

Defining and Using Views Creating a View using the Sub Query CREATE VIEW Emp_History ( Employee_ID, Employee_Name, Salary) AS SELECT Emp_id, Ename, Salary FROM Employees WHERE Dept_id IN ( 10, 20 ); Creating a View that does not allow to Change ( INERT, UPDATE, DELELE) its contents CREATE OR REPLACE VIEW Emp_History AS SELECT Emp_id, Ename, Salary FROM Employees WHERE Dept_id = 20 WITH READ ONLY;