Presentation is loading. Please wait.

Presentation is loading. Please wait.

Structured Query Language S Q L. What is SQL It is a database programming language developed by IBM in the early 1970’s. It is used for managing and retrieving.

Similar presentations


Presentation on theme: "Structured Query Language S Q L. What is SQL It is a database programming language developed by IBM in the early 1970’s. It is used for managing and retrieving."— Presentation transcript:

1 Structured Query Language S Q L

2 What is SQL It is a database programming language developed by IBM in the early 1970’s. It is used for managing and retrieving data stored in database system Mostly all DMMS ‘s support SQL

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 database SQL can create tables in a database SQL can create views in a database SQL can set permissions on tables, procedures and tables

4 Advantages of using SQL SQL commands consists of English language words such as create, insert, delete etc, so it is easy to learn SQL is a non procedural language. We simply specify what information is to be retrieved rather than how to retrieve it SQL is a keyword based language. Each command of SQL begins with a unique keyword

5 SQL is a free format language, ie parts of SQL statements do not have to be typed at particular locations on the screen SQL is a portable language. If we follows standard syntax we can move SQL commands from one DBMS to another SQL can be used by variety of users from DBA(Database Administrators), application developers to end users.

6 SQL statements 1.Data Definition Language (DDL) : CREATE,ALTER,RENAME, DROP 2.Data retrieval : SELECT 3.Data Manipulation Language (DML) : UPDATE,DELETE,INSERT 4.Transaction Control Language (TCL) : COMMIT,ROLLBACK,SAVEPOINT 5.Data Control Language : GRANT,REVOKE

7 Data Definition Language (DDL) DDL commands are subset of SQL commands.These commands are used to perform three main function on database objects.(tables).They are 1.Defining or creating database objects through CREATE statement 2.Modifying database objects through ALTER statement

8 Removing definition of database object through DROP statement Definition of all database objects is stored in permanent table called data dictionary. Data dictionary stores data about data called metadata

9 Data Manipulation Language (DML) Subset of SQL commands used to query and manipulate the database. INSERT : Inserting new records in to a table or relation. UPDATE : Modifying existing records. DELETE : Deleting unwanted records.

10 SELECT statement can be considered in the category of DML. It is used to retrieve existing records from the database

11 Types of DML 1.Procedural DML : It not only require a user to specify what data is needed, but also the procedure of how to retrieve the data. 2. Non-Procedural DML : It require only to specify what data is needed without giving details of procedure. Eg : INSERT,UPDATE,DELETE,SELECT

12 Transaction Control Language (TCL) When we make changes on a table suing insert,delete or update,these are temporary changes. COMMIT is used to make theses changes permanent. After applying COMMIT transaction is successfully completed. It is managed by TCL commands

13 COMMIT : used to make the changes permanent ROLLBACK : used to undo all changes of a transaction SAVEPOINT : Identify a point or mark in a transaction since COMMIT. Incase of failure u can undo last transaction, ie rollback up to that save point

14 Data Control Language (DCL) It controls type of data access to the database GRANT : is used to assign user’s access privileges to the database. REVOKE : used to withdraw the access privileges given by GRANT

15 Rules for SQL commands 1.SQL commands can be typed in lower or uppercase. It is not case sensitive 2.It can be typed in a single line or more than one line 3.A semi colon is used to terminate SQL command. 4.A comma (,) can be used to separate parameter 5.Characters and date constraints or literals must be enclosed in single quotes (‘A’)

16 Reserved words can’t be used as identifier’s name. Some of the words are ADD,SET,DATE,CHAR,DROP,ELSE,INTO,LIKE,CREATE,DELETE,VARCHAR,AS,OR,ON,FL OAT,ALTER,CHECK etc A command can be typed either in full or first four characters

17 Database objects 1.Relation or table : used to …………….. 2.View : it is a logical table, part of original table. Different views of database are assigned to different users. 3.Sequence : it is used to identify the records in a table by generating the primary key value to them 4.Index : it improve response time of queries 5.Synonym : Used to give alias name or alternative names to objects

18 Naming conventions 1.Name must be 1 to 30 characters long. Name of the database can be 8 characters long 2.Names of objects are not case sensitive 3.Names should not contain quotation marks 4.First character of the name must be an alphabet. 5.Names of alphabets can have alphanumeric values 6.Reserved words cannot be used for naming objects

19 SQL data types 1.NUMBER It may contain a number with or without decimal point and a sign. An attribute of a relation can have numbers in three forms a). NUMBER : Here we don’t specify the width or precision. Default one ‘ll be taken b). NUMBER (P) : Here we specify the width or precision without any decimal point.

20 It is mainly used for EmpNo, Age c). NUMBER (P,S) : Here we specifies both precision P and scale S. P is total number of decimal digits and Scale S is total number of digits to the right of the decimal point.

21 2. CHARACTER It contain fixed length character data. Abbreviated as CHAR, specified as CHARACTER [(Size)] or CHAR [(Size)]. It is used for Item_code, the length of which remains same for all items

22 3). VARCHAR2 It contain varying length character data and is specified as VARCHAR2 (Size) Maximum size must be given.Attributes such as EName, DName uses this data type in which length varies frequently.

23 4). DATE Used to store date and time value. It is defined simply as DATE It is stored in standard format as DD- MON-RR DD : Day MON : Month RR : Year

24 SQL Commands Points to remember : 1.Every SQL command must be terminated with a semicolon (;) 2.SQL is a case insensitive language

25 Presentation style 1.All SQL key words are written in capital letters 2.Table names are written with their first letter capital 3.All SQL commands are indented properly to provide readability

26 DDL commands 1.CREATE TABLE : Each table in the database is created by using CREATE TABLE command Syntax : CREATE TABLE ( [size], [size]…..);

27 Table name and column name are given by the user. When a table is created it must have at least one column. Table is empty, it has no data. Only the definition of the table is stored in the database. This definition is called schema of the table Eg :::@@ IMP @@:::

28 1.Create a table EMPLOYEE which has the following columns Column NameData TypeDescription of column EmpNo Ename Hire_date Job Salary DeptNo Number (3) Varchar2(30) Date Varchar2(15) Number (7,2) Number (2) Employee Identity Number Employee Name Date of joining of Employee Job title of employee Basic salary of employee Department number of employee

29 CREATE table EMPLOYEE (EmpNo Number (3), EName Varchar2(30), Hire_date Date, Job Varchar2(15), Salary Number (7,2), DeptNo Number (2)) ; Table created

30 Including constraints Constraints : Constraints are the mean by which you can prevent invalid data entry in to the table. Eg : salary must not exceed 30,000.00 Constraints are stored in data dictionary. if we don’t specify the name of the constraint Oracle automatically gives a name. (SYS_Cn) We can view constraint in User_constraint in data dictionary,

31 Defining constraint Various constraints which can be defined on database object are 1.NOT NULL 2.UNIQUE KEY 3.PRIMARY KEY 4.FOREIGN KEY 5.CHECK 6.DEFAULT

32 You can create constraint either 1.At the time when the table is created using CREATE TABLE or 2.After the table has been created using ALTER TABLE. constraint can be defined at two levels when table is created

33 Column level : It is used when it is to be applied on a single column Table level : It is used when it is to be applied on more than one column. All the constraints except NOT NULL can be defined at table level Detail about different types of constraints

34 NOT NULL Null ??? It is a value which is unknown,unavailable, unassigned or inapplicable. It is neither a zero or a blank space, because zero is a numeric value and space is a character. Column of any data type can contain NULLS

35 NOT NULL ensures that the column cannot contain a null value. SQL > Create Table Student ( Name Varchar2 (25) Not Null, Class Number (2) ) ; Explain !!! Here constraint name is unnamed. We can provide name by the command

36 Create Table Student ( Name Varchar2 (25) constraint Name_st Not Null, Class Number (2) ) ; Here Name_st is the constraint name given by us

37 UNIQUE It specifies a column or combination of columns whose value must be unique for all rows in the table. No two rows can have duplicate values. It can be defined at the column level or table level.

38 Column level : It references a single column SQL > Create Table Student (Rollno Number (3) Unique, Name Varchar2(25) Not Null, Class Number (2)) ; Here no two records can have same roll number

39 Table level : It references one or more columns SQL > Create Table Student (Rollno Number (3), Name Varchar2(25) Not Null, Class Number (2), Unique (Rollno)) ; Column included in unique constraint is known as UNIQUE KEY

40 PRIMARY KEY One limitation of candidate key is that it allows null values in the column. Primary key constraint allow two things Unique identification of each row in the table No column that is a part of primary key can contain a null value It can be defined at column or table level

41 Column level : SQL > Create Table Student (Rollno Number (3) PRIMARY KEY, Name Varchar2(25), Class Number (2)) ; Null value and duplicate for Rollno is not allowed

42 Table level : SQL > Create Table Student (Rollno Number (3), Name Varchar2(25), Class Number (2) PRIMARY KEY (Name, Class)) ;

43 FOREIGN KEY It designates a column or combination of columns as a foreign key and establishes it’s relationship with a primary key or unique key in different table. Eg : EMPLOYEE and DEPARTMENT

44 Column level : SQL > CREATE TABLE Employee (EmpNoNumber (3), …………………. salary Number (7,2), DeptNo Number(2) REFERENCES Department (DeptNo) ) ;

45 Table level : SQL > CREATE TABLE Employee (EmpNoNumber (3), …………………. salary Number (7,2), DeptNo Number(2) FOREIGN KEY (DeptNo) REFERENCES Department (DeptNo) ) ;

46 CHECK Values in some of the columns are to be within a certain range or they must satisfy certain condition. Given to column so that all value must satisfy the condition.

47 SQL > CREATE TABLE Employee (EmpNoNumber (3), Ename Varvhar2(30), Salary Number (8, 2)CHECK (salary > 0), …………………… ); We can apply it for table level also

48 DEFAULT It is used to assign a default value to a column. It prevents null entry in a row. SQL > Create Table Student (Rollno Number (3) UNIQUE, Name Varchar2(25) NOT NULL, Class Number (2) Adm_dateDATE DEAFULT SYSDATE );

49 Adding a constraint Syntax : ALTER TABLE Tablename ADD [constraint type] (col) ; Eg : ALTER TABLE Employee ADD PRIMARY KEY (EmpNo) ;

50 Dropping a constraint Syntax : ALTER TABLE Tablename DROP CONSTRAINT Constraint name ; Eg : ALTER TABLE Employee DROP PRIMARY KEY ; OR ALTER TABLE Employee DROP CONSTRAINT EmpName ;

51 Disabling constraints Syntax : ALTER TABLE Tablename DISABLE CONSTRAINT constraint_name ; Eg : ALTER TABLE Employee DISABLE CONSTRAINT EmpNumber ;

52 Enabling constraints Syntax same as that of previous one E g : ALTER TABLE Employee ENABLE CONSTRAINT EmpNumber ;

53 Viewing constraints E g : SELECT constraint_name, column_name from user_cons_columns where tablename = ‘Employee’;

54 Drop table Dropping a table not only deletes the data contained in the table but also removes the definition of it’s structure from the database. Syntax : DROP TABLE ; E g: To drop employee table DROP TABLE Employee ;

55 Alter table The structure of a table can be altered by applying the alter table statement. Table can be altered in one of the three ways 1.By adding a column to an existing table 2.By changing a column definition (data type) 3.By dropping a column of a table.

56 Adding a new column in a table Syntax : ALTER TABLE ADD [constraint definition] ; E g : ALTER TABLE Student ADD grade char(1);

57 SQL > ALTER TABLE Student ADD Percentage Number (3) CHECK (Percentage < =100) ;

58 Modifying existing column It changes the data type or size of an existing column.Here we uses MODIFY clause. Syntax : ALTER TABLE MODIFY ( [size]) ;

59 Here 1.Width of the column can be increased at any time. 2.Number of decimal place in a NUMBER column can be increased or decreased at any time 3.Data type of a column can only be changed if the column contains null values Eg : NUMBER (7, 2) to NUMBER (8, 2) ALTER TABLE Employee MODIFY (Salary Number (8,2));

60 Dropping a column A column can be dropped from a table if it is no longer required. Syntax : ALTER TABLE DROP COLUMN ; We can drop more than one columns at a time ALTER TABLE DROP COLUMN (, ) ;

61 To drop grade from student table sql command is SQL > ALTER TABLE Student DROP COLUMN grade ; It will drop the column’s definition from the database

62 Renaming an object We can change the name of an existing table by using RENAME command. Syntax : RENAME to Eg:RENAME Employee To Empl ;

63 Truncating a table TRUNCATE command deletes all the rows of a table. It empties a table completely Syntax : TRUNCATE TABLE ; E g: TRUNCATE TABLE Employee ;

64 Adding comment to a table Syntax for adding a comment to a column of a table is COMMENT ON COLUMN. IS ‘COMMENT’; Eg :COMMENT ON COLUMN Employee.Job IS ‘Job Title Of Employee’;

65 Comment on table COMMENT ON TABLE Employee IS ‘Details of Employee’;

66 Dropping a comment Syntax : COMMENT ON COLUMN. IS ‘ ’ ; E g : COMMENT ON TABLE Employee IS ‘ ’; COMMENT ON COLUMN Employee.Job IS ‘’;

67 Data manipulation language(DML) These are used to manipulate the existing object of a database such as tables. 1.INSERT statement It is used to store data in a table. Syntax : INSERT INTO [ ] VALUES ( ) ;

68 SQL > INSERT INTO Employee Values (111,’Lucky’,’10-June-2003’,’Clerk’) ; We can view the table by SQL > SELECT * from Employee ;

69 Listing columns in the INSERT clause When we do not want to supply values for all the columns we ‘ll use it. INSERT INTO Employee (Empno,Ename,Hire_date, salary) Values (112,’Mansi’,’05-Sep-2011’,1300) ;

70 Inserting new row with null values INSERT INTO Employee values (112,’Mansi’, ’05-Sep-2011’,NULL,1300,Null);

71 Use of substitution variables to insert values SQL > INSERT INTO Employee values (&Empno, &Empname, &Job, &salary);

72 Copying rows from another table We can insert the rows from another table by INSERT command. Here we insert values in Employee1 from Employee table SQL > INSERT INTO Employee1 Select * from Employee where Empno BETWEEN 103 and 105 ;

73 UPDATE statement It changes or modifies the value of specified column in a table. Syntax : UPDATE SET = where ;

74 Updating multiple rows and multiple columns UPDATE Employee1 SET Salary = Salary + 1500, Job = ‘Manager’ where Deptno IN (11,12,13) ;

75 Setting column values to NULL UPDATE Employee SET job = NULL ;

76 Updating rows based on another table UPDATE Employee1 SET job = ‘Manager ‘ WHERE Empno = (Select EmpNo From Employee where Hire_Date = ’05-Nov-1999’ ) ;

77 DELETE Statement It does exactly opposite to that of an INSERT statement. It is used to DELETE rows from a table Syntax :DELETE [FROM] [WHERE ]; Where clause is used to restrict the number of rows to be deleted

78 DELETE with WHERE clause Syntax :DELETE [FROM] WHERE ; SQL > DELETE from Employee where Salary < 25000 ;

79 DELETE without WHERE clause Syntax : DELETE FROM ; SQL > DELETE FROM Employee1 ; OR DELETE * FROM Employee1 ;

80 Deleting rows based on conditions from another table SQL >DELETE FROM Deptt WHERE DeptNo Not In (Select DeptNo from teacher) ;

81 Transaction control commands A transaction is a unit of work that contains logically related statements. A transaction has a beginning and an end. Commit and rollback statements are used to control transaction.

82 Commit (Making data manipulation permanent) Commit is used to finish the current transaction by making the changes permanent. After applying the commit we cannot retain the previous state of the data.

83 SQL > UPDATE Teacher Set Salary = 18000 Where Tno = 103; SQL >COMMIT;

84 Rollback (Undo data manipulation changes) ROLLBACK is used to cancel or undo all the changes in the current transaction. SQL >UPDATE Teacher Set Salary = 18000 WHERE Tno=103 ; SQL >ROLLBACK ; SQL > Select * from teacher ;

85 Making simple queries (select) It is used to retrieve information from a table. it can be used to access a row, a column, a group of rows, a group of columns or all the rows and columns in a table. Syntax :SELECT,[ …] FROM ;

86 EMPNOENAMEHIRE_DATEJOBSALARYDEPTNO 101Sunil01-Jul-01President2700011 102Pavitra11-Jan-02Clerk1800012 103Seema18-Feb-95Manager2000013 104Sanjay28-Aug-97President2300014 105Deepa05-Nov-99Operator1300011 106Sanker09-Mar- 2006 Manager2200011 107Surekha29-Apr-03President2500013

87 Selecting columns Selecting all columns Syntax :SELECT * FROM ; is used for displaying all the columns from a table. To retrieve all columns from Employee SQL > SELECT * FROM Employee ;

88 Selecting specific columns Syntax :SELECT,,…. FROM ; Display Empno, Ename and job from Employee SQL > SELECT Empno, Ename, Job FROM Employee ;

89 LIKE Operator Powerful feature of SQL is pattern matching using LIKE. Two symbols are used to construct the search string 1. %Represent any sequence of zero or more characters 2. _(underscore)Represent any single character

90 To list all the employees whose names begin with letter ‘S’ in Employee table. SQL >SELECT * FROM Employee WHERE Ename LIKE ‘S%’ ; To list the details of employee having the second character of their name as ‘a ‘ in the table Employee SQL >SELECT * FROM Employee WHERE Ename LIKE ‘_a%’ ;

91 Display name job and department number of employees whose name if of seven characters long from Employee table SQL >SELECT Ename, Job, DeptNo FROM Employee WHERE Ename LIKE ‘_ _ _ _ _ _ _ ’;

92 IS NULL Operator It is for testing null values in a table To list class and name of students who have not been assigned any grade. SQL > SELECT Name, Class FEOM SPORTS WHERE Grade IS NULL ;

93 Set III : Logical operators 1.OR List the rollno, name, game,grade of all students with game either cricket or tennis SQL > SELECT rollno, name, game, grade from SPORTS WHERE game = ‘Tennis’ OR game = ‘Cricket’ ;

94 2. AND List the name game grade of all the students in table SPORTS with game = tennis and grade = A is SQL > SELECT name, game, grade from SPORTS WHERE game= ‘tennis’ AND grade =‘A’;

95 3. NOT List the details of all the students not in class 7,8,10 SQL > SELECT * FROM SPORTS WHERE class NOT IN (7,8,10) ;


Download ppt "Structured Query Language S Q L. What is SQL It is a database programming language developed by IBM in the early 1970’s. It is used for managing and retrieving."

Similar presentations


Ads by Google