Practical File SQL Queries DBMS
Practical File SQL Queries DBMS
2009
Submitted to:
Kanika Mahajan Concerned Lect. in DBMS Ashoka college of Computer Education
Ashoka College of Computer Education |
Certificate
This is certified that the practical file belongs to Prabhat Kumar, Class roll no. 06 and Examination Roll noof session 2009-10 and has completed all the practical in the college computer lab under our guidance and his behavior in the college is good.
Ashoka College of Computer Education |
Index
S. no.
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25.
Name of practical
Database, DBMS definition Introduction to SQL Components of SQL, Data types SQL Queries create, insertion Create a table Describe the table Insert the values To view the table Sorting the data To rename the table Delete a particular row Lower case Upper case Drop the table Maximum Minimum Average Like Between Primary key Unique key Count Sum Alter Update
Remarks
Database
A database is an organized collection of facts. In other words, we can say that it is a collection of information arranged and presented to serve an assigned purpose. An example of a database is a dictionary
some examples of the various incarnations of DBMS technology that are currently in use, and some of the basic elements that are part of DBMS software applications. As the tool that is employed in the broad practice of managing databases, the DBMS is marketed in many forms. Some of the more popular examples of DBMS solutions include Microsoft Access, FileMaker, DB2, and Oracle. All these products provide for the creation of a series of rights or privileges that can be associated with a specific user. This means that it is possible to designate one or more database administrators who may control each function, as well as provide other users with various levels of administration rights. This flexibility makes the task of using DBMS methods to oversee a system something that can be centrally controlled, or allocated to several different people.
maintaining systems.
It is English like language.
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. They are normally used by the DBA not by user to a limited extent, a database designer or application developer. These statements are immediate i.e. they are not susceptible to ROLLBACK commands. It should also be noted that if several DML statements for example UPDATES are executed then issuing any DDL command would COMMIT all the updates as every DDL command implicitly issues a COMMIT command to the database. Anybody using DDL must have the CREATE object privilege and a table space area in which to create objects. For example: - CREATE, ALTER, DROP, TRUNCATE, COMMENT etc.
2)
1)
4)
values of fixed length. The size in brackets determines the number of characters the cell can hold. The maximum number of characters (i.e. the size) this data type can hold is 255
Ashoka College of Computer Education |
characters. The data held is right- padded with spaces to whatever length specified.
variable length alphanumeric data. It is a more flexible form of the CHAR data type. The maximum this data type can hold up to 4000 characters. One difference between this data type and char data type is oracle compares varchar values using non padded comparison semantics i.e. the inserted values will not be padded with spaces. VARCHAR can hold 1 to 255 characters. Varchar is usually a wiser choice than char due to its variable length format characteristics but keep in mind that char is much faster than varchar sometimes up to 50%.
NUMBER: - The number data type is used to store numbers
(fixed or floating point).The precision (P) determines the length of the data while(s), the scale, determines the number of places after the decimal. The NUMBER data type that is used to store number data can be specified either to store integers or decimals with the addition of a parenthetical precision indicator. If we do not use then the default value is 0 and if we dont use precision then by default value stored can be of 38 digits.
DATE:- The DATE data type stores date and time information. Although date and time information can be represented in both character and number data types, the DATE data type has special associated properties. For each DATE value, Oracle stores the following information: century, year, month, date, hour, minute, and second.
LONG:- LONG columns store variable-length character strings containing up to 2 gigabytes, or 231-1 bytes. LONG columns have many of the characteristics of VARCHAR2 columns. You can use LONG columns to store long text strings. The length of LONG values may be limited by the memory available on your computer
Ashoka College of Computer Education |
10 DBMS & SQL queries The use of LONG values is subject to some restrictions:
A table can contain only one LONG column. You cannot create an object type with a LONG attribute. LONG columns cannot appear in WHERE clauses or in integrity constraints (except that they can appear in NULL and NOT NULL constraints). LONG columns cannot be indexed. A stored function cannot return a LONG value. You can declare a variable or argument of a PL/SQL program unit using the LONG datatype. However, you cannot then call the program unit from SQL. Within a single SQL statement, all LONG columns, updated tables, and locked tables must be located on the same database.
QUERY
A query is a concise memo submitted to an editor by a writer seeking publication. It is basically an in query to see whether the writers work is of interest to a particular publication. A query briefly details a writers experience and knowledge of the subject matter, and gives a summary or synopsis of the article the writer hopes to have published. An approximate word count for the proposed article or feature is also generally included.
1) THE CREATE TABLE COMMAND :- The CREATE TABLE command
defines each column of the table uniquely. Each column has a minimum of three attributes, a name, data type and size (i.e. column width). Syntax: - CREATE TABLE<table name>(<column Name 1> <data type>(<size>), <columnname2> <data type>(<size>)); Example:
SQL> create table student(name varchar(23),roll_no number(12),class varchar2(12),address varchar(23)); Table created. 2) THE INSERTION OF DATA INTO TABLE: - Once a table is created, the
most natural thing to do is load this with data to be manipulated later i.e. to insert the rows in a table. The data in a table can be inserted in three ways. Syntax:-INSERT INTO <table name >(<columnname1>,<columnname2>)
VALUES(<expression1>,<expression 2>); Ashoka College of Computer Education |
11 DBMS & SQL queries OR INSERT INTO <tablename>VALUES(<expression1 >,<expression2> ); OR INSERT INTO <tablename> VALUES(<&columnname1> ,<&columnname2>); Example:SQL> insert intostudent(name,roll_no,class,address)values('Prabhat',06,'BCA',Hat limore'); 1 row created. Or SQL> insert into student values('kishore',01,'BCA','Nagri'); 1 row created. Or SQL> insert into student values('&name','&roll_no','&class','&address'); Enter value for name: Amarjeet Enter value for roll_no: 30 Enter value for class: BCA Enter value for address: airwan old 1: insert into student values('&name','&roll_no','&class','&address') new 1: chack') insert into studen values('Atinder','04','BCA','Sawan
1 row created.
FOR inserting more values we use / slash after SQL> as below but after above syntax used: SQL> / Enter value for name: Vinay Ashoka College of Computer Education |
12 DBMS & SQL queries Enter value for roll_no: 08 Enter value for class: BCA Enter value for address: Barnoti old 1: insert into student values('&name','&roll_no','&class','&address') new 1: insert into studen values('Vinay','08','BCA','Barnoti')
1 row created. 3) FOR VIEWING DATA IN THE TABLE: - Once data has been inserted
into a table, the next most logical operation would be to view what has been inserted. The SELECT SQL verb is used to achieve this. The SELECT command is used to retrieve rows selected from one or more tables.
Syntax: - SELECT * FROM <table name>; If we want to see all the tables that are already exist in the database .we use SELECT * FROM TAB; Example:SQL> select * from student;
NAME
ROLL_NO CLASS
ADDRESS
----------------------- ---------- ------------ ---------Prabhat Kishore Amarjeet Vinay 06 BCA 01 BCA 30 BCA 08 BCA Hatlimore Nagri airwan barnoti
1 row created.
When we use the command SELECT* FRM TAB; the output is displayed as:Ashoka College of Computer Education |
TNAME
TABTYPE
CLUSTERID
------------------------------ ------- ---------ABC ANKU BONUS DEPARTMENTS DEPT EMP EMPLOYEE EMPLOYEES STUDENT TABLE TABLE TABLE TABLE TABLE TABLE TABLE TABLE TABLE
9 rows selected.
Syntax: - SELECT DISTINCT <column name 1>,<column name2> FROM <table name> ; This syntax will give the unique values of column 1 and column 2. Example:SQL> select distinct name,roll_no from student;
NAME --------------------
ROLL_NO ----------
Syntax:- SELECT DISTINCT * from <tablename>; Example:SQL> Select DISTINCT * from student;
NAME -----------------Prabhat
ROLL_NO CLASS
ADDRESS
viewed in sorted order. The rows retrieve from the table will be sorted either in ascending or descending order depending on the condition specified in the select sentence.
Syntax: - SELECT * FROM <tablename>ORDER BY<column name1>,<column name 2> <[sort order]>; Example:SQL> SELECT * FROM STUDENT ORDER BY name;
NAME
ROLL_NO CLASS
----------------------- ---------- -----Amarjeet Atinder Dushyant Kishore Prabhat Vinay 30 04 34 01 06 08 BCA BCA BCA BCA BCA BCA
NAME
ROLL_NO CLASS
ADDRESS
08 06 01 34 04 30
6 rows selected.
NAME
ROLL_NO CLASS
ADDRESS
01 04 06
16 DBMS & SQL queries Vinay Amarjeet Dushyant 08 30 34 BCA BCA BCA barnoti airwan jagatpur
6 rows selected.
can be modified by using the ALTER TABLE command. ALTER TABLE allows changing the structure of an existing table. With ALTER TABLE it is possible to add or delete columns, create or destroy indexes, changes the data type of existing columns, or rename columns or the table itself.
(a) ADDING NEW COLUMNS Syntax: - ALTER TABLE <Table name> ADD(<New column Name> <data type> (<size>),<new column name><data type>(<size>).); Example:-
(b) DROPPING A COLUMN FROM A TABLE Syntax: - ALTER TABLE<TABLE NAME>DROP COLUMN<COLUMNNAME>; Example:- alter table prabhu drop column name;
(c) MODIFYING EXISTING COLUMNS Syntax: - ALTER TABLE<Table name>MODIFY(<COLUMN NAME> <NEW DATATYPE>(<NEW SIZE>)); Example:- alter table prabhat modify(name varchar(22));
17 DBMS & SQL queries 7) RENAMING TABLES: - Oracle allows renaming of tables. The rename
operation is done atomically, which means that no other thread can access any of the tables while the rename process is running.
Syntax: - RENAME <Table name> to <New Tablename> Example:SQL> rename student to candidates;
Table renamed.
8) DESTROYING TABLES: DROP COMMAND: - By using the DROP TABLE statement with the table name we can destroy a specific table . Syntax: - DROP TABLE <table name>; Example:--
TRUNCATE COMMAND:- The truncate command is much faster in comparison to delete statement but similar to the drop command as to destroy a specific table. Syntax:- TRUNCATE table <tablename> Example:-
18 DBMS & SQL queries 9) DISPLAYING THE TABLE STRUCTURE:- To display information about the columns defined in a table use the following syntax. Syntax: - DESCRIBE <table name> This command displays the columns names, the data types and the special attributes connected to the table. Example: -
Name
Null?
Type
---------------------------------- -------- ----------EMP_ID EMP_NAME DEPT_ID DEPT_NAME SALARY NUMBER(5) VARCHAR2(20) NUMBER(10) NAME(12) NUMBER(21)
10) UPDATING THE CONTENTS OF A TABLE: - The update command is used to change or modify data values in a table. The verb UPDATE in SQL is used to either all the rows from a table or a select set of rows from a table. UPDATING ALL ROWS:- The update statement updates columns in the existing tables rows with new values .The SET clause indicates which column data should be modifying and the new values that they should hold. The WHERE CLAUSE specifies which rows should be updated. Otherwise all table rows are updated. Syntax: - UPDATE < Table name> SET <column name1>=<expression1> , <column name2>=<expression2>; Ashoka College of Computer Education |
UPDATES RECORDS CONDITIONALLY:Syntax :- UPDATE <table name> SET <columnname1> = <expression1>, <columnname2> = <expression2> WHERE <condition>;
CONSTRAINTS 11) NOT NULL:- The NOT NULL column constraint ensures that a table column cannot be left empty. When a column is defined as not null, then that column becomes a mandatory column. It implies that a value must be entered into the column if the record is to be accepted for storage in the table. Syntax:- <Column Name> <data type>(<size>) NOT NULL ; Example:-name varchar(22) not null;
THE PRIMARY KEY CONSTRAINT: - A primary is one or more column in a table used to identify each row in a table. None of the fields that are part of the primary key can contain a null value. A table can have only one primary Syntax:- <Column name> <data type>(<size>) PRIMARY KEY Example:-
SQL> create table student name varchar2(12), roll_no number(12) primary key, class varchar2(21) NOT NULL, dob date); or
20 DBMS & SQL queries SQL> create table student(name varchar2(12), roll_no number(12) constraint pk_roll primary key ,class varchar2(21) not null, dob date);
12) THE FOREIGN KEY (SELF REFERENCE) CONSTRAINT:-Foreign key represent relatio nships between tables. A foreign key is a column (or a group of columns) whose values are derived from the primary key or unique key of some other table. The table in which the foreign key is defined is called a FOREIGN TABLE or DETAIL TABLE. The table that defines the primary or unique key and is referenced by the foreign key is called the PRIMARY KEY or MASTER KEY. Syntax: - Foreign key (<column name>) REFERENCES <table name>(column name); Example:-
SQL> create table department(dept_no number(10) primary key,dept_name varchar2(25),dept_loc char(5,e_no number(11), foreign key(e_no) references employee (e_no);
Table created
SQL> describe department; Name -------------------------DEPT_NO DEPT_NAME DEPT_LOC E_NO Null? -------NOT NULL Type ------NUMBER(10) VARCHAR2(25) CHAR(5) NUMBER(11).
13) THE UNIQUE KEY CONSTRAINT:- The unique key constraint permits multiple entries of NULL into the column. These NULL values are clubbed at the top of the column in the order in which they were entered into the table. This is the essential difference between the primary key and the unique constraints when applied to table column(s). Key point about UNIQUE constraint: Unique key will not allow duplicate values. Unique index is created automatically. A table can have more than one unique key which is not possible in primary key.
Syntax:- CREATE TABLE Table name (<columnName1> <datatype>(<size>), <columnName2> <data type>(<size>),UNIQUE(<columnName1>, <columnName2>)); Example:-
SQL> create table student1(roll_no number(12)primary key,dob date,name varchar2(20),class varchar2(2),e_mail varchar2(20) constraint un_st unique);
Table created.
Name
Null?
Type
22 DBMS & SQL queries ROLL_NO DOB NAME CLASS E_MAIL NOT NULL NUMBER(12) DATE VARCHAR2(20) VARCHAR2(20) VARCHAR2(20)
ORACLE FUNCTIONS
Oracle functions serve the purpose of manipulating data items and returning a result. Functions are the programs that take zero or more arguments and return a single value. Oracle has built a no. of functions into SQL. These functions can be called from SQL statements.
14) COUNT (expr) function: - Returns the number of rows where expression is not null. Syntax: - COUNT ([<distinct>[<all>] <expr>) Example:-
EMP_ID NAME
DEPT_ID
SALARY
--------- -------------------- ---------- ---------1 sourabh 2 sonu 3 anku 5 anku 3 panku 21 22 4 21 22 55000 55000 55000 55000 75000
COUNT(SALARY) ---------5
15) COUNT (*) function: - Returns the number of rows in the table, including duplicates and those with nulls. Syntax: - COUNT(*) Example:-
COUNT(*) ---------5
SQL>
salary ---------5
24 DBMS & SQL queries 16) THE SUM FUNCTION: - Returns the sum of the values of n. Syntax: - SUM ([<distinct>][<all>] <expr>) Example:-
SUM(SALARY) ----------295000
17) THE MAX FUNCTION: - Returns the maximum value of expression. Syntax: - MAX([<distinct>][<all>] <expr>) Example:-
MAX(SALARY) ----------75000
18) THE MIN FUNCTION: - Returns the minimum value of expression. Syntax: - MIN ([<distinct>][<all>] <expression>)
19) THE AVG FUNCTION: - Returns an average value of n, ignoring null values in a column. Syntax: - AVG ([<distinct>][<all>] <n>); Example:-
AVG(SALARY) ----------59000
20) LIKE OPREATOR :- The LIKE predicate allows comparison of one string value with another string value, which is not identical. This is achieved by using wildcard characters. Two wildcard characters that are available are: % allows to match any string of any length(including zero length) _allows to match on a single character.
Example:-
26 DBMS & SQL queries EMP_ID -----3 5 NAME ------anku anku DEPT_ID ----------4 21 SALARY --------55000 55000
Example:-
EMP_ID --------1 2 3
DEPT_ID ---------21 22 22
EMP_ID ---------3 5
27 DBMS & SQL queries 21) IN OPERATOR:- In case a value needs to be compared to a list of values then the IN predicate is used. The IN predicates helps reduce the need to use multiple OR conditions. Example:-
EMP_ID ---------2 3
NAME
DEPT_ID
NOT IN OPERATOR:-
EMP_ID -------1 3 5
DEPT_ID ---------21 4 21
22)
SQL> select emp_id,name,dept_id,salary from employees where dept_id between 22 and 30;
EMP_ID --------2 3
DEPT_ID ---------22 22
EMP_ID --------1 5
DEPT_ID ---------21 21
STRING FUNCTIONS
23) UPPER function :- Returns char, with all letters forced to uppercase.
24)
25) INITCAP function: - Returns a string with the first letter of each word in upper case. Syntax:- INITCAP(char) Example:-