0% found this document useful (0 votes)
19 views

Basic SQL Commands

sql notes

Uploaded by

suryaniraj80
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
19 views

Basic SQL Commands

sql notes

Uploaded by

suryaniraj80
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 8
ge “ACES pee a < types of interface provided by a DBMS : six ' thet? O70 & ased Interfaces for Browsing oe 1, Ment pased Interfaces jcal-User Interfaces Language Interfaces for Parametric Users for the DBA erfaces for Browsing : These interfaces present the user with lists of that lead the user through the formulation of a request. Pull-down options cued ng a very popular technique in window-based user interfaces. They are menus ae DECC Sing interfaces, which allow a user to look through the contents of a en used a exploratory and unstructured manner. database inal : 7 ipased Interfaces : A form-based interfaces displays a form to each user. Users Form BL of the form entries to insert new data, or they fill out only certain entries, in a case ‘he DBMS will retrieve matching data for the remaining entries. Many DBMSs w wie forms specification languages special languages that help programmers specify such B forms. ‘ ' Graphical-User Interfaces : A Graphical User Interfaces (GUI) typically displays a ‘user in diagrammatic form. The user can then specify a query by manipulating the diagram, In many cases, GUI utilize both menus and forms. Most GUI use a pointing Mitjees such as a mouse, to pick certain parts of the displayed schema diagram. Natural Language Interface : These interfaces accept requests written in English or and” them. A natural language interface some other language and attempt to “underst: usually has its own “schema” which is similar to the database conceptual schema. 5. Interface schema to the Interfaces for Parametric Users : Parametric users, such as bank tellers, often have must perform repeatedly system analyst and programmers, _ om ss asmall set of operation that th design and implement a special interface for a known class of naive users. Cc : Interfaces for the DBA: Most database system contain privileged commands that can bé used only by the DBA’s staff. These includes commands for creating accounts, setting system parameters etc. DATA DEFINITION LANGUAGE (DDL) (UPTU, 2004, 2006) (Im) (tis a set of SQL commands used to create, modify and delete database structures byt Notdata. These commands are normally not used by a general user, who should be accessing the database tia., an application. They are normally used by th® DBA Yo a limited ex base designer or application are immediate developer. ‘These statements are immediate, ee net susceptible to Rollback commands. DDL also updates a special set of ables called the data dictionary or data directory. -Adata dictionary contains metadata, ie., data about data. = iple of metadata. A database system consults the data ifying actual data. Database Management System Fundamental Commands of DDL: The main tasks of the Date Definition Language are : + Tocreate the database 0! ables, Indexes etc. + To modify the databse objec we can chant p or add a field from/to t pjects like t ge the data type of a field, ts, for example, he table. we can dro} » To destroy the database objects: Creating Database Objects : tase the CREATE statement. For example : For creating database objects We tax : SQL > CREATE TABLE < table Name > (fieldname, Datatype, (width, fieldname, Datatype (width), ----); . Example: SQL > CREATE TABLE STUDENT (NAME VARCHAR, (12) (2, 0), ADDRESS VARCHAR, (10), Class Number (2, 0)); Output: Table Created. This creates a table of students hi ), AGE-NUMBE aving field namne, age, address and class: ription of Table d field width by “describ De Tris possible to obtain description o f table to know field ant command. Syntax: SQL> DESCRIBE Tablename; OR DESC Tablename; Example: SQL> DESCRIBE STUDENT; - Output: TYPE NAME VARCHAR2(12) AGE NUMBER(2) aa VARCHAR2(10) ~ SS NUMBER(2) ‘This describes the database of student, Creating table using Constraint Example: SQL > CREATE TABLE Dept. (deptno.NUMBER(2) PRIM ; ARYKEY, D B VARCHAR2(25) CHECK (LOC IN (‘Delhi’, Dosa Noidemaeeede 10) NOTNULL, LO In the abov ‘ Q The oat al » Dept, table has three Sgldanamel cola ee “aul accept the number type Ee dept.no, dname and lo Enlehis to be stor a we have tolenter the ni er ot department stored ih the datgpgses the. Hea ueeth fo partment wll je havinga valid name, We Se eas pulmet ’ ri ey < i obser ena her cos vhs ‘Noida’. Any value of other thai a ese tht n these Cons' department, that every new NULL. The last co! three locations nam will not be accepted. Introduction to DEMS: er sarative Date Integrity UNTRUE No duphicney. bot Bee ene are 100 (YDES of data Integrities; NULLA anu PRIMARY Mo dtep,No Nou “patil ' PAULI Specifics default vale, NOT NUM ~ Pupticacy, pur at ia NOTNULL = Specifies that value should not be null not nut iq UNIQUE ~ Specifies that vale should be unique. CHECK - Specifies that values should be eheeked, (@ 2, Referential ; (a) PRIMARY KEY ~The field is Primary field, (b) FOREIGN KEY ~ (gq DELETE/UPDATE Restrict ~ NULL Value Concept NULL Value Concer iva particular row do not contain a data, then it may be treated as null value, Column of any data type may contain NULL unless, the column was defined as NOT NULL, When table was created. NOT NULL Ifa column is defined as NOT NULL, then it becomes a mandatory column ie., the user nas to enter the data into it. It can take duplicate values if it is not a unique column but annot take NULLS. Example : SQL > CREATE TABLE Emp (EMP_NO VARCHAR2(2} NOT NULL); rimary Key primary key is a one or more column used to uniquely identify each row in the table] hese values should never be changed and should never be NULL. Through this key, rows Tthe table are individually identified. NULLS are not allowe’ in the primary key column. he important point about primary key is t nly one primary key per table is allowed. he reason may be that the important task which the primary key. performs is to uniquely lentify the row. — = _ Example : SQL > CREATE TABLE Emp (emp_no VARCHAR2(2) Primary Key); . ip (emp. In this case Emp_no is primary key. nique Key mate Key This is similar to primary key. It is used to ensures that information in the colu! ch record in unique. feample : SQL > CREATE TABLE Emp (emp_no VARCHAR2(2) Constraint (Uniquel}: in this case emp_no is unique key. fault Value ne ymin for Wi 7 Fi hen the cell is created, default value can be assigned to it as below. pample : SQL > CREATE TABLE Emp (emp_no VARCHAR2(2) Default 0) inthis case default value of emp_no is 0. Foreign Key : aa key represents the relationships between aed El ca Refereng ix ae A rgein y ClN Te can lao Be used elcid mae ie Sete or prrespondin g primary key value in the primary key table to nae a meaning. A foereign key value can be left nul ~ REFERENCES emp 1; key in emp table is Foreign key. 1. It is inserted by. In this case the Reference Check Constraints of the name data entered. These constraints can be inserted to check integrity syntax : CONSTRAINT CHECK (Logical Expression) Example : SQL> CONSTRAINT CHECK (NAME LIKE “M%); an be declared at the time of creations of table. The constraint c Example of Constraints = SQL > CREATE TABLE LOANS ( account NUMBER (6, 0) NOT NULL, Loan_number NUMBER (6, 0) NOT NULL UNIQUE, Loan_type VARCHAR2(8) CONSTRAINT Loan_type in (PERS’, ‘HOME’, ‘AUTO}), amount NUMBER (8, 0) NOT NULL, Loan_Date DATE DEFAULT SYSDATE); Creating Index Indexes are used to speed up the retrieval of records in response to certain seard condition. The index structure provides the alternative way of accessing the records withot affecting the physical, placement of records on physical media, The index is construct’ based on a column or a group of columns from the table. When this index is used in query for searching the records, it retrives the information in an efficient manner. The Syntax QL > CREATE [UNIQUE] INDEX ON CREATE INDEX Empno_index ON emp (emp no); Modifying the table : To change the definition of a table, we have to three clauses ADD, MODIFY and DROP, which page cae tne + Add a new column , + Add a new constraint * Modify acolumn + Modify a constraint ropacolumn Introduction to DBMS CE + Drop "constraint ac : at SOL > ALTER TABLE (ADD/MODIFY/DROP; (column tex! A spection $QL> ALTER TABLE emp ADD (Commission NUMBER (7, 2); 2 TER TABLE EMP MODIFY (Commission NUMBER (8, 2)); 9. LTER TABLE emp DROP COLUMN Commission; anc an object (table/view) ie DROP Command is used to drop an object permanently. tag: SQL> DROP TABLE ;’ erimple : SQL> DROP TABLE emp; yaTA MANIPULATION LANGUAGE (DML) : (UPTU, 2004, 2006) (imp, iris the area of SQL that allows changing data within the database! /xDNL is a language that enables users to access or manipulate data or organised by heappropriate data model. ‘Through DML, we can 1. Insert the new ~ then we have to 2. Modify the data, already s' database, if an employee gets the record of that employee. 2. Deletion of the Data: For example, ifan employee region from the company than we have to delete that record from the database. 4. Retrieve the ation : For example, if we want to display the address of employee than we have to write the query statement for that information. in the database : For example, if person joins the company sert the information of that employee in our employee database. »d_ in the database : For example, in employee e (increment) in his salary than we have to modify This of two types : 1. Procedural DML. (UPTU 2010) (05 Marks) 2. Non-procedural DML. 1. Procedural DML : It requires a user to specify what data are needed and how to get a Italso requires writing the procedures/ methods to specify what datas needed. Sontfol a DML language has all the features of any other high-level language including “Ogio! Constructs, error handling and other features.) Non-Procedural DML : It is also called as declarative DML and it require a user to 4 need data are needed without specifying how to get those data. Nonsprpoedurel ,, {Re collection of commands for data manipulation including insert, update, delete mdi guery the data. ————oeeeee———e— mental Commands of DML : ~ New Records in the Table : glues could be inserted into the table by use of INSERT INTO COMMAND. Proteins INSERT INTO emp (emp no, name, department, age, bp) VALUES (701, ‘Suresh’, 5 35000); ¢ ee on 7% shich the corresponding columns are spey Output n r svangenrmans be ves inane same order SDD UCIT ea craingtothatook, + specified in the list then it ee ME, AGE, ADDRESS, CLASS) VALUES (yj; Hany cohamn is 00" RT INTO STUD (NAI SQL> INSE 24, KANPUR’ 1 Outpat : 1 row created This insert values into database of student Addition of Field from the ‘SQL Editor: pwn = taallow SQL to read data values from the screen by attachis g¢etevis s * afield, &field, .....) Syate o table values (Gfield,” &fiel i elds are enclosed in single quote. a QL > Insert into emp values (&emp no, ‘&empname’, ‘kaddress’, ‘&deszmber 1 and is executed, the editor ask the value for ee themerator a the data screen. bie. sert the recoriis of fifteen students or more than one table. Once the value is inserted then just press ‘back slash’ {fhe 0} Synta Exam i command the table haa been created and ‘insert into’comm it will of data into the table. The data filled in the table can be vit y “SELECT” command. _— = s in the table, the ‘SELECT’ command is used. FROM Tablename; QL > SELECT * FROM emp; the con ete data in the table. SELECT * FROM STUDENT; KALPANA OB AMISHA Manager NOOPUR Manager RAJEEV Admin Officer. itoill display the name of the employees and their desi ignation for all the records. retrieving data of selectred columns and selected rows : ‘Syntax: SELECT FROM [WHERE Condition]; pxample : SQL > SELECT ename, desig FROM emp WHERE dest.no=10; ‘qe command will give the name and designation of all the exployees from department number 10. The WHERE clause expects three element : a column name, a comparison ‘operetor and content or the List values to be compared against the column values from the table. Sorting Data in a Table : ¢ ORDER BY Command is used for sorting the data in either increasing or decreasin; ORDER BY Ci d is used fo ing the data in either i ing or di ig order, depending in the condition specified in the select statement. Syntax : SELECT * FROM ORDER BY [Sort order] Example : SQL > SELECT * FROM emp ORDER At will give the data in the increasing order of salary, all records having null values in the Slary column will be displayed in the last. Output : ‘Exp table - Emp no. Ename Sal. 1002 RADHA 8,000/- 1001 RAVI 9,200/- 1006 RAM 10,800/- 1008 RAJESH 11,000/- - For getting the data in decreasing order of salary, we use DESC at the end. EXAMPLE : SQL > SELECT * FROM emp ORDER BY Sal DESC; Ebdating the rows ‘ geste Command is used to change the values of one or more columns in a row or a set ple : SQL > UPDATE emp SET ename = ‘Akash’ WHERE empno = 1002; ple : SQL > UPDATE emp SET Sal = (SELECT MAX (sal) from emp] Bris ‘RE ename= ‘Akash’; command will update the salary of Akash to the maximum salary of emp table. Introduction to DBMS GEEa Database Management System Deleting the row ‘To remove one or more record from a table, we use Delete command, Syntax : DELETE FROM [WHERE Condition]; ; Example : SQL > DELETE FROM emp WHERE ename = ‘Kalpana’; f P DCL (Data Control Language) "Tis the component of SQL statement that control access to data and to the datat Occasionally DCL statements are grouped with DML statements, 7 . i Through DCL, we can 1, Commit: Save work done, - 2. Roll back: Restore database to original since the last commit. Fundamental Commands of DCL When an INSERT, UPDATE and can reverse or rollback the work w DELETE operations are performed on the database yhat we have done. We process of s: aving the work é, Rorranently or routing back work is controlled by Two commands namely: COMMIT: ROLLBACK. iy COMMIT make changes in the current transaction pemanent and ends the transaci Syntax : COMMIT; Example : SQL > COMMIT’, a Output : Commit Complete Syntax : ROLLBACK; Example : SQL > ROLLBACK; Output : ROLLBACK Complete, bei INSERT, UPDATE & DELETE Commands are jot i i the DDI comme oat Pai re not made final untill we commit them _ 3 z g 3 8 = 3 E s B z

You might also like