1 SQL
STRUCTURED QUERY LANGUAGE (SQL) The first questions to ask are what is SQL and how do you use it with databases? SQL has 3 main roles: Creating a database and defining its structure Querying the database to obtain the data necessary to answer questions Controlling database security 2
INTRODUCTION TO SQL Structured Query Language(SQL) is a language that provides and interface to relational database system. SQL was developed by IBM in 1970s for use insystem R. SQL is often pronounced SEQUEL( Structured English Query Language). 3
WHAT CAN SQL DO? SQL can execute queries against a database SQL can retrieve data from a database SQL can insert records in a database SQL can update records in a database SQL can delete records from a database SQL can create new databases SQL can create new tables in a database SQL can create stored procedures in a database SQL can create views in a database SQL can set permissions on tables, procedures, and views 4
INTRODUCTION TO SQL Concept of SQL The user specifies a certain condition. The program will go through all the records in the database file and select those records that satisfy the condition.(searching). Statistical information of the data. The result of the query will then be stored in form of a table. 5
FEATURE OF SQL 1. SQL can be used by a range of users, including those with little or no programming experience. 2. It is a no procedural language. 3. It reduce the amount of time required for creating and maintain systems. 4. It is an English-like language. 6
FEATURES OF SQL *PLUS 1. SQL *PLUS accepts ad hoc entry of statements. 2. It accepts SQL input from files. 3. It provides a line editor for modifying SQL statements. 4. It controls environmental settings. 5. It formats query results into basic reports 6. It accesses local and remote databases 7
RULES FOR SQL 1. SQL starts with a verb(i.e. SQL action word). Example: SELECT statements. This verb may have additional adjectives. Example: FROM 2. Each verb is followed by number of clauses. Example: FROM, WHERE, HAVING 3. A space separates clauses. Example: DROP TABLE EMP; 4. A comma(,) separates parameters without a clause. 5. A ; is used to end SQL statements 6. Statements may be spilt across line but keywords may not 8
1. Reserved can not be used as identifiers unless enclosed with double quotes. Reserved words are: AS, ASC,INTO, ALTER, ROWID etc. 2. Identifiers can contain up to 30 characters and must start with an alphabetic character 3. Character and data literal must be enclosed within single quotes. 4. Comments may be enclosed between /* and */ symbols and may be multi line. Single line comments may be prefixed within a - symbol 9
SQL DELIMITERS + Addition Quote identifier - Subtraction : Host variable * Multiplication ** Exponential / Division <>! =^= Relational = > < Relational < = > = Relational ( ) Expression or list := Assignment ; Terminator => Association % Attribute indicator Concatenation, Item Separator << Label. Component selector >> Label @ Remote access indicator Character string delimiter -- Comments /* */ Comment(multi line) 10
COMPONENTS OF SQL DDL (Data Definition Language) : - it is a set of SQL commands used to create, modify, and delete database structures but not data. These commands are normally not used by a general user. They are normally used by the DBA. These statements are immediate i.e. they are not susceptible to ROLLBACK commands. 11
DML(Data Manipulation Language) : - It is the area of SQL that allows changing data within database DCL(Data Control Language) : - It is the component of SQL statement that control access to data and to the database. Occasionally DCL statements are grouped with DML statements. DQL(Data Query Language) : - It is the component of SQL statement that allows getting data from the database and imposing ordering upon it. In includes the SELECT statement. This command is the heart of SQL. It allows getting the data out of the database perform operations with it. When a SELECT is fired against a table/s the result is compiled into a further temporary table, which is displayed or perhaps received by the programmer. 12
EXAMPLE DDL : Data Definition Language Examples CREATE : To create objects in the database ALTER : Alters the structure of the database DROP: Delete object from the database TRUNCATE : Remove all records from a table, Including all spaces allocated for the records are removed COMMENT: Add comments to the data dictionary GRANT: Give user's access privileges to database REVOKE: Withdraw access privileges given with the GRANT command. 13
DML : Data Manipulation Language Examples: INSERT : Insert data into a table UPDATE : Updates existing data within a table DELETE : Deletes all records from a table, the space for the records remain CALL : call a PL/SQL or Java Subprogram EXPLAIN PLAN : Explain access path to data LOCK : TABLE control concurrency 14
DCL : Data Control Language Statements Example COMMIT : Save work done SAVEPOINT : Identify a point in a transaction to which you can later roll back ROLLBACK : Restore database to original since the last COMMIT SET TRANSCATION : Change transaction options like what rollback segment to use GRANT / REVOKE : Grant or take back permission to or from the oracle users. DQL : Data Query Language statement Examples : SELECT : Retrieve data from the a database 15
RELATIONAL MODEL Current popular DBMS(RDBMS) --DB2 & Informix Dynamic server from IBM --Oracle & Rd from Oracle --SQL Server from Access from Microsoft 16
ORACLE DATA TYPES CHAR(size) : - This data type is used to store character strings values of fixed length. The size of brackets determines the number of characters the cell can hold. The maximum number of characters this data type can hold is 255 characters. The data held is right padded with spaces to whatever length specified. VARCHAR / VARCHAR2 : - This data type is used to store variable length alphanumeric data. It is more flexible form of the CHAR data type. The maximum this data type can hold up to 4000 characters. VARCHAR can hold up to 255 characters. CHAR is much faster than VARCHAR, may be up to 50% 17
DATE : - This data type is used to represent data and time. The standard format is DD-MMM-YY as in 29-APR- 11. to enter dates other than the standard format, use the appropriate functions. DateTime stores date in the 24-hour format. NUMBER(P,S) : -The NUMBER data type is used to store numbers(fixed or floating point). Numbers of virtually any magnitude may be stored up to 38 digits of precision. The precision (P), determines the maximum length of the data, whereas the scale (S), determines the number of places to the right of the decimal. If scale is omitted then the default is zero. If the precision is omitted, values are stored with their original precision uptothe maximum of38 digits 18
LONG : - This data type is used to store variable length character string containing up to 2 GB. Only one LONG value can be defined per table. LONG values can not be used in sub queries, function, expressions, where clauses or indexes and the normal character functions such as SUBSTR can not applied to LONG values. RAW / LONG RAW : - The RAW / LONG RAW data types are used to store binary data, such as digitized picture or image. Data loaded into columns of these data types are stored without any further conversion. RAW data type can have a maximum length of 255 bytes. LONG RAW data type can contain up to 2 GB. 19
TABLE The foundation of every Relational Database Management System is a database object called table. Every database consists of one or more tables, which store the database s data/information. Each table has its own unique name and consists of columns and rows. The database table columns (called also table fields) have their own unique names and have a pre-defined data types. Table columns can have various attributes defining the column functionality (the column is a primary key, there is an index defined on the column, the column has certain default value, etc.) While table columns describe the data types, the table rows(tuple) contain the actual data for the columns. 20
Columns(Attributes, Fields) Data Types ID No.(NUMBER) Name (CHAR) Mobile(VARCHAR2) 1 Chintan 9498900000 2 Pankti 89676897080 Row (Data, tuple) 21
CREATE TABLE COMMAND This command is use for creating a table. Rules for creating tables A name can have maximum up to 30 characters. A-Z, a-z, 0-9 allowed A name should be begin with an alphabet The use of special character like _ allowed and also recommended SQL reversed words not allowed.(ex. create, select and so on.) 22
SYNTAX FOR CREATE TABLE CREATE TABLE TABLENAME ( ATTRIBUTES1 DATATYPE(SIZE), ATTRIBUTES 2 DATATYPE(SIZE), ATTRIBUTES 3 DATATYPE(SIZE) ); Table Created 23
P_ID LASTNAM E CREATE TABLE PERSON ( P_ID NUMBER(5), LASTNAME CHAR(50), FIRSTNAME CHAR(50), EXAMPLE ADDRESS VARCHAR2(100), CITY VARCHAR2(30) ); FIRSTNA ME ADDRESS CITY Table Created 24
INSERT DATA INTO TABLE Syntax INSERT INTO TABLENAME (ATTRIBUTES1, ATTRIBUTES2, ATTRIBUTES3) VALUES ( VALUE1, VALUE2, VALUES3 ); Note : When we are inserting values in table, if data type of table is NUMBER in that case do not provide. In all other data types, provides. Also match table attributes and values that provide. 25
EXAMPLE P_ID LASTNAME FIRSTNAM E ADDRESS CITY 1 SHAH CHINTAN MAHARAJ A INSERT INTO PERSON ( P_ID, LASTNAME,FIRSTNAME,ADDRESS,CITY) VALUES AHMEDABA D (1, SHAH, CHINTAN, MAHARAJA, AHMEDABAD ); OUTPUT : - 1 ROW CREATED 26
EXERCISE TIME Insert more data in same table P_ID LASTNAME FIRSTNAME ADDRESS CITY 1 SHAH CHINTAN MAHARAJA AHMEDABAD 2 IVAN BAYROSS CARLISLE NJ 3 SHAH KHUSHBU PARUL AHMEDABAD 27
VIEWING DATA IN THE TABLES Syntax : - SELECT * FROM TABLENAME; Example SELECT * FROM PERSON; 28
NOW DISPLAY ALL THE TABLE Query : Select * from tab; Display list of all tables. 29
Displaying Table Structure Syntax DESC table_name; Example Desc abc; 30
INSERT MULTIPLE ROWS IN TABLE QUERY INSERT INTO persons values (&ID, &LASTNAME, &FIRSTNAME, &ADDRESS, &CITY ); 31
32
FILTERING TABLE DATA Selected Columns And All Rows Syntax : SELECT columnname1,columnname2 FROM Table Name ; Example : 33
PROBLEM? Here when I am retrieving details of table, we will get all data of table, but if we want to restrict the data or we want specific person s data 34
FILTERING TABLE DATA Selected Rows and All Columns Syntax : SELECT * FROM table_name WHERE = CONDITION ; Example : 35
FILTERING TABLE DATA Selected Rows and selected Columns Syntax : SELECT column1,column2 FROM table_name WHERE = Condition ; Example : SELECT P_ID, LASTNAME,CITY FROM PERSONS WHERE NAME= KHUSHBU ; 36
DISTINCT Eliminating duplicate rows The DISTINCT clause removing duplicates from the result set. The DISTINCT clause can only used with select statements. Syntax SELECT DISTINCT COLUMNNAME1 FROM TABLENAME; 37
Example WE USE THE FOLLOWINGSELECT STATEMENT FOR RETRIEVING CITY 38
SEE DIFFERENCE 39
SORTING DATA IN A TABLE Oracle allows data from a table to be viewed in a sorted orders. The rows retrieved from the table will be sorted in either ascending or descending order. The ORDER BY keyword is used to sort the resultset by specified column. The ORDER BY keyword sort the records in ascending order by default. If you want to sort the records in a descending order, you can use the DESC keyword. 40
SQL ORDER BY SYNTAX SELECT * FROM TABLE_NAME ORDER BY COLUMN_NAME(S) ASC DESC 41
EXAMPLE 42
We use the following SELECT statement: SELECT * FROM PERSON ORDER BY LASTNAME; P_ID LASTNAME FIRSTNAM E ADDRESS CITY 3 PANDYA NITIN TALOD GANDHINA GAR 2 PATEL SANJAY GANDHINA GAR GANDHINA GAR 4 PATEL VISHAL GHATLODIA AHMEDABA D 1 SHAH CHINTAN SATELLITE AHMEDABA 43 D
ORDER BY DESC example SELECT * FROM persons ORDER BY LASTNAME DESC; P-ID LASTNAME FIRSTNAM E ADDRESS CITY 1 SHAH CHINTAN SATELLITE AHMEDABA D 4 PATEL VISHAL GHATLODIA AHMEDABA D 2 PATEL SANJAY GANDHINA GAR GANDHINA GAR 3 PANDYA NITIN TALOD GANDHINA GAR 44
DELETE STATEMENT Removal of all ROWS -Syntax DELETE FROM PERSONS; -All rows deleted 45
QUESTION: - If I want to retrieve data of persons table. What will happen? What will be an answer? 46
UPDATING CONTENS OF A TABLE The UPDATE command is used to change or modify data values in a table. SQL UPDATE Syntax UPDATING ALL ROWS UPDATE TABLENAME SET COLUMNNAME1= NEW VALUE, COLUMNNAME2 = NEW VALUE; 47
EXAMPLE Now we want to UPDATE LASTNAME in persons table 48
OUTPUT 49
UPDATE RECORDS CONDITIONALLY UPDATE table_name SET columnname= value, columnname= value2 WHERE columnname= value 50
EXAMPLE Now we want to UPDATE Lastname from ABC to SHAH, whose FIRSTNAME IS CHINTAN 51
MODIFY STRUCTURE OF TABLE ADDING new columns in existing table. Syntax ALTER TABLE TABLENAME ADD (NEW COLUMNNAME DATATYPE(SIZE)); 52
NOW WE WANT TO ADD PINCODE FIELDS IN PERSONS TABLE 53
54
EXERCISE TIME NOW INSERT PINCODE IN EXISTING ROWS OF PERSONS TABLE. 55
MODIFY STRUCTURE OF TABLE MODIFY columns in existing table. Syntax ALTER TABLE TABLENAME MODIFY (COLUMNNAME NEWDATATYPE (NEWSIZE)); 56
NOW WE WANT TO MODIFY PINCODE DATA TYPE FROM VARCHAR2 TO NUMBER IN PERSON TABLE. 57
58
RESTRICTIONS ON ALTER TABLE Following task cannot be performed Change name of table Change name of column Decrease size of column if data exists 59
Syntax : RENAMING TABLES RENAME TableName TO NewTableName ; Problem RENAME PERSON table TO CLIENT table 60
TRUNCATING TABLES EXAMPLE : TRUNCATE TABLE PERSONS; Table Truncated. Similar to DELETE Find out difference Delete table tablename; & truncate table tablename; 61
DESTROYING TABLES EXAMPLE: DROP TABLE PERSON; Table Dropped. 62
PREPARED BY: - Chintan Shah & Pankti Dharwa Assistant Professor, Shankersinh Vaghela Bapu Institute of Technology 63