11
SPECTRUM STUDY CIRCLE (The Acme of Excellence) 15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M) Class: XII C++ STRUCTURED QUERY LANGUAGE * Structured Query Language (SQL) is a language that enables to create and operate on relational databases, which are sets of related information stored in tables. * Data Definition Language (DDL): The SQL DDL provides commands for defining relation schema, deleting relations, creating indexes, and modifying relation schemes. * Data Manipulation Language (DML): The SQL DML includes a query Language bases on both relational algebra and tuple relational calculus. It includes commando to insert, delete and modify tuples in database. DATA DEFINITION LANGUAGE A database scheme is specified by a set of definitions which are expressed by a special language called DDL. The result of compilation of DDL statement is set of tables stored in data dictionary (or directory) * DATA DICTIONARY is file that contains “meta data” i.e. “data about data”. DATA MANUPULATION LANGUAGE After the database scheme has been specified ‘&’ database has been created, the data can be manipulated using a set of procedures which are expressed by a special language called Data manipulation Language → The retrieval of information stored in data base. → The insertion of new information into database. → The deletion of information from database → The modification of data stored in database Hence, DML is a Language that enables users to access or manipulate data as organized by the appropriate data model The DMLs are basically of two types Procedural DML → requires user to specify what data is needed and how to get it Non procedural DML → requires user to specify what data is needed without specifying how to get it. Concept of SQL Processing * CHAR (or character): Values of this type must be enclosed in single quotes such as ‘example’ * INT (or integer) : represents a number without a decimal point * FLOAT : represents a floating point number in base 10 exponential notation. The size argument consists of a single number specifying minimum precision. 1

SQL

Embed Size (px)

DESCRIPTION

SQL NOTES , DBMS , SQL, Assignment , C++ , 12th CBSE

Citation preview

Page 1: SQL

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ STRUCTURED QUERY LANGUAGE

* Structured Query Language (SQL) is a language that enables to create and operate on relational databases, which are sets of related information stored in tables.

* Data Definition Language (DDL): The SQL DDL provides commands for defining relation schema, deleting relations, creating indexes, and modifying relation schemes.

* Data Manipulation Language (DML): The SQL DML includes a query Language bases on both relational algebra and tuple relational calculus. It includes commando to insert, delete and modify tuples in database.

DATA DEFINITION LANGUAGEA database scheme is specified by a set of definitions which are expressed by a special language called DDL. The result of compilation of DDL statement is set of tables stored in data dictionary (or directory)

* DATA DICTIONARY is file that contains “meta data” i.e. “data about data”.

DATA MANUPULATION LANGUAGEAfter the database scheme has been specified ‘&’ database has been created, the data can be manipulated using a set of procedures which are expressed by a special language called Data manipulation Language→ The retrieval of information stored in data base.→ The insertion of new information into database.→ The deletion of information from database→ The modification of data stored in database

Hence, DML is a Language that enables users to access or manipulate data as organized by the appropriate data model

The DMLs are basically of two types Procedural DML → requires user to specify what data is needed and how to get it Non procedural DML → requires user to specify what data is needed without specifying how to get

it.Concept of SQL Processing

* CHAR (or character): Values of this type must be enclosed in single quotes such as ‘example’ * INT (or integer) : represents a number without a decimal point* FLOAT : represents a floating point number in base 10 exponential notation. The size

argument consists of a single number specifying minimum precision.* DEC (or decimal) : represents fractional numbers as17.321, here size argument has two part,

precision & scale given size (5,2) indicates precision as 5 & scale as 2. Here scaled cannot exceed the precision

Keywords are words that have special meaning in SQL commands/statements are instructions given to SQL database command consists of one or more logically distinct partscalled CLAUSESExample WHERE VALUE = 150.00, or

FROM Sales* Tables are defined with CREATE TABLE command* When a table is created, its columns are named, data types & sizes are supplied for each column

// To create an employee table whose scheme isemployee (ecode, ename, sex, grade)

The SQL command will beCREATE TABLE employee(

Ecode integer,ename char (20);sex char (1);grade char (2);

1

Page 2: SQL

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ STRUCTURED QUERY LANGUAGE

SYNTAXCREATE TABLE < table – name>(<column-name> <data type> [ (<size>)],<column name> <data type> [(<size>)].............) ;CREATE TABLE employee(

ecode integer Not Null Unique,ename, char (20) Not Null,Sex char (1) );

Note: UNIQUE Constraint is always applied to Not NullPRIMARY KEY CONSTRAINTThis constraint declares a column as primary key of table. It is similar to UNIQUE, except that only one column (or One group of columns can be applied in this. It cannot allow Null Values

CREATE TABLE employee(ecode integer Not Null PRIMARY KEY,ename char (20) Not Null,Sex char (1) );

DEFAULT CONSTRAINTWhen a year does not enter a value for column, it can set automatically the defined default value for that column* NOT NULL columns cannot have NULL as default * A column can have only one default value

CHECK CONSTRAINTIt limits values that can be inserted into a column of a table

CREATE TABLE employee(ecode integer NOT NULL PRIMARY KEY,ename char(20) NOT NULL,sex char (1) NOT NULL,grade char (2) DEFAULT = ‘E’gross decimal CHECK (gross > 2000);

* This statement ensures that value inserted for gross must be greater than 2000* It is specified after all, the column, when it involves more than one column

CREATE TABLE items(icode char(5),descp char (20),ROL integer,QOH integer,CHECK (ROL < QOH);

Compares two columns ROL and QOH, hence two columns must defined before check constraint.

Examples of CHECK CONSTRAINT USING ‘IN’→ descp char (20) CHECK (descp IN (‘NUT’, ‘BOLT’, ‘SCREW’) )→ Price decimal CHECK (price BETWEEN 253.00 and 777.00)→ CHECK ( (discount = 0.15 AND city = ‘HISSAR’ ) OR

(discount = 0.13 AND city = ‘JAIPUR’) OR

2

Page 3: SQL

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ STRUCTURED QUERY LANGUAGE

(discount = 0.17 AND city = ‘DELHI’) )TABLE CONSTRAINTWhen a Constraint is applied on a group of columns of table, it is called table constraint

CREATE TABLE items(icode char (5) NOT NULL,descp char (20) NOT NULL,ROL integer,QOH integer,CHECK (ROL < QOH),UNIQUE (icode, descp) );

If you want to declare A PRIMARY KEY as combination firstname and lastname, it can be done asCREATE TABLE members(first name char (15) NOT NULL,last name char (15) NOT NULL,city char (20),PRIMARY KEY (firstname, lastname));

SELECT COMMANDTo make queries on databaseQuery is a command that is given to produce certain specified information from database table

If you want to view only two columns empno and empnameSELECT Empro, EmpnameFROM emp,

SYNTAXSELECT < column name > [, >column-name>,.............]FROM < table name>;

* All Keyword retains the duplicate output rows It is just same when you specify neither Distinct nor AllSelect All city From suppliers;

The output will beCityDelhi

MumbaiDelhi

BangloreJaipur

* SELECTING SPECIFIC ROWS For such condition, when certain rows are needed, we use ‘WHERE” clause

SYNTAX: SELECT < column name > [,<column name>,.............]FROM < table name >WHERE < condition> ;

Example: SELECT empname, empno, salFROM empWHERE (Sal > 2900) ;

Relational Operators= , >, <, > = , < = , < >LOGICAL OPERATORSOR, AND, NOTexample: SELECT * FROM suppliers

Where City < > ‘DELHI’ ; (OR)

SELECT ecode, ename, grade, gross

3

Page 4: SQL

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ STRUCTURED QUERY LANGUAGE

FROM employeeWHERE (grade = ‘E4’ AND gross < 9000);SELECT icode, descp, QOHFROM itemsWHERE QOH BETWEEN 30 AND 50 ;

(Condition Based on Range)This query will list the items whose ROC is below 100 and above 1000SELECT icode, descpFROM itemsWHERE ROL NOT BETWEEN 100 AND 1000 ;

// Condition Based on ListSELECT * FROM membersWHERE city IN (‘DELHI’, ‘MUMBAI’, ‘CHENNAI’ ) ;SELECT * FROM membersWHERE city NOT IN (‘DELHI’, ‘MUMBAI’);It will list members not from the cities mentioned in list

PATTERN MATCHES% Character matches any substring(-) under score matches any character* “LIKE” keyword is used to select rows containing colkumns that match pattern→ “San %” matches any string beginning with “San”→ “% bid%” matches any string containing “bid”as substring → “ - - - - - -“ matches any string of exactly 4 characters→ “- - - - - - %” matches any string of at least 3 characters→ SELECT firstname, lastname, city FROM members WHERE pin like “13%”;

// To list employees of names of 4 character endline with “D”→ SELECT empno, empname FROM emp WHERE empname LIKE “ - - - - - -D”;

// Searching for Null → SELECT empno, empname, Job FROM emp WHERE DeptNo IS NULL;

* SORTING RESULTS BY “ORDER BY” CLAUSE// To display list of employees in ascending order of their names

SELECT * FROM employee ORDER BY ename;

// To display list of employees in descending order of employee code SELECT * FROM employee ORDER BY ecode DESC; SELECT * FROM employee ORDER BY grade DESC, ename ASC.

// For simple calculations, the Dual table is used. It is dummy table Select 4 * 3 FROM dual

Output: 4 * 3 = 12// To find system dateSELECT Sysdate FROM dual ; AGGREGATE FUNCTIONSavg → To compute average valuemin → To find minimum value

4

Page 5: SQL

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ STRUCTURED QUERY LANGUAGE

max → To find maximum valuesum → To find total valueStddev → To find standard deviationCount → To count non-null values in a columnCount (*) → To count total number of rows in a tableVariance → To compute variance of values in column→ SELECT sum (gross) FROM employee WHERE grade = ‘E2’→ SELECT avg (gross) FROM employee WHERE (grade = ‘E2’ OR grade = ‘E1’); To display the average gross of employee with grades ‘E1’ or ‘E2’→ SELECT count (*) FROM employee;

To count no of employees in employee table→ SELECT count (DISTINCT city) FROM members;→ SELECT Count (All city) FROM members;Grouping Results – GROUP BYSelect Job, Count (*), Sum (comm.) empGROUP BY job ;

It is used to divide the table into groups. It is done by column name or with aggregate functionGROUP BY applies the aggregate functions independently to a series of groups that are defined by having a field value in common

Job COUNT (*) SUM (COMM)PRESIDENTMANAGERSALESMANANALYST

1342

0022000

* HAVING clause places conditions on groups, WHERE clause places conditions on individual rows.→ SELECT Job, Count (*) FROM emp

GROUP BY jobHAVING Count (*) < 3 ;

JOB COUNT(*)PRESIDENTANALYST

12

→ SELECT avg (gross), sum (gross)FROM employeeGROUP BY gradeHAVING grade = ‘E4’ ;

// Scalar expression with selected fields→ SELECT Salesman-name, Comm*100

FROM Salesman;// Putting Text in Query output→ SELECT Salesman-name, Comm*100, ‘%’

FROM Salesman;Salesman-name

AJAYAMIT

13.00%11.00%

5

Page 6: SQL

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ STRUCTURED QUERY LANGUAGE

SHALLY 07.00%→ SELECT salesman-name, ‘gets the commission’, Comm*100, ‘%’ FROM Salesman ;o/p : Ajay gets the commission 13.00%

Amit gets the commission 11.00%Shally gets the commission 07.00%

SELECT SYNTAXSELECT column listFROM < table name >WHERE < predicate >GROUP BY < column name >HAVING < search condition >ORDER BY column-name ;

CREATING TABLE FROM EXISTING TABLE→ CREATE TABLE orditem AS

(SELECT icode, descpFROM itemsWHERE (QOH < ROL) );It will create New table orditem from old table items

→ SELECT icode, descp INTO orditemsFROM itemsWHERE (QOH < ROL);

It is same o/p, by implementation of SELECT INTO CommandUNION – COMBINING QUERIES

* It operates on two or more queries by combining results into a single setIF Relation A Relation B

Roll no Name Age Roll no Name Age1 A1 15 4 A4 172 A2 16 7 A7 193 A2 17 5 A5 18

3 A3 17→ SELECT * FROM A

UNIONSELECT * FROM B ;Roll no Name Age123475

A1A2A3A4A7A5

151617171918

SELECT empno, empnameFROM Accounts → Relation 1UNIONSELECT empno, empnameFROM Sales → Relation 2ORDER BY empno desc;

* FOR UNION OPERATOR, the select lists must have same number of columns having similar data types & order→ SELECT ecode, ename

FROM R1

6

Page 7: SQL

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ STRUCTURED QUERY LANGUAGE

UNIONSELECT ename, ecodeFROM R2

* IN UNION operator, the ORDER BY occur at end of UNION. It can’t be used with in individual queries, BUT, GROUP BY & HAVING CLAUSES are allowed within individual queries, since these cannot be used to affect final Result set

INTERSECT OPERATORIt gives those rows that are common in multiple tables

SELECT job FROM AccountsINTERSECTSELECT job FROM ResearchINTERSECTSELECT job FROM Sales ;

O/p: Manager(Since all the relations have Manager Job in common)

MINUS OPERATION(A –B) Part/portion of A, which is not in B hence, all the rows that are selected by first Query, which are not

in following querySELECT job FROM AccountsMINUSSELECT job FROM Sales

O/p only the jobs that are in Accounts relation but not in sales relationINSERT COMMANDSyntax: INSERT INTO < tablename > [< column List >

VALUES ( < value >, <value > , - - - - - - - );→ INSERT INTO employee (ecode, ename, sex)

VALUES (2014, ‘Manju’, ‘F’);The columns that are not listed will have their default value or Null value

→ INSERT INTO employeeVALUES (1001, ‘Ravi’, ‘M’, ‘E4’, 467.00);

* Only those columns can be omitted that have either default value defined or they allow Null values INSERT INTO branch1SELECT * FROM branch2WHERE gross > 7000.00;

DELETE COMMANDThis removes entire rows, not individual field values.

DELETE FROM < table name>[WHERE < predicate > ];

→ DELETE FROM items ; // to delete all contents of item table→ DELETE FROM employee WHERE gross < 2200.00;DROP TABLE COMMANDIt drop a table from database, It must be an Empty table A table with rows cannot be dropped

DELETE FROM items; → It removes all rows// Now to drop empty table

DROP TABLE items;* UPDATE COMMAND *// To change ROL of all items to 250

UPDATE itemsSET ROL = 250 ;

To change ROL to 400 only for those that have ROL = 300UPDATE items

7

Page 8: SQL

SPECTRUM STUDY CIRCLE (The Acme of Excellence)15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)

Class: XII C++ STRUCTURED QUERY LANGUAGE

SET ROL = 400WHERE ROL = 300;

Update multiple columnsUPDATE itemsSET ROL = 400, QOH = 700WHERE icode < ‘1040’ ;

→ UPDATE employeeSET gross = gross + 900WHERE (grade= ‘E3’ or grade = ‘E4’);

// updating to Null→ UPDATE employees

SET grade = NULLWHERE grade = ‘E4’;

CREATE VIEW COMMANDIt is a virtual table with no data, but can be operated like any other table

→ CREATE VIEW taxpayeeAs SELECT *FROM employeeWHERE gross>8000;

Now, the view can be queried asSELECT * FROM taxpayee;

CREATE VIEW can be specified by Column name (new)→ CREATE VIEW taxpayee (empcode, empname, sex)

As SELECT * FROM employeeWHERE gross > 8000;

→ CREATE VIEW taxpayee (ecode, ename, tax)As SELECT ecode, ename, gross*0.1FROM employee;

DROP-VIEW COMMANDTo delete a view from a database,

DROP VIEW taxpayee ;to drop the view taxpayee

ALTER TABLE COMMANDSyntax: ALTER TABLE < table name> ADD < column> <data type> <size> ;

example →ALTER TABLE EmpADD (tel-number integer);

// It is also used to modify existing columnsALTER TABLE EmpMODIFY (JOB char (30) );

Syntax: ALTER TABLE < table name>MODIFY (column name newdata type (newsize)

8