* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Document
Survey
Document related concepts
Microsoft Jet Database Engine wikipedia , lookup
Relational algebra wikipedia , lookup
Ingres (database) wikipedia , lookup
Functional Database Model wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Clusterpoint wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Transcript
Chapter:12 Structured Query Language(SQL) History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SQL (ANSI 1986), SQL1 or SQL86 SQL2 or SQL92 SQL3 or SQL99 Core specification and optional specialized packages SQL consists of ~20 basic commands A lot of research money for each SQL command… Standard language for all commercial DBMS 2 Why a query language? Given some data, how should users and computer programs communicate with it? ? •we need an interface to the data An Overview of SQL SQL stands for Structured Query Language. It is the most commonly used relational database language today. SQL works with a variety of different fourthgeneration (4GL) programming languages, such as Visual Basic. SQL Requirements SQL Must be embedded in a programming language, or used with a 4GL like VB SQL is a free form language so there is no limit to the the number of words per line or fixed line break. Syntax statements, words or phrases are always in lower case; keywords are in uppercase. 5 STRUCTURE QUERY LANGUAGE(SQL): The SQL is a language that enables you to create and operate on relational databases, which are sets of related information stored in tables. => SQL is a simple query language used for accessing , handling and managing data in relational database. SQL, enables the following: (i) Creating/modifying a database’s structure (ii) Changing security settings for system (iii) Permitting users for working on databases or tables (iv) Querying database (v) Inserting/Modifying/Deleting the database contents. Processing Capabilities of SQL Data definition language-The SQL DDL provides commands for defining relation schemas, deleting relations, creating indexes, and modifying relation schemas. Interactive Data Manipulation Language-The SQL DML includes a query language based on both the relational algebra and the tuple relational calculus. 8 Embedded Data Manipulation LanguageThe Embedded form of SQL is designed for use within general purpose programming languages such as PL/1,Cobol,Fortan,Pascal and C. View Definition-The SQL DDL also includes commands for defining views. Authorization-The SQL DDL includes commands for specifying access rights to relations and views. 9 Integrity-The SQL provides limited forms of integrity checking. Future products and standards of SQL are likely to include enhanced features for integrity checking. Transaction Control-SQL includes commands for specifying the beginning and ending of transactions along with commands to have a control over a transaction processing. 10 =>Data definition language(DDL): A database scheme is specified by a set of definition which are expressed by a special language called a data definition language (DDL). The result of compilation of DDL statements is a set of tables which are stored in a special file called Data dictionary (or dictionary). i.e. A data dictionary is a file that contains “Metadata” i.e. , “data about data” Classification of sql statement All sql statement are instruction to the database only. And that is where it differs from generalpurpose programming languages like ‘C’ or ‘c++’ or ’BASIC’ etc DDL perform the following functions: It should identify the types of data division such as data item, record type, segment, record and database file it should give a unique name to each data –item type, record type, file type, database etc. it should specify the proper data type it should specify how the record types are related to make structures. It may define the length of the data items. It may define the range of values that a data-item can assume. checking the error in the data Create, alter, and drop schema object =>A DATA MANIPULICATION LANGUAGE(DML) is a language that enables user to access or manipulate data as organized by the appropriate data model. =>By data manipulation, we mean 1.the retrieval of information stored in the database 2.the insertion of new information into the database 3.The deletion of information from the database 4.the modification of data stored in the database =>The DML are basically of two types: 1.Procedure DML required a user to specify what data is needed and how to get it. 2. Non-procedure DMLs required a user to specify what data is needed without specifying how to get it. Examples: INSERT INTO, UPDATE, DELETE, SELECT, LOCK => DCL(Data control Language): It is used to access to the data base(by GRANTing / REVOKing etc) and essential to the system Some MySQL SQL Elements The MySQL implementation of SQL has certain elements that play an important role in defining /querying a database. These basic elements are: (i) Literals (ii) Data types (iii) Nulls (iv) Comments (i) Literals Literals in general, refer to a fixed data value. The fixed data value may be of character type or numeric literal. (ii)Data types Data types are means to identify the type of data and associated operations for handling it. Numeric Data Types MySQL uses all the standard ANSI SQL numeric data types. The following list shows the common numeric data types INT TINYINT SMALLINT MEDIUMINT BIGINT FLOAT(M.D) DOUBLE(M.D) DECIMAL(M.D) Date and Time Types The MYSQL date and time data types are: DATE DATETIME TIMESTAMP TIME YEAR(M) String/Text Types Most data that you in a database is in string format. This list describes the common string data types in MySQL CHAR(M) VARCHAR(M) BLOB or TEXT TINYBLOB or TINYTEXT MEDIUMBLOB or MEDIUMTEXT LONGBLOB or LONGTEXT ENUM SQL Data types (from Oracle 9i) String types CHAR(n) – fixed-length character data, n characters long Maximum length = 2000 bytes.It is inclosed in single qoutes( ‘ram’) VARCHAR2(n) – variable length character data, maximum 4000 bytes LONG – variable-length character data, up to 4GB. Maximum 1 per table Numeric types NUMBER(p,q) – general purpose numeric data type INTEGER(p) – signed integer, p digits wide FLOAT(p) – floating point in scientific notation with p binary digits precision 21 Date/time type DATE – fixed-length date/time in dd-mm-yy form SQL Server Data Types int, integer: 4 byte integer smallint: 2 byte integer tinyint: 1 byte integer float: 4 or 8 byte floating point number real: 4 byte floating point number double precision: 8 bype floating point number numeric, decimal(precision, scale): exact numeric, 2 to 17 bytes. Only difference is that only numeric types with a scale of 0 can be used of the IDENTITY column. Destroy a table: drop table table_name Difference between Char and Vachar datatypes The difference between CHAR and VARCHAR is that of fixed length and variable length. The CHAR data types specifies a fixed length character string and VARCHAR data types specifies a variable length string. (iii)Null Values If a column in a row has no value, then column is said to be null , or to contain a null. Nulls can appear in columns of any data type provided they are not restricted by NOT NULL or PRIMARY KEY integrity constraints. Comments: A comment is a text that is not executed ; it is only for documentation purpose. Comments within SQL statements do not affect the statement execution, but they may make your application easier for you to read and maintain. A comment can be given using double minus sing i.e. - - SQL COMMAND SYNTAX The SQL provides a predefined set of commands that help us work on relational databases. Keywords are words that have a special meaning in SQL. They are understood to be instructions. Commands, or statements, are instructions given by you to a SQL database. Arguments complete or modify the meaning of a clause. SQL Environment Catalog Schema 26 Commands that define a database, including creating, altering, and dropping tables and establishing constraints Data Manipulation Language (DML) The structure that contains descriptions of objects created by a user (base tables, views, constraints) Data Definition Language (DDL) A set of schemas that constitute the description of a database Commands that maintain and query a database Data Control Language (DCL) Commands that control a database, including administering privileges and committing data 27 Queries SPECIAL OPERATORS BETWEEN - define range limits IS NULL - check if attribute value is null LIKE - check for similar character strings IN - check if attribute value matches a value within a (sub)set of listed values EXISTS - check whether attribute has a value Basic MySQL Operations Create database use database see data base Create table Insert records Load data Retrieve records Update records Delete records Modify table Join table Drop table Optimize table Count, Like, Order by, Group by More advanced ones (sub-queries, stored procedures, triggers, views …) Syntax to Create database Create database databasename ; Create a database (make a directory) whose name is MyDB mysql> create database MyDB; Select database to use mysql> use MyDB; Database changed What tables are currently stored in the MyDB database? mysql> show tables; Empty set (0.00 sec) What are the current databases at the server? mysql> show databases; +--------------+ | Database | +--------------+ | mysql | | test | +--------------+ mysql is a database (stores users’ password) used by system. =>CREATE TABLE COMMAND CREATE TABLE – defines a table and its columns, data types and sizes are supplied for each column. CREATE TABLE Table_Name (column_specifications) Syntax; <table-name> (column name data tpes[size], column name data tpes[size],….); Example: CREATE TABLE employee ( ecode int, ename char(20),sex char(1), grade char(2), gross decimal); CREATE TABLE Constraint; A CONSTRAINT IS A CONDITIONAL OR CHECK APPLICABLE ON A FIELD OR SET OF FIELD. There are two type of constraints Column constraint: It apply only to individual columns Table Constraint: It apply to groups of one or more columns. Syntax: CREATE TABLE table-name ( column-name data type[size] column constraint, columnname data type[size] column constraint, ….); employee ( ecode int NOT NULL, ename char(20) NOT NULL, sex char(1) NOT NULL, grade char(2), gross decimal); Different Constraints: Unique Constraints Primary key Constraints Default Constraints Check Constraints CREATE TABLE Unique Constraints: This Constraints ensures that no two rows have the same value in the specified columns. CREATE TABLE employee ( ecode int NOT NULL UNIQUE, ename char(20), NOT NULL sex char(1), NOT NULL grade char(2), gross decimal); Primary key Constraint: It is a set of column or columns that uniquely identify a row in a relation. CREATE TABLE employee ( ecode int NOT NULL PRIMARY KEY, ename char(20), NOT NULL sex char(1), NOT NULL grade char(2), gross decimal); Default Constraint: A default value can be specified for a column using the default clause. When a user does not enter a value for the column(having default), automatically the defines default value is inserted in the field. CREATE TABLE employee ( ecode int NOT NULL PRIMARY KEY, ename char(20), NOT NULL sex char(1), NOT NULL grade char(2) DEFAULT=‘E’, gross decimal); Check Constraints: This constraint limit values that can be inserted into a column of a table. CREATE TABLE employee ( ecode int NOT NULL PRIMARY KEY, ename char(20), NOT NULL sex char(1), NOT NULL grade char(2) DEFAULT=‘E’, gross decimal CHECK(GROSS>2000)); =>When a check constraint involves more than one column from the same table, it is specified after all the columns have been defined. employee ( icode char(5) NOT NULL PRIMARY KEY, descp char(20), NOT NULL ROL integer, QOH integer, CHECK (ROL<QOH) ); CREATE TABLE Applying Table Constraints: The Table constraints appear in the end of the table definition. CREATE TABLE items ( icode char(5) NOT NULL, Descp char(20) NOT NULL, ROL integer, QOH integer, CHECK (ROL<QOH), UNIQUE (icode,descp)); mysql> show tables; +--------------------+ | Tables_in_MyDB | +--------------------+ | student | +--------------------+ 1 row in set (0.00 sec) mysql> describe student; +---------------+----------------------+------+------+----------+--------+ | Field | Type | Null | Key | Default | Extra | +---------------+----------------------+-------+-----+-----------+-------+ | student_ID | int(10) unsigned | | |0 | | | name | varchar(20) | | | | | | major | varchar(50) | YES | | NULL | | | grade | varchar(5) | YES | | NULL | | +---------------+----------------------+-------+------+----------+-------+ 4 rows in set (0.00 sec) The SELECT Command The SELECT command of SQL lets you make queries on the database. A query is a command that is given to produce certain specified information from the database table(s). SELECT statement is used as given below; SELECT <column name>, <column name> , …FROM <table name> ; Example: SELECT Empno,Empname FROM emp; SELECT Statement Used for queries on single or multiple tables Clauses of the SELECT statement: SELECT List the columns (and expressions) that should be returned from the query FROM Indicate the table(s) or view(s) from which data will be obtained WHERE Indicate the conditions under which a row will be included in the result GROUP BY Indicate columns to group the results HAVING Indicate the conditions under which a group will be included ORDER BY Sorts the result according to specified columns 44 List the selected column of a table SELECT empno,job,sal FROM emp; List the all column of a table * is wildcard character - gives “all rows” SELECT * FROM emp; Reordering columns in query Results SELECT job,empno,sal FROM emp; Eliminating Redundant data (with keyword DISTINCT): The DISTINCT keyword eliminates duplicates rows from the results of a SELECT statement. Example: SELECT DISTINCT city FROM suppliers; Selecting From All the Rows-ALL Keyword: The result retains the duplicates output rows. It is just the same as when you specify neither DISTINCT nor ALL. EXAMPLE: SELECT ALL city FROM suppliers; Selecting Specific Rows-Where clause: The tables can contain unlimited rows. If you want to view selected rows from the table.the WHERE clause in SELECT statement specifies the criteria for selection of rows to be returned. Syntax: SELECT column name, column name,.... FROM table name WHERE condition; EXAMPLE: SELECT empname,sal FROM emp WHERE sal>2900; 48 List all the members not from ‘DELHI’ SELECT * FROM suppliers WHERE city < > ‘ DELHI’ ; Logical Operator: The logical operators OR ,AND and NOT are used to connect search conditions is the WHERE clause. 1. To list the employees details having grade ‘E2’ or ‘E3’ from the table employee SELECT ecode,ename,grade,gross FROM employee WHERE(grade=‘E2’ OR grade=‘E’); 2. To list the employees details having grades ‘E4’ but with the gross<9000 from the table employee SELECT ecode,ename,grade,gross FROM employee WHERE(grade=‘E4’ AND gross<9000); 3. To list all the employees details whose grade are other than ‘G1’. SELECT ecode,ename,grade,gross FROM employee WHERE(NOT grade=‘G1’); CONDITION BASED ON A RANGE: The BETWEEN operator defines a range of values that the column values must fall into make the condition true.yhe range includes both lower values and the upper value. To list the item whose QOH falls between 30 to 50(both inclusive). SELECT icode ,descp,QOH FROM items WHERE QOH BETWEEN 30 and 50. SELECT icode ,descp,QOH FROM items WHERE QOH NOT BETWEEN 30 and 50. CONDITION BASED ON A LIST: The IN operator selects values that match any value in a given list of values. To display a list of members from ‘DELHI’, ‘MUMBAI’, ‘CHENNAI’, OR ‘ BANGALORE’ CITIES. SELECT * FROM members WHERE city IN (‘DELHI’, ‘MUMBAI’, ‘CHENNAI’, ‘ BANGALORE’ ); => SELECT * FROM members WHERE city NOT IN (‘DELHI’, ‘MUMBAI’, ‘CHENNAI’, ‘ BANGALORE’ ); CONDITIN BASED ON PATTERN MATCHES: The string matching operatr, LIKE, for comparisons on character strings using patterns. Patters are described using two special wildcard characters. percent(%): The % character matches any substring. underscore( _ ): The _ character matches any one character. Patterns are case sensitive i.e. , upper case characters dot not match lower case characters or vice –versa. The keyword NOT LIKE is used to select rows that do not match the specified pattern of characters. In order for patterns to include the special pattern characters(that is, %,_), SQL allows the specific of an escape character. The escape character is used immediately before a special pattern character to indicate that the special pattern character is to be treated as a normal character. “San%” matches any string beinning with “San”. “%idge%” matches any string containing “idge” as a substring, for example “ridge” , Bridge”, etc. “ _ _ _ _” matches any string of exactly 4 characters. “ _ _ _ _ %” matches any string of at least 4 characters. 1. To list members which are in areas with pin codes starting with 13. SELECT firstname, lastname,city FROM members WHERE pin LIKE “13%”; 2.To list employees who have four letter first names ending with “ D”. SELECT empno, empname FROM emp WHERE empname LIKE “ _ _ _ D”; 3.To list members which are not in areas with pin codes starting with 13. SELECT firstname, lastname,city FROM members WHERE pin NOT LIKE “13%”; SEARCHING FOR NULL: The NULL value in a column can be searched for in a table using IS NULL in the WHERE clause. SELECT empno, empname, job FROM emp WHERE DeptNo IS NULL; SEARCHING RESULTS- ORDER BY CLAUSE: The ORDER BY clause allows sorting of query results by one or more columns. The sorting can be done either on ascending or descending order. the data in the table is not sorted; only the results that appear on the screen are sorted, Syntax: SELECT column name,… FROM table name WHEE condition ORDER BY column name. SELECT * FROM employee ORDER BY ename; SELECT empno , empname , job FROM emp WHERE sal> 2500 ORDER BY ename ; SELECT * FROM employee ORDER BY ecode DESC; DESC: descending order ASC: Ascending order SELECT * FROM employee ORDER By grade DESC , ename ASC; SIMPLE CALCULATION: DUAL table is a small worktable , which has just one row and one column. SELECT 4*3 FROM dual; SELECT sysdate FROM dual; What is an aggregate function? An aggregate function summarizes the results of an expression over a number of rows, returning a single value. The general syntax for most of the aggregate functions is as follows: aggregate_function ([DISTINCT|ALL] expression) Commonly used Aggregate functions Some of the commonly used aggregate functions are : • SUM • COUNT • AVG • MIN • MAX 1.Avg Function The AVG() function returns the average value of a numeric column. Query 1: If we want to calculate the AVG of all the salaries in the organization the SQL would be SELECT AVG(SALARY) FROM EMPLOYEE 62,500 Is this what we expect???? Employee table has 7 records and the salaries are 50,000+60,000+50,000+70,000+75,000+70,000+null/7 = 53571 But we obtained 62500 from the query? Why is this so???? AVG (Continued….) Remember : COUNT(*) is the only function which won’t ignore Nulls. Other functions like SUM,AVG,MIN,MAX they ignore Nulls. What it means is in the previous query the salary value for a particular employee was NULL. So the query SELECT AVG(SALARY) FROM EMPLOYEE would ignore nulls and the way the average is calculated then would be 50,000+60,000+50,000+70,000+75,000+70,000/6 = 62500 AVG (Continued….) From the information given in the previous slide what do you think would be the output of the following query Select COUNT(*),COUNT(SALARY) FROM EMPLOYEE; It would be COUNT(*) COUNT(SALARY) 7 6 Because COUNT(*) is not going to ignore the Nulls in the result whereas COUNT(SALARY) is going to ignore the Nulls. 2.COUNT The SQL COUNT aggregate function is used to count the number of rows in a database table. The SQL COUNT syntax is simple and looks like this: COUNT({*[DISTINCT | ALL] expr}) FROM Table1 If we want to count the number of records in table empl, we will use the following SQL COUNT statement: SELECT COUNT(*) “Total” FROM empl; The result of this SQL COUNT query will be: Total 14 3.MAX The SQL MAX aggregate function allows us to select the highest (maximum) value for a certain column. The SQL MAX function syntax is very simple and it looks like this: MAX([DISTINCT | ALL] expr) If we want to display maximum salary from table empl SQL MAX expression: SELECT MAX(sal) “Maximum Salary” FROM empl; Maximum Salary 5000.00 4.MIN The SQL MIN aggregate function allows us to select the lowest (minimum) value for a certain column. The SQL MIN function syntax is very simple and it looks like this: MIN([DISTINCT | ALL] expr) If we want to display the joining date of senior most employee the following SQL MIN expression is used : SELECT MIN(hiredate) “Minimum Hire Date” FROM empl; Minimum Hire Date 1990-12-18 5.sum sum is an aggregate function. It returns the sum of its numeric-expressions for each group indicated in the group by clause. Query 1: To find the sum of all salaries in the organization: SELECT SUM(SALARY) FROM EMPLOYEE; 375000 Query 2: To find the sum of the salaries grouped by dept SELECT SUM(SALARY) FROM EMPLOYEE GROUP BY DEPT_NAME Types of sql functions (i)Single-Row Functions Single-row functions return a single result row for every row of a queried table or view. Examples of single row functions are the functions are text/Character functions such as year(),day(),etc. (ii) Multiple Row or Group Functions work with data of multiple rows at a time and return aggregate value. Examples of multiple row functions are the group functions i.e. , sum(),count(),max(),min(), Avg()etc. A single row function works with the data of single row at a time and returns a single result for each row queried upon ; a multiple row function works with the data of group of rows at a time and returns a single result for that Grouping result – group by The GROUP BY clause combines all those records that have high identical values in a particular field or a group of fields. This grouping results into one summary record per group if group-functions are used with it.In other words ,the GROUP BY clause is used in SELECT statements to divide the table into groups. Grouping can be done by a column name,or with aggregate functions in which case the aggregate produces a value for each group. Ex: SELECT job ,COUNT(*),sum(comm) FROM emp GROUP BY job ; GROUP BY applies the aggregate functions independently to a series of groups that are defined by having a field value in common. NESTED Groups - Grouping on multiple Columns With GROUP BY clause ,you can create groups within groups. Such type of grouping is called Nested grouping. This can be done by specifying in GROUP BY expression, where the first field determines the highest group level, the second field determines the second group level, and so on. The last field determines the lowest level of grouping. See there are multiple records having same value for depno,we can group records on the basis of field Deptno. For instance ,if you want to count the number of employees in each group ,you need to issue a query statement as given below: SELECT COUNT(empno) FROM empl GROUP BY Deptno; Result produced by the query is Count(empno) 3 5 6 But can you make out ,these are employee-counts for which departments? To get this information , you may modify the SELECT list as: SELECT Deptno, COUNT(empno) FROM empl GROUP BY Deptno ; Deptno count(empno) 10 3 20 5 30 6 One thing should be kept in mind is that while grouping , you should include only those values in the selected list that either have the same value for group or contain a group(aggregate) function i.e. , a group expression. Like in the above query, the first expression Deptno field has one (same) value for a group and the other expression COUNT(empno) contains a group function. A non group field (or expression) is the field that has different values in the rows belonging to group. In the select list of a group ,only those fields or expressions state be included that either return single value for a group are constants.Otherwise you may not get authentic results. Placing condition on groups-HAVING Clause: The HAVING clause places conditions on groups in contrast to WHERE clause that places conditions on individual while WHERE conditions cannot include aggregate functions, Having conditions can do so. SELECT avg (gross), sum(gross) FROM employee GORUP BY grade HAVING grade=‘E4’; To display the jobs where the number of employee are less than 3. SELECT job count(*) FROM emp GROUP By job Having count(*)<3; SCALAR EXPRESSIONS WITH SELECTED FIELD: SQL allow to place scalar expressions and constants among the selected fields. SELECT salesman_name , comm * 100 FROM salesman; PUTTING TEXT IN THE QUERY OUTPUT: To insert comment or symbol with every row of the output. SELECT salesman_name , comm * 100 , ‘%’ FROM salesman; SELECT salesman_name , ‘gets the commission’, comm * 100, ‘%’ FROM salesman; CREATING TABLE FROM EXISTING TABLE: To create the table without going through the usual data definition process. this can be done by SELECT statement with CREATE TABLE. CREATE TABLE orditem AS ( SELECT icode, descp FROM items WHERE QOH<ROL ); A new table create from an existing table with help of SELECT INTO. SELECT icode, descp INTO orditems FROM items WHERE QOH<ROL ; Basic Insert: Inserting a Tuple into a Table Insert one tuple into table: insert into table_name[(column_list)] values(value_list) Ex: specify values for all attributes: insert into STUDENT values(‘Mike’, 1, 3.8, 3, ‘CS’) Ex: specify values for only some attributes: insert into STUDENT(name, regno, level) values (‘Jenny’, 2, 1) NOTE: in SQL, strings are surrounded by single quote, not double quote. Double quotes surround identifiers that contain special characters. To include a single quote in the string use two single quotes (eg.,’it’’s good’) INSERTING THE RESULTS OF A QUERY: inserting COMMAND CAN ALSO be used to take or drive values from one table and place them in another by using it with a query. INSERT INTO branch1 SELECT * FROM branch2 WHERE gross>7000.00; => THE DELETE COMMAND: To removes rows from a table. SYNTAX: DELETE FROM <tablename> [ WHERE<SONDITION> ]; SQL> DELETE FROM employee WHERE gross<2200.00; Mysql> DELETE FROM student; Will delete ALL student records => The UPDATE COMMAND: The UPDATE command specifies the rows to be changed using the WHERE clause, and the new data using the SET keyword. => SYNTAX: UPDATE table name SET which columns to change WHERE condition Example mysql> UPDATE student SET grade='B' WHERE name='Shannon'; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 Mysql> UPDATE items SET ROL=250; Mysql> UPDATE items SET ROL=400 WHERE ROL=300; =>UPDATING MULTIPLE COLUMNS: Mysql> UPDATE items SET ROL=400,QOH=700 WHERE icode<‘I040’; Using Expressions in UPDATE: Scalar expressions can also be used in the SET clause of the UPDATE command. Mysql> UPDATE employee SET gross=gross+900; UPDATING TO NULL VALUES: The NULL values can also be inserted just as other values. Mysql> UPDATE employee SET grade=NULL WHERE grade=‘E4’; The CREATE VIEW COMMAND: A view is a virtual table with no data , but can be operated like any other table; CTREATE VIEW taxpayee AS SELECT * FROM employee WHERE gross> 8000; Note : The SELECT statement used in a view definition cannot include: ORDER BY clause INTO clause CREATE VIEW taxpaee ( empcode, empname,sex,empgrade,empgross) AS SELECT * FROM employee WHERE gross>8000; SOME BUILD – IN FUNCTIONS: 1.LOWER(character expression ): This function converts a giving character expression into lowercase. Syntax : LOWER(char); Description: returns the argument char , with all latter lowercase; SQL> SELECT LOWER(‘MR.ANIL’) lowername1, LOWER(‘MR. Maithili’) “Lowername2” from dual; 2.UPPER(character expression ): This function converts a giving character expression into uppercase. Syntax : UPPER (char); Description: returns the argument char , with all latter lowercase; SQL> SELECT UPPER (‘MR.ANIL’) lowername1, UPPER(‘MR. Maithili’) “Lowername2” from dual; Output: 3. Replicate(char-expn,no-of-time): To repeats yhe given char-expn the no-of –times .the no-of-times has to an integer. mysql>SELECT replicate(“*#”,4) FROM Dual; Output: *#*#*#*# 4.SUBSTR: This function extract a substring from a given string. Syntax: SUBSTR(char, m[, n]) Description: Returns a portion of char, beginning at character m, n character long. if m is 0.it is treated as 1.if m is positive , negative. If n is less than 1,a null is returned. SQL> select SUBSTR(‘Pointer’, 3,2) “subs” from dual; Output: in 5.getdate( ): it return the current system date. Mysql>SELECT getdate( ) FROM Dual; 6.CONCAT: Syntax: CONCAT(char1,char2). SQL>select CONCAT(ename, ecode) “name and code” from emp where empno =7900 or empno=7788. 7. INITCAP: Syntax: INITCAP(char) Description: Returns the given arguments char, with the first letter of each word in uppercase, all other letters in lowercase. SQL>select INITCAP( ‘the soap’) “Capitals” from dual; 8.LPAD: This function left-pads (i.e., inserts the left side) the giving character to given string to reach at given width. Syntax:LPAD(char1, n [, char2]) Description: Returns argument char1,left-padded to length n with the sequence of characters in argument char2. The arguments n is the total length of the return values as it is displayed on the screen. SQL> select LPAD(‘hello’,15,’*.’) “left padded ename” from EMP where empno=7788; 9.RPAD: function RPAD is similar to that of LPAD. only difference is that the specified character are right padded. =>Join is a query that combines rows from two or more tables. that is Join is used to give the data from multiple table with single query. The function of combining data from multiple table is called Joining. SQL> SELECT patient_no, description, normal_charge,charge FROM billed,item WHERE billed.item_code= item.item_code; CARTESIAN PRODUCT: In unrestricted join or Cartesian product of two table ,all possible concatenations are formed of all rows of both the tables. SELECT * FROM EMP,DEPT ; =>A Table Alias is a temporary label given along with table name in FROM clause. SQL>SELECT DISTINCT patient_no, phy_id FROM treats WHERE phy_id IN(8887,8886,8883,8882); Types of Join 1. Inner or Equi-Join 2.Self Join 3.Outer Join (a). Left outer Join (b). Right outer Join (c). Full outer Join 4.Natural Join 1. Inner or Equi-Join: The join in which columns are compared for equality, is called Equi-Join. OR INNER Join. Inner Join is used to give the matching records from Joined tables. For example: Table A.equi join table B SQL>SELCT billed.patient_no, date_discharged, charge FROM billed,patient WHERE patient.patient_no =billed.patient_no; =>Non-Equi Joins: A non- equi-join is a query that specifies some relationship other than equality between the columns. 2.Natural Join: The Join in which only one of the identical columns(coming from joined tables) exits, is called Natural Join. 3. Self Join: A table Joined with itself is called self join SQL> select.*,sup2.supp# from suppliers where sup1.supp#<>sup2.supp# and sup1.city= sup2.city; Outer Join: Outer Join selects all the rows that satisfy the join condition and those rows from one table for which no rows from the other table satisfy the join condition. Left-Outer Join: Left outer jon give the results as combination of matching record from both the table plus remaining record from left side tables. It is denoted by + For left join + is used to the right side table variable SQL>select sname, email, feebal from student s, fees f where s.sid =f.sid (+); Right-outer Join: It Gives the results as combination of matching records plus remaining record from right sides tables. SQL>select sname,email,feebal from student s,fees f where s.sid(+)=f.sid; Full outer-join: It Gives the results as combination of matching records and remaining record from left sides table plus remaining record from right sides tables. SQL>select sname, email, feebal from student s, fees f where s.sid(+)=f.sid(+); =>UNION: The SQL UNION operator allows manipulation of results returns by two or more queries by combining the results of wach query into a single result set. Mysql> SELECT * FROM A UNION SELECT * FROM B; It remove the duplicate rows from results. if the all option is used,all rows, including duplicate are included in the results. SELECT statement UNION [ALL] SELECT statement; RULE OF using UNION OPERATOR: 1. Both the SELECT statements must be UNION compatible, that is, the select-list of SELECT statement must have same number of column having similar data type and order. Mysql> SELECT ecode,ename FROM branch1 UNION SELECT ecode,ename FROM branch2; 2. The ORDER BY clause occurs only at the end of the UNION statement. It can’t be used within the individual queries that make the UNION statement. 3. The GROUP BY and HAVING clause are allowed only within individual queries . These clause cannot be used to affect the final result set. ALTERING TABLE: It is used to change definitions of existing tables. 1.To add a column 2. To add an integrity constraint 3. To redefine a column (data type, size , default value). ADDING COLUMNS: SYNTAX: ALTER TABLE <table name> ADD <column name> <data type> <size> [<constraint name>]; SQL>ALTER TABLE Emp ADD (tel_number integer); =>The new column will be added with NULL values for all rows currently in the table. Mysql> ALTER TABLE Emp ADD (tel_number integers); Modifying Column Definitions: SYNTAX: ALTER TABLE <table name> MODIFY (column name new data types (new size)); SQL> ALTER TABLE Emp MODIFY (Job char(30)); Removing Integrity Constraints To drops the primary key of table DEPT SQL> ALTER TABLE dept DROP PRIMARY KEY CASCADE ; ENABLING OR DISABLING CONSTRAINTS: The ALTER TABLE command can be used for enabling or disabling a constraint. SQL> ALTER TABLE products ENABLE pk_produce_01 ; SQL> ALTER TABLE products DISABLE UNIQUE (serial#) ; TRUNCTING TABLE: It allows users to delete information from a table quickly, using TRUNCTING COMMAND. SQL> TRUNCTING TABL products; =>TRUNCATE is a part of DDL unlike DELETE which is a part of DML THE DROP TABLE COMMAND: To drop a table from databse.It must be an empty table SQL> DELETE FROM items ; SQL> DROP TABLE items; SQL> TRUCATING TABLE items; A table with rows in it cannot be dropped. THE DROP VIEW COMMAND: To delete a view from the database ,the DROP VIEW command is used. Mysql>DROP VIEW taxpayee; To drops the view taxpayee from database. When a view is dropped, it does not cause any change in its base table after the removal of view taxpayee.