SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.

Slides:



Advertisements
Similar presentations
SQL Rohit Khokher.
Advertisements

Virtual training week 4 structured query language (SQL)
Database Systems: Design, Implementation, and Management Tenth Edition
Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Introduction to Structured Query Language (SQL)
Introduction to Structured Query Language (SQL)
Structured Query Language Part I Chapter Three CIS 218.
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
30-Jun-15 SQL A Brief Introduction. SQL SQL is Structured Query Language Some people pronounce SQL as “sequel” Other people insist that only “ess-cue-ell”
Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
Chapter 3: SQL Data Definition Language Data Definition Language Basic Structure of SQL Basic Structure of SQL Set Operations Set Operations Aggregate.
Introduction to SQL J.-S. Chou Assistant Professor.
Introduction to DBMS and SQL Introduction to DBMS and SQL GUIDED BY : MR. YOGESH SAROJ (PGT-CS) MR. YOGESH SAROJ (PGT-CS) Presented By : JAYA XII –COM.
ASP.NET Programming with C# and SQL Server First Edition
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
3.1 Chapter 3: SQL Schema used in examples p (omit 3.8.2, , 3.11)
Agenda TMA01 M876 Block 3 – Using SQL Structured Query Language - SQL A non-procedural language to –Create database and relation structures. –Perform.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
SQL (DDL & DML Commands)
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
ACTION QUERIES (SQL COMMANDS ) STRUCTURED QUERY LANGUAGE.
1 Structured Query Language (SQL). 2 Contents SQL – I SQL – II SQL – III SQL – IV.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 7 Introduction to Structured.
Topic 1: Introduction to SQL. SQL stands for Structured Query Language. SQL is a standard computer language for accessing and manipulating databases SQL.
Session 2: SQL (A): Parts 1 and 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
BACS 287 Structured Query Language 1. BACS 287 Visual Basic Table Access Visual Basic provides 2 mechanisms to access data in tables: – Record-at-a-time.
Chapter 8: SQL. Data Definition Modification of the Database Basic Query Structure Aggregate Functions.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
SQL. คำสั่ง SQL SQL stands for Structured Query Language is a standard language for accessing and manipulating databases.
Tables and Constraints Oracle PL/SQL. Datatypes The SQL Data Definition Language Commands (or DDL) enable us to create, modify and remove database data.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Prince Sultan University Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
5. Simple SQL using Oracle1 Simple SQL using Oracle 5. Working with Tables: Data management and Retrieval 6. Working with Tables: Functions and Grouping.
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
1 SQL SQL (Structured Query Language) : is a database language that is used to create, modify and update database design and data. Good Example of DBMS’s.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
An Introduction To SQL Part 2 (Special thanks to Geoff Leese)
1 Information Retrieval and Use (IRU) An Introduction To SQL Part 2.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
Distribution of Marks For Second Semester Internal Sessional Evaluation External Evaluation Assignment /Project QuizzesClass Attendance Mid-Term Test Total.
Introduction to Database SEM I, AY Department of Information Technology Salalah College of Technology Chapter No.3 SQL.
CSCI N311: Oracle Database Programming 5-1 Chapter 15: Changing Data: insert, update, delete Insert Rollback Commit Update Delete Insert Statement –Allows.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
1 ORACLE I 3 – SQL 1 Salim Phone: YM: talim_bansal.
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
Fundamentals of DBMS Notes-1.
CHAPTER 7 DATABASE ACCESS THROUGH WEB
SQL Query Getting to the data ……..
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Unit-3 Interactive SQL.
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Presentation transcript:

SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is a standard language for communicating with the RDBMS from any tool.

Processing Capabilities of SQL  Data Definition Language (DDL)  Interactive Data Manipulation Language (DML)  Embedded Data Manipulation Language  View Definition  Authorization  Integrity  Transaction Control

DATA DEFINITION LANGUAGE The SQL DDL Provide commands for  Defining Relations (Create Table)  Deleting Relations (Delete Table)  Creating Indexes (Create index)  Modifying Relations (Alter Table)

DATA MANIPULATION LANGUAGE DML includes query language based on both the relational algebra and the tuple relation calculus. It includes commands to INSERT (Insert into ) INSERT (Insert into ) DELETE (Delete from ) DELETE (Delete from ) MODIFY (Update ) MODIFY (Update )

SQL Data Types:-  Char(n)/ varchar2(n)- to hold character string  Number(n, d)- to hold data of type number n- maximum number of digits n- maximum number of digits d- number of digits to right of decimal point d- number of digits to right of decimal point  Date- to hold data of type date  Long- to hold character of up to 65,535 characters  Raw- to hold data of byte oriented such as graphics  Long raw- similar as Raw but stores 2 Gb

Create table Command- Create table <table-name> (<column-name> <data type> [(<size>)], <column-name> <data type> [(<size>)….]); Eg: To create table Employee with following scheme. Employee(ecode, ename, sex, grade, gross) Create table Employee(ecode number, ename char(20), Sex char(1), grade char(2), gross number(7,2));

Constraint:- AAAA constraint is a condition or check applicable on a field or set of fields. WWWWhen a table is created, constraints are placed on the fields to check the entered values.

Different Constraints:  Unique constraint  Primary key constraint  Default constraint  Check constraint

Unique Constraint This constraint ensures no two rows have same value in the specified columns Eg. Create table employee ( ecode number NOT NULL UNIQUE, Ename char (20) NOT NULL, Sex char(1) NOT NULL, Grade char(2), Gross number(9,2)); UNIQUE Constraint applied on ecode of employee table ensures that no two rows have same ecode value.

Primary Key constraint: Similar to Unique constraint except that only one column or one group of columns can be applied in this constraint. The Primary Key cannot allow NULL values. Eg. Create table employee ( ecode number NOT NULL Primary Key, Ename char (20) NOT NULL, Sex char(1) NOT NULL, Grade char(2), Gross number(9,2));

Default Constraint: This constraint inserts default value for the column if the user does not enter a value for the column. Eg. Create table employee ( ecode number NOT NULL Primary Key, Ename char (20) NOT NULL, Sex char(1) NOT NULL, Grade char(2) Default ‘E1’, Gross number(9,2)); According to above command if no value is provided for grade, the default value of ‘E1’ will be entered. This constraint inserts default value for the column if the user does not enter a value for the column. Eg. Create table employee ( ecode number NOT NULL Primary Key, Ename char (20) NOT NULL, Sex char(1) NOT NULL, Grade char(2) Default ‘E1’, Gross number(9,2)); According to above command if no value is provided for grade, the default value of ‘E1’ will be entered.

Check Constraint: This constraint limits values that can be inserted into a column of a table. Eg. Create table employee ( ecode number NOT NULL Primary Key, Ename char (20) NOT NULL, Sex char(1) NOT NULL, Grade char(2) Default ‘E1’, Gross number(9,2) check (gross>2000); This ensures value inserted for gross must be greater than 2000

Check constraint involving more than one column: Check constraint involving more than one column: Eg. Create table items (icode char(5), Descp char(20), ROL number(5), QOH number(3), Check (ROL< QOH)); Here check constraint was referring to more than one columns, hence it has been in the end of table definition, after all the column definitions

Check constraint can consist of: A list of constant expressions specified using IN A list of constant expressions specified using IN Eg. Decp char(20) CHECK (decp IN (‘NUT’, ‘BOLT’, ‘SCREW’, ‘WRENCH’, ‘NAIL’)) Range of constant expressions using BETWEEN Range of constant expressions using BETWEEN Eg. Prince number(9,2) CHECK(Price BETWEEN and ) A pattern specified using LIKE A pattern specified using LIKE Eg. Ordate char(10) NOT NULL CHECK (ordate LIKE ‘--/--/----’) Multiple conditions using OR, AND etc. Multiple conditions using OR, AND etc. Eg. CHECK (discount = 0.15 AND City= ‘HISSAR’) OR ( discount = 0.13 AND city = ‘JAIPUR’) OR ( discount = 0.13 AND city = ‘JAIPUR’) OR ( discount = 0.17 AND city = ‘MOHALI’)) ( discount = 0.17 AND city = ‘MOHALI’))

SELECT COMMAND: SELECT command make queries on the database. A QUERY is a command that is given to produce certain specified information from the database tables SELECT command make queries on the database. A QUERY is a command that is given to produce certain specified information from the database tables SELECT [,,….] From ; Eg. (1) SELECT empno, ename from emp; (2) SELECT * from emp; (to view all column in emp table) (2) SELECT * from emp; (to view all column in emp table)

DISTINCT keyword: DISTINCT keyword eliminates duplicates rows from the results of a SELECT statement DISTINCT keyword eliminates duplicates rows from the results of a SELECT statement Eg. Select DISTINCT city from Suppliers; Eg. Select DISTINCT city from Suppliers; In the output there would be no duplicate rows. ALL keyword: ALL keyword includes all the rows without considering the duplicate entriesALL keyword includes all the rows without considering the duplicate entries Eg. Select ALL city from Suppliers;Eg. Select ALL city from Suppliers;

Selecting specific Rows- WHERE clause Eg. Select empname, sal from emp where sal > 2900; Eg. Select empname, sal from emp where sal > 2900; This clause will extract only those rows where sal is having value more than Relational Operators- To compare two values, a relational operator is used. The result of the comparison is true or false. Relational Operators recognized by SQL:To compare two values, a relational operator is used. The result of the comparison is true or false. Relational Operators recognized by SQL: =, >, =, <>(not equal to)=, >, =, <>(not equal to)

Eg. Select * from suppliers where city<> ‘DELHI’; Eg. Select * from suppliers where city<> ‘DELHI’; Above query will not display those suppliers details whose city column value is DELHI. Select empname from emp where deptno<>20; Select empname from emp where deptno<>20; Above query will not display those employee names whose dept number is 20

Logical Operators- (OR, AND, NOT) 1) To list the employee details having grades E2 or E3. 1) To list the employee details having grades E2 or E3. Select ecode, ename, grade, gross from employee where (grade=‘E2’ OR grade=‘E3’); 2) To list all the employees’ details having grades as ‘E4’ but with gross < ) To list all the employees’ details having grades as ‘E4’ but with gross < Select ecode, ename, grade, gross from employee where (grade=‘E4’ and gross< 9000); 3) To list all the employees’ details whose grades are other than ‘G1’ 3) To list all the employees’ details whose grades are other than ‘G1’ Select ecode, ename, grade, gross from employee where (NOT grade= ‘G1’);

Condition based on a range- BETWEEN Select icode, descp, QOH From items WHERE QOH BETWEEN 30 and 50; Select icode, descp, QOH From items WHERE QOH BETWEEN 30 and 50; Above query will display only those items whose QOH falls between 30 to 50. Select empno, ename, dept from emp where sal between 2500 and Select empno, ename, dept from emp where sal between 2500 and Above query will display only those employees’ whose salary falls in between 2500 and Select empno, ename, dept from emp where sal Not Between 2500 and Select empno, ename, dept from emp where sal Not Between 2500 and Above query will not display those employee whose salary is not between 2500 and 5000.

Condition based on LIST- IN / NOT IN Select * from members where city IN(‘DELHI’, ‘CHENNAI’, MUMBAI’); Select * from members where city IN(‘DELHI’, ‘CHENNAI’, MUMBAI’); Above query will display the list of members from DELHI, CHENNAI, MUMBAI cities. Select * from members where city NOT IN(‘DELHI’, ‘CHENNAI’, MUMBAI’); Select * from members where city NOT IN(‘DELHI’, ‘CHENNAI’, MUMBAI’); Above query will display the list of members from who are not from cities DELHI, CHENNAI, MUMBAI

Condition Based on Pattern Matches- (‘%’, ‘_’) SQL includes a string-matching operator- SQL includes a string-matching operator- (1) percent (%)- The % character matches any substring (1) percent (%)- The % character matches any substring (2) Underscore (_) - The _ character matches any character. Patterns are case sensitive Eg. (1) To list members which are in area with pincode starting with 13. Select firstname, lastname, city from members where pin LIKE ’13%’;

2) To list employees who have four letters with names ending with ‘D’ 2) To list employees who have four letters with names ending with ‘D’ Select empno, ename from emp where ename LiKE ‘ --- D’; 3) To list employees whose name starts with ‘S’ Select empno, ename from emp where ename LIKE ‘S%’; 4) To list employees whose name’s second character is ‘J’ Select empno, ename from emp where ename LIKE ‘_J%’

Searching for NULL- The NULL value in a column can be searched for in a table using IS NULL in the where clause. The NULL value in a column can be searched for in a table using IS NULL in the where clause. Select empno, ename, job from emp where Deptno IS NULL; (NULL- columns not having value is considered as NULL)

Sorting Results- ORDER BY clause Results of SQL query can be sorted in a specific order using ORDER BY clause Results of SQL query can be sorted in a specific order using ORDER BY clause The ORDER BY clause allows sorting of query results by one or more columns The ORDER BY clause allows sorting of query results by one or more columns The sorting can be done either in ascending or descending order The sorting can be done either in ascending or descending order Eg. Select * from emp order by ename; Above query arranges the records in alphabetical order of ename value. By default order by clause arranges in ascending order.

To display records in descending order To display records in descending order Select * from emp order by ename desc; Above query gives output in descending order of ename Select * from employee ORDER BY grade DESC, ename ASC; Select * from employee ORDER BY grade DESC, ename ASC; Above query displays records first in the descending order of grade and within the same grade employees are displayed in the ascending order of Ename

Performing Calculations- Using SELECT clause calculations can be performed. For this Oracle provides a dummy table called DUAL. SELECT clause always works with a table. Using SELECT clause calculations can be performed. For this Oracle provides a dummy table called DUAL. SELECT clause always works with a table. DUAL table is a small worktable, which has just one row and one column. DUAL table is a small worktable, which has just one row and one column. Select 4*3 from Dual; Output: - 12 Select sysdate from dual; Output:- 06-Jun-08 (Displays current system date)

AGGREGATE FUNCTIONS:- SQL’s aggregate functions: SQL’s aggregate functions: Avg – to compute average value Avg – to compute average value Min – to find minimum value Min – to find minimum value Max – to find maximum value Max – to find maximum value Sum – to find total value Sum – to find total value Count – to count non-null values in a column Count – to count non-null values in a column Count( *) – to count total number of rows in a table Count( *) – to count total number of rows in a table Select avg(sal) from emp; Select min(sal) from emp where deptno= 10; Select count(*) from emp where sal> 3000; Select count (ALL CITY) from members; Select count (DISTINCT CITY) from members;

Grouping Result- GROUP BY Clause GROUP BY Clause is used in SELECT statements to divide the table into groups. GROUP BY Clause is used in SELECT statements to divide the table into groups. To calculate the number of employees in each grade and average gross for each grade of employees To calculate the number of employees in each grade and average gross for each grade of employees SELECT job, count(*), sum(comm) from emp group by job;

Placing conditions on Groups- HAVING Clause The HAVING clause places conditions on groups in contrast to WHERE clause that places conditions on individual rows. The HAVING clause places conditions on groups in contrast to WHERE clause that places conditions on individual rows. WHERE conditions cannot include aggregate functions, HAVING conditions can do so. WHERE conditions cannot include aggregate functions, HAVING conditions can do so. SELECT avg(gross), sum(gross) from employee GROUP BY grade HAVING grade= ‘E4’;

INSERT Command:- INSERT INTO [ ] VALUES (, …); INSERT INTO [ ] VALUES (, …); Eg. INSERT INTO employee VALUES (1001, ’Ravi’, ’M’, ’E4’, ); Eg. INSERT INTO employee VALUES (1001, ’Ravi’, ’M’, ’E4’, ); INSERT INTO employee (ecode, ename, sex, grade, gross) VALUES (1001, ’Ravi’, ’M’, ’E4’, ); INSERT INTO employee (ecode, ename, sex, grade, gross) VALUES (1001, ’Ravi’, ’M’, ’E4’, ); INSERT INTO employee (ecode, ename, sex) VALUES (2014, ’Manju’, ’F’); INSERT INTO employee (ecode, ename, sex) VALUES (2014, ’Manju’, ’F’);

DELETE Command:- DELETE Command removes rows from a table. DELETE Command removes rows from a table. DELETE FROM [WHERE ]; Eg. To remove all the contents of items table Eg. To remove all the contents of items table DELETE From items; To remove the tuples from employee that have gross less than To remove the tuples from employee that have gross less than DELETE From employee WHERE gross< ;

UPDATE Command:- Update Command allows to change some or all the values in an existing rows. Update Command allows to change some or all the values in an existing rows. Update command specifies the rows to be changed using the WHERE clause and the new data using the SET keyword Update command specifies the rows to be changed using the WHERE clause and the new data using the SET keyword Eg. UPDATE items SET ROL= 250; Eg. UPDATE items SET ROL= 250; UPDATE items SET ROL=400, QOH=700 WHERE icode < ‘I040’; UPDATE items SET ROL=400, QOH=700 WHERE icode < ‘I040’; UPDATE employees SET grade=NULL WHERE grade= ‘E4’; UPDATE employees SET grade=NULL WHERE grade= ‘E4’;

VIEW:- VIEW is a virtual table with no data, but can be operated like any other table. VIEW is a virtual table with no data, but can be operated like any other table. It is like a window through which we can view the data of another table, which is called base table. It is like a window through which we can view the data of another table, which is called base table. Using view we can query, update (if allowed), inserted (if allowed), deleted from (if allowed) etc. Using view we can query, update (if allowed), inserted (if allowed), deleted from (if allowed) etc. The SELECT statement used in a view definition cannot include: The SELECT statement used in a view definition cannot include: ORDER BY clause ORDER BY clause INTO clause INTO clause

CREATE VIEW- CREATE VIEW taxpayee AS SELECT * FROM employee WHERE gross > 8000; CREATE VIEW taxpayee AS SELECT * FROM employee WHERE gross > 8000; This view will be having details of those employees that have gross more than Rs. 8000/-.

ALTER TABLE- ALTER TABLE command is used to change the definitions of existing table. ALTER TABLE command is used to change the definitions of existing table. It can be used to add new columns or modify the existing columns of table. It can be used to add new columns or modify the existing columns of table. ALTER TABLE ADD ; ALTER TABLE ADD ; ALTER TABLE MODIFY (columnname newdatatype (newsize)); ALTER TABLE MODIFY (columnname newdatatype (newsize)); Eg. Alter table Emp Add (tel_number integer); Eg. Alter table Emp Add (tel_number integer); ALTER TABLE Emp MODIFY (Job char(30)); ALTER TABLE Emp MODIFY (Job char(30));

DROP TABLE & DROP VIEW DROP TABLE allows to drop table from database. A table with rows in it cannot be dropped. To remove all the rows use DELETE command. DROP TABLE allows to drop table from database. A table with rows in it cannot be dropped. To remove all the rows use DELETE command. Once the DROP command is issued table will no longer be recognized Once the DROP command is issued table will no longer be recognized To delete a view DROP VIEW command is used. When a view is dropped, it does not cause any change in its base table. To delete a view DROP VIEW command is used. When a view is dropped, it does not cause any change in its base table.

Eg. Eg. DROP TABLE EMP; DROP TABLE EMP; DROP VIEW TAXPAYEE; DROP VIEW TAXPAYEE;