STRUCTURED QUERY LANGUAGE (SQL)

Similar documents
INTRODUCTION TO DATABASE

Relational Database Language

Practical 8. SHANKER SINH VAGHELA BAPU INSTITUTE OF TECHNOLGY Subject: - DBMS Branch: - IT/CE Semester: - 3rd. 1. What does SQL stand for?

Chapter-14 SQL COMMANDS

CSC Web Programming. Introduction to SQL

SQL DATA MANIPULATION. Prepared By: Dr. Vipul Vekariya.


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

Lab # 4. Data Definition Language (DDL)

SQL DATA MANIPULATION. Prepared By: Vipul Vekariya M.E( Computer) Gardi College Of Eng. & Tech. Rajkot.

Chapter 13 : Informatics Practices. Class XI ( As per CBSE Board) SQL Commands. New Syllabus Visit : python.mykvs.in for regular updates

ADVANTAGES. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without use of Oracle engine.

None of the techniques used till now allows display of data from a after some arithmetic has been done it. Computations may include displaying

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

Creating and Managing Tables Schedule: Timing Topic

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

SQL Commands & Mongo DB New Syllabus

SQL stands for Structured Query Language. SQL lets you access and manipulate databases

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

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

Unit 1 - Chapter 4,5

The Structured Query Language Get Started

SQL Structured Query Language Introduction

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

tablename ORDER BY column ASC tablename ORDER BY column DESC sortingorder, } The WHERE and ORDER BY clauses can be combined in one

Data Base Concepts. Course Guide 2

CS6312 DATABASE MANAGEMENT SYSTEMS LABORATORY L T P C

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

UNIT III INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL)

A <column constraint> is a constraint that applies to a single column.

Exact Numeric Data Types

Types. Inner join ( Equi Joins ) Outer(left, right, full) Cross. Prepared By : - Chintan Shah & Pankti Dharwa 2

Chapter 9: Working with MySQL

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

ASSIGNMENT NO 2. Objectives: To understand and demonstrate DDL statements on various SQL objects

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

Oracle Database 11g: SQL and PL/SQL Fundamentals

EE221 Databases Practicals Manual

SQL Interview Questions

UNIT-3 RELATIONAL DATABASE MANAGEMENT SYSTEM

Downloaded from

5. Single-row function

Oracle Database: SQL and PL/SQL Fundamentals NEW

SQL is an English like language consisting of commands to store, retrieve, maintain & regulate access to your database.

Introduction to Computer Science and Business

Oracle Syllabus Course code-r10605 SQL

Oracle Database 10g: Introduction to SQL

Oracle Database: SQL and PL/SQL Fundamentals Ed 2

G64DBS Database Systems. Lecture 7 SQL SELECT. The Data Dictionary. Data Dictionaries. Different Sections of SQL (DDL) Different Sections of SQL (DCL)

Oracle. SQL(Structured Query Language) Introduction of DBMS. Build In Function. Introduction of RDBMS. Grouping the Result of a Query

chapter 2 G ETTING I NFORMATION FROM A TABLE

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

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

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

SQL. Char (30) can store ram, ramji007 or 80- b

CMP-3440 Database Systems

SQL language. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

Course Outline and Objectives: Database Programming with SQL

How to use SQL to create a database

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

GridDB Advanced Edition SQL reference

Database Programming with PL/SQL

Data Definition Language (DDL)

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

SQL Data Definition Language: Create and Change the Database Ray Lockwood

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

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

Database Programming with SQL

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

DS Introduction to SQL Part 1 Single-Table Queries. By Michael Hahsler based on slides for CS145 Introduction to Databases (Stanford)

Simple Quesries in SQL & Table Creation and Data Manipulation

Oracle Database: Introduction to SQL/PLSQL Accelerated

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

CSIE30600 Database Systems Basic SQL 2. Outline

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

SQL. Structured Query Language

Simple SQL. Peter Y. Wu. Dept of Computer and Information Systems Robert Morris University

Today Learning outcomes LO2

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

@vmahawar. Agenda Topics Quiz Useful Links

1. Using Bitvise SSH Secure Shell to login to CS Systems Note that if you do not have Bitvise ssh secure shell on your PC, you can download it from

Data Manipulation Language

1 Prepared By Heena Patel (Asst. Prof)

Introduction to SQL. SQL is a standard language for accessing and manipulating databases. What is SQL?

Laboratory Manual. For. Database Management System (IT 502) B.Tech (IT) SEM V. June 2010

Database Programming with SQL

Relational Data Structure and Concepts. Structured Query Language (Part 1) The Entity Integrity Rules. Relational Data Structure and Concepts

Advanced SQL Tribal Data Workshop Joe Nowinski

UNIT 4 DATABASE SYSTEM CATALOGUE

Introduction to Computer Science and Business

Lecture 5. Monday, September 15, 2014

Full file at

Database Management System 9

EDUVITZ TECHNOLOGIES

Relational Database Languages

Structured Query Language. ALTERing and SELECTing

Oracle Tables TECHGOEASY.COM

Oracle Database: Introduction to SQL

Retrieving Data Using the SQL SELECT Statement. Copyright 2009, Oracle. All rights reserved.

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

Transcription:

1 SQL

STRUCTURED QUERY LANGUAGE (SQL) The first questions to ask are what is SQL and how do you use it with databases? SQL has 3 main roles: Creating a database and defining its structure Querying the database to obtain the data necessary to answer questions Controlling database security 2

INTRODUCTION TO SQL Structured Query Language(SQL) is a language that provides and interface to relational database system. SQL was developed by IBM in 1970s for use insystem R. SQL is often pronounced SEQUEL( Structured English Query Language). 3

WHAT CAN SQL DO? SQL can execute queries against a database SQL can retrieve data from a database SQL can insert records in a database SQL can update records in a database SQL can delete records from a database SQL can create new databases SQL can create new tables in a database SQL can create stored procedures in a database SQL can create views in a database SQL can set permissions on tables, procedures, and views 4

INTRODUCTION TO SQL Concept of SQL The user specifies a certain condition. The program will go through all the records in the database file and select those records that satisfy the condition.(searching). Statistical information of the data. The result of the query will then be stored in form of a table. 5

FEATURE OF SQL 1. SQL can be used by a range of users, including those with little or no programming experience. 2. It is a no procedural language. 3. It reduce the amount of time required for creating and maintain systems. 4. It is an English-like language. 6

FEATURES OF SQL *PLUS 1. SQL *PLUS accepts ad hoc entry of statements. 2. It accepts SQL input from files. 3. It provides a line editor for modifying SQL statements. 4. It controls environmental settings. 5. It formats query results into basic reports 6. It accesses local and remote databases 7

RULES FOR SQL 1. SQL starts with a verb(i.e. SQL action word). Example: SELECT statements. This verb may have additional adjectives. Example: FROM 2. Each verb is followed by number of clauses. Example: FROM, WHERE, HAVING 3. A space separates clauses. Example: DROP TABLE EMP; 4. A comma(,) separates parameters without a clause. 5. A ; is used to end SQL statements 6. Statements may be spilt across line but keywords may not 8

1. Reserved can not be used as identifiers unless enclosed with double quotes. Reserved words are: AS, ASC,INTO, ALTER, ROWID etc. 2. Identifiers can contain up to 30 characters and must start with an alphabetic character 3. Character and data literal must be enclosed within single quotes. 4. Comments may be enclosed between /* and */ symbols and may be multi line. Single line comments may be prefixed within a - symbol 9

SQL DELIMITERS + Addition Quote identifier - Subtraction : Host variable * Multiplication ** Exponential / Division <>! =^= Relational = > < Relational < = > = Relational ( ) Expression or list := Assignment ; Terminator => Association % Attribute indicator Concatenation, Item Separator << Label. Component selector >> Label @ Remote access indicator Character string delimiter -- Comments /* */ Comment(multi line) 10

COMPONENTS OF SQL DDL (Data Definition Language) : - it is a set of SQL commands used to create, modify, and delete database structures but not data. These commands are normally not used by a general user. They are normally used by the DBA. These statements are immediate i.e. they are not susceptible to ROLLBACK commands. 11

DML(Data Manipulation Language) : - It is the area of SQL that allows changing data within database DCL(Data Control Language) : - It is the component of SQL statement that control access to data and to the database. Occasionally DCL statements are grouped with DML statements. DQL(Data Query Language) : - It is the component of SQL statement that allows getting data from the database and imposing ordering upon it. In includes the SELECT statement. This command is the heart of SQL. It allows getting the data out of the database perform operations with it. When a SELECT is fired against a table/s the result is compiled into a further temporary table, which is displayed or perhaps received by the programmer. 12

EXAMPLE DDL : Data Definition Language Examples CREATE : To create objects in the database ALTER : Alters the structure of the database DROP: Delete object from the database TRUNCATE : Remove all records from a table, Including all spaces allocated for the records are removed COMMENT: Add comments to the data dictionary GRANT: Give user's access privileges to database REVOKE: Withdraw access privileges given with the GRANT command. 13

DML : Data Manipulation Language Examples: INSERT : Insert data into a table UPDATE : Updates existing data within a table DELETE : Deletes all records from a table, the space for the records remain CALL : call a PL/SQL or Java Subprogram EXPLAIN PLAN : Explain access path to data LOCK : TABLE control concurrency 14

DCL : Data Control Language Statements Example COMMIT : Save work done SAVEPOINT : Identify a point in a transaction to which you can later roll back ROLLBACK : Restore database to original since the last COMMIT SET TRANSCATION : Change transaction options like what rollback segment to use GRANT / REVOKE : Grant or take back permission to or from the oracle users. DQL : Data Query Language statement Examples : SELECT : Retrieve data from the a database 15

RELATIONAL MODEL Current popular DBMS(RDBMS) --DB2 & Informix Dynamic server from IBM --Oracle & Rd from Oracle --SQL Server from Access from Microsoft 16

ORACLE DATA TYPES CHAR(size) : - This data type is used to store character strings values of fixed length. The size of brackets determines the number of characters the cell can hold. The maximum number of characters this data type can hold is 255 characters. The data held is right padded with spaces to whatever length specified. VARCHAR / VARCHAR2 : - This data type is used to store variable length alphanumeric data. It is more flexible form of the CHAR data type. The maximum this data type can hold up to 4000 characters. VARCHAR can hold up to 255 characters. CHAR is much faster than VARCHAR, may be up to 50% 17

DATE : - This data type is used to represent data and time. The standard format is DD-MMM-YY as in 29-APR- 11. to enter dates other than the standard format, use the appropriate functions. DateTime stores date in the 24-hour format. NUMBER(P,S) : -The NUMBER data type is used to store numbers(fixed or floating point). Numbers of virtually any magnitude may be stored up to 38 digits of precision. The precision (P), determines the maximum length of the data, whereas the scale (S), determines the number of places to the right of the decimal. If scale is omitted then the default is zero. If the precision is omitted, values are stored with their original precision uptothe maximum of38 digits 18

LONG : - This data type is used to store variable length character string containing up to 2 GB. Only one LONG value can be defined per table. LONG values can not be used in sub queries, function, expressions, where clauses or indexes and the normal character functions such as SUBSTR can not applied to LONG values. RAW / LONG RAW : - The RAW / LONG RAW data types are used to store binary data, such as digitized picture or image. Data loaded into columns of these data types are stored without any further conversion. RAW data type can have a maximum length of 255 bytes. LONG RAW data type can contain up to 2 GB. 19

TABLE The foundation of every Relational Database Management System is a database object called table. Every database consists of one or more tables, which store the database s data/information. Each table has its own unique name and consists of columns and rows. The database table columns (called also table fields) have their own unique names and have a pre-defined data types. Table columns can have various attributes defining the column functionality (the column is a primary key, there is an index defined on the column, the column has certain default value, etc.) While table columns describe the data types, the table rows(tuple) contain the actual data for the columns. 20

Columns(Attributes, Fields) Data Types ID No.(NUMBER) Name (CHAR) Mobile(VARCHAR2) 1 Chintan 9498900000 2 Pankti 89676897080 Row (Data, tuple) 21

CREATE TABLE COMMAND This command is use for creating a table. Rules for creating tables A name can have maximum up to 30 characters. A-Z, a-z, 0-9 allowed A name should be begin with an alphabet The use of special character like _ allowed and also recommended SQL reversed words not allowed.(ex. create, select and so on.) 22

SYNTAX FOR CREATE TABLE CREATE TABLE TABLENAME ( ATTRIBUTES1 DATATYPE(SIZE), ATTRIBUTES 2 DATATYPE(SIZE), ATTRIBUTES 3 DATATYPE(SIZE) ); Table Created 23

P_ID LASTNAM E CREATE TABLE PERSON ( P_ID NUMBER(5), LASTNAME CHAR(50), FIRSTNAME CHAR(50), EXAMPLE ADDRESS VARCHAR2(100), CITY VARCHAR2(30) ); FIRSTNA ME ADDRESS CITY Table Created 24

INSERT DATA INTO TABLE Syntax INSERT INTO TABLENAME (ATTRIBUTES1, ATTRIBUTES2, ATTRIBUTES3) VALUES ( VALUE1, VALUE2, VALUES3 ); Note : When we are inserting values in table, if data type of table is NUMBER in that case do not provide. In all other data types, provides. Also match table attributes and values that provide. 25

EXAMPLE P_ID LASTNAME FIRSTNAM E ADDRESS CITY 1 SHAH CHINTAN MAHARAJ A INSERT INTO PERSON ( P_ID, LASTNAME,FIRSTNAME,ADDRESS,CITY) VALUES AHMEDABA D (1, SHAH, CHINTAN, MAHARAJA, AHMEDABAD ); OUTPUT : - 1 ROW CREATED 26

EXERCISE TIME Insert more data in same table P_ID LASTNAME FIRSTNAME ADDRESS CITY 1 SHAH CHINTAN MAHARAJA AHMEDABAD 2 IVAN BAYROSS CARLISLE NJ 3 SHAH KHUSHBU PARUL AHMEDABAD 27

VIEWING DATA IN THE TABLES Syntax : - SELECT * FROM TABLENAME; Example SELECT * FROM PERSON; 28

NOW DISPLAY ALL THE TABLE Query : Select * from tab; Display list of all tables. 29

Displaying Table Structure Syntax DESC table_name; Example Desc abc; 30

INSERT MULTIPLE ROWS IN TABLE QUERY INSERT INTO persons values (&ID, &LASTNAME, &FIRSTNAME, &ADDRESS, &CITY ); 31

32

FILTERING TABLE DATA Selected Columns And All Rows Syntax : SELECT columnname1,columnname2 FROM Table Name ; Example : 33

PROBLEM? Here when I am retrieving details of table, we will get all data of table, but if we want to restrict the data or we want specific person s data 34

FILTERING TABLE DATA Selected Rows and All Columns Syntax : SELECT * FROM table_name WHERE = CONDITION ; Example : 35

FILTERING TABLE DATA Selected Rows and selected Columns Syntax : SELECT column1,column2 FROM table_name WHERE = Condition ; Example : SELECT P_ID, LASTNAME,CITY FROM PERSONS WHERE NAME= KHUSHBU ; 36

DISTINCT Eliminating duplicate rows The DISTINCT clause removing duplicates from the result set. The DISTINCT clause can only used with select statements. Syntax SELECT DISTINCT COLUMNNAME1 FROM TABLENAME; 37

Example WE USE THE FOLLOWINGSELECT STATEMENT FOR RETRIEVING CITY 38

SEE DIFFERENCE 39

SORTING DATA IN A TABLE Oracle allows data from a table to be viewed in a sorted orders. The rows retrieved from the table will be sorted in either ascending or descending order. The ORDER BY keyword is used to sort the resultset by 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. 40

SQL ORDER BY SYNTAX SELECT * FROM TABLE_NAME ORDER BY COLUMN_NAME(S) ASC DESC 41

EXAMPLE 42

We use the following SELECT statement: SELECT * FROM PERSON ORDER BY LASTNAME; P_ID LASTNAME FIRSTNAM E ADDRESS CITY 3 PANDYA NITIN TALOD GANDHINA GAR 2 PATEL SANJAY GANDHINA GAR GANDHINA GAR 4 PATEL VISHAL GHATLODIA AHMEDABA D 1 SHAH CHINTAN SATELLITE AHMEDABA 43 D

ORDER BY DESC example SELECT * FROM persons ORDER BY LASTNAME DESC; P-ID LASTNAME FIRSTNAM E ADDRESS CITY 1 SHAH CHINTAN SATELLITE AHMEDABA D 4 PATEL VISHAL GHATLODIA AHMEDABA D 2 PATEL SANJAY GANDHINA GAR GANDHINA GAR 3 PANDYA NITIN TALOD GANDHINA GAR 44

DELETE STATEMENT Removal of all ROWS -Syntax DELETE FROM PERSONS; -All rows deleted 45

QUESTION: - If I want to retrieve data of persons table. What will happen? What will be an answer? 46

UPDATING CONTENS OF A TABLE The UPDATE command is used to change or modify data values in a table. SQL UPDATE Syntax UPDATING ALL ROWS UPDATE TABLENAME SET COLUMNNAME1= NEW VALUE, COLUMNNAME2 = NEW VALUE; 47

EXAMPLE Now we want to UPDATE LASTNAME in persons table 48

OUTPUT 49

UPDATE RECORDS CONDITIONALLY UPDATE table_name SET columnname= value, columnname= value2 WHERE columnname= value 50

EXAMPLE Now we want to UPDATE Lastname from ABC to SHAH, whose FIRSTNAME IS CHINTAN 51

MODIFY STRUCTURE OF TABLE ADDING new columns in existing table. Syntax ALTER TABLE TABLENAME ADD (NEW COLUMNNAME DATATYPE(SIZE)); 52

NOW WE WANT TO ADD PINCODE FIELDS IN PERSONS TABLE 53

54

EXERCISE TIME NOW INSERT PINCODE IN EXISTING ROWS OF PERSONS TABLE. 55

MODIFY STRUCTURE OF TABLE MODIFY columns in existing table. Syntax ALTER TABLE TABLENAME MODIFY (COLUMNNAME NEWDATATYPE (NEWSIZE)); 56

NOW WE WANT TO MODIFY PINCODE DATA TYPE FROM VARCHAR2 TO NUMBER IN PERSON TABLE. 57

58

RESTRICTIONS ON ALTER TABLE Following task cannot be performed Change name of table Change name of column Decrease size of column if data exists 59

Syntax : RENAMING TABLES RENAME TableName TO NewTableName ; Problem RENAME PERSON table TO CLIENT table 60

TRUNCATING TABLES EXAMPLE : TRUNCATE TABLE PERSONS; Table Truncated. Similar to DELETE Find out difference Delete table tablename; & truncate table tablename; 61

DESTROYING TABLES EXAMPLE: DROP TABLE PERSON; Table Dropped. 62

PREPARED BY: - Chintan Shah & Pankti Dharwa Assistant Professor, Shankersinh Vaghela Bapu Institute of Technology 63