Structured Query Language (SQL) : Advant
Structured Query Language (SQL) : Advant
Data Definition Language - Data Manipulation Language - Basic SQL Queries – Views
ADVANTAGES:
1.CREATE
2.ALTER
3.DROP
4. View
5.Truncate
6. Rename
1.CREATE COMMAND:
);
DBMS@Ch7 Page 1
Basic components necessary to create a table:
A table must have the following components:
Column constraint:
CREATE TABLE employee
( empno NUMBER (4) PRIMARY KEY,
ename VARCHAR2(10),
job CHAR(9) NOT NULL,
mgr_id NUMBER(4) REFERENCES employee(empno),
hiredate DATE,
salary NUMBER(7,2),
commission NUMBER(7,2),
deptno NUMBER(2) REFERENCES DEPT(DEPTNO)
DBMS@Ch7 Page 2
);
Table constraint:
CREATE TABLE employee
( empno NUMBER(4),
ename VARCHAR2(10),
…
deptno NUMBER(2) NOT NULL, PRIMARY KEY (empno, ename)
);
CREATE TABLE employee
( empno NUMBER(4),
ename VARCHAR2(10),
…
deptnoNUMBER(2) NOT NULL,FOREIGN KEY(deptno) REFERENCESdept (deptno)
);
Note: The FOREIGN KEY reserved word should be used only for table constraints.
CONSTRAINT clause:
Constraints can be named by users using the CONSTRAINT clause as shown below.
2.ALTER COMMAND:
DBMS@Ch7 Page 3
Tables can be altered in one of two ways: by changing a column’s definition, or by adding a
column.
Adding a column:
Syntax: ALTER TABLE table_name ADD ([column] / [constraint]);
Ex: ALTER TABLE employee ADD (deptnoNUMBER(2) );
Modifying a column:
3.DROP COMMAND:
Used to drop tables when they are no longer needed.
Syntax: DROP TABLE table_name;
Table dropped.
SQL>descStudentt;
ERROR:
ORA-04043: object Studentt does not exist
DBMS@Ch7 Page 4
4.TRUNCATE COMMAND :
Syntax:
truncate table <table_name>;
Description:
The details in the table are deleted but the table structure remains.
Example:
SQL> truncate table Student;
Table truncated.
SQL>desc Student;
5.RENAME COMMAND :
Syntax:
rename<old_table_name> to <new_table_name>;
Description:
The old table name is replaced with the new table name.
Example
SQL> rename Student to Studentt;
Table renamed.
SQL>desc Student;
ERROR:
ORA-04043: object Student does not exist
SQL>descStudentt;
DBMS@Ch7 Page 5
REGNO NUMBER(8)
NAME VARCHAR2(15)
DEPT VARCHAR2(20)
YEAR NUMBER(4)
View created.
SQL>descStudentview;
Example:
SQL> drop view Studentview;
View dropped.
DBMS@Ch7 Page 6
7.CREATE DUPLICATE TABLE :
SQL> create table Stud as select * from Student;
Table created.
SQL>desc Stud;
2.UPDATE
3.INSERT
4.DELETE
INSERT COMMAND :
Syntax:
insert into <table_name> values(Column_name);
Description:
The ‘insert into’ command insert the values in the specified table .In the insert into SQL sentence
the columns and values have a one to one relationship (i.e) the first value described into the first
column, the second value described being inserted into the second column and so on.
Example:
SQL> insert into Student values(®no,'&name','&city','&dept');
Enter value for regno: 100
Enter value for name: A
Enter value for city: Cuddalore
Enter value for dept: IT
old 1: insert into Student values(®no,'&name','&city','&dept')
DBMS@Ch7 Page 7
new 1: insert into Student values(100,'A','Cuddalore','IT')
1 row created.
(Or)
DELETE COMMAND :
Syntax:
delete from <table_name> [where <Condition>];
Description:
The delete in SQL is used to remove rows from table. To remove
All the rows from a table.
(OR)
A select set of rows from a table.
Example:
SQL> delete from Student where regno=101;
1 row deleted.
UPDATE COMMAND :
Syntax:
update<table_name> set <field_name>=<Expression/Values> [where <Condition>];
Description:
The update command is used to change or modify data values in a table. To update
All the rows from a table.
(OR)
A select set of rows from a table.
Example:
SQL> update Student set dept='CSE' where regno=101;
1 row updated.
SELECT COMMAND:
SELECT command is used to retrieve the information from a table or tables.
Format: SELECT column1, column2…
FROM table_name
WHERE conditions;
DBMS@Ch7 Page 8
SELECT clause
The SELECT clause is used to specify which columns are to be selected. In the following
statement ‘*’ retrieves all the columns from the table employee.
Ex: SELECT *
FROM employee;
FROM clause
FROM is used to specify the names of the table or tables from which the data is retrieved.
WHERE clause:
The WHERE clause is used to specify what qualifiers are to be imposed on the data to be
retrieved. This is known as SELECTION. A table that is built from columns from one or more
tables is called a PROJECTION, or a RESULT TABLE. The following statement retrieves all
the records whose department_id is 13 and reports only those columns, which are in the SELECT
clause.
DISTINCT keyword:
The following statement retrieves all the manager_ids with no duplicates.
ORDER BY clause:
The ORDER BY clause is used to sort the selected data in a specific order. By default, records
are sorted in ascending order. The key word DESC is used to sort in the descending order (ASC
is used for ascending).
DBMS@Ch7 Page 9
Logical operators such as ‘=’, ‘<’, ‘>’, ‘<=’, ‘>=’, ‘!=’ or ‘^=’ or ‘<>’ are used to compare a
column or expression with a single value.
NULL checking:
NULL tests to see if data exists in a column for a row. If the column is completely empty, it is
said to be NULL, and if it is non-empty, it is said to be NOT NULL. The keyword ‘IS’ must be
used to check if a value is NULL or NOT NULL. The following statement returns all the records
where data does not exist in manager_id column. (NULL is generally used to represent a value
which is not known, NULL is not equal to any value)
The following statement returns all the records where data exists in commission column.
MULTI-VALUE CONDITIONS:
IN:
IN checks if the expression is equal to any member of the given list of values.IN works with
VARCHAR2, CHAR, DATE, and NUMBER data types. The following statement retrieves all
records whose department_id is 10,20 or 30.
DBMS@Ch7 Page 10
FROM employee
WHERE department_id IN (10, 20, 30);
NOT IN:
NOT IN means the expression is not equal to any member of the given list of values. NOT IN
works with VARCHAR2, CHAR, DATE, and NUMBER data types. The following statement
retrieves all those records whose job_id is neither 670 nor 669.
BETWEEN clause:
BETWEEN…AND clause is used to check if an expression is between a pair of values. The
following statement retrieves all those records whose salary is greater than or equal to 3000 and
less than or equal to 5000.
NOT BETWEEN:
If NOT is combined with BETWEEN clause, only those records are retrieved which are not in
the specified range, including the specified values. The following statement retrieves all the
records whose salary is less than 3000 and greater than 5000.
LOGICAL OPERATORS:
The AND and OR are called Logical operators. They are used to combine multiple conditions in
the queries.
‘AND’ OPERATOR
Returns TRUE only when both conditions are true. The following statement retrieves those
records which satisfy both the conditions in the WHERE clause.
DBMS@Ch7 Page 11
WHERE salary = 5000
ANDJob_id IN (670, 669)
‘OR’ OPERATOR
Returns TRUE when either one of the conditions is true. The following statement retrieves those
records which satisfy at least one condition in the WHERE clause.
SUBQUERIES
A query (that is, a SELECT statement) may be used as a part of another SQL statement (called
the parent, or outer statement), including CREATE TABLE, DELETE, INSERT, SELECT and
UPDATE. The results of the child query (also called a sub-query) are passed to the parent SQL
statement. A sub-query cannot contain ORDER BY clause.
The sub-query returns a single value to the outer-query. All of the logical operators that test
single values can work with sub-queries, as long as the sub-query returns a single row. The
following example illustrates a sub-query, which returns only one value.
FROM employee
The sub-query may return one or more rows, the value in the column for each row will be
stacked up in a list. The following are some relevant points:
DBMS@Ch7 Page 12
In the following statement, the sub-query returns more than one row to the outer query. So, IN
operator is used.
FROM employee
NESTED SUBQUERIES:
Nested sub-queries are those, which have a sub-query for an inner query. The following
example demonstrates a nested sub-query.
FROM employee
FROM employee
FROM employee
OPERATOR ‘ANY’:
=ANY is the equivalent of IN. Operator can be any one of ‘=’, ’>’, ‘>=’, ‘<’, ‘<=’, ‘!=’
and list can be a series of literal strings (such as ‘RAVI’,’KISHORE’,’RAJU’) or a series of
literal numbers (such as 2, 43, 76, 32.06, 44) or a column from a sub-query, where each row of
the sub-query becomes a member of the list.
Ex: SELECT last_name
FROM employee
WHERE department_id=10
AND
Job_id =ANY (SELECT job_id
FROM employee
WHERE department_id=20);
OPERATOR ‘ALL’:
!=ALL is the equivalent of NOT IN. Operator can be any of ‘>’, ‘>=’, ‘<’, ‘<=’, ‘!=’
and list can be a series of literal strings (such as ‘RAVI’,’KISHORE’,’KIRAN’), or a series of
literal numbers (such as 2, 23, 76, 32.06, 44), or a column from a sub-query, where each row of
the sub-query becomes a member of the list.
DBMS@Ch7 Page 13
SELECT last-name
FROM employee
CORRELATED SUB-QUERIES:
A correlated sub-query is that which is executed repeatedly once for each value of a
candidate row selected by the main query. The outcome of each execution of the sub-query
depends on the values of one or more fields in the candidate row; that is, the sub-query is
correlated with the main query.
In the following example, the department_id of each row in the main query is correlated
with the department_id of the rows in the subquery.
SELECT first_name, last_name FROM employee E
EXISTS:
Exists is test for existence. It is placed the way IN might be with a subquery, but differs
in two ways. (1) It does not match a column or columns and (2) It is typically used only with a
correlated sub-query. EXISTS returns true in a WHERE clause if the sub-query that follows it
returns at least one row.
DBMS@Ch7 Page 14
The above query can also be written using IN as follows.
NOT EXISTS:
NOT EXISTS is typically used to determine which values in one table do not have
matching values in another table. NOT EXISTS allows you to use a correlated a sub-
query to eliminate from a table all the records that may successfully be joined to another
table
GROUP FUNCTIONS:
A GROUP FUNCTION computes a single summary value (such as sum or average) from
the individual number values in a group of values. Group functions are useful only in queries and
sub-queries.
COUNT( ): gives the count of rows for a column, or for a table (with *).
MIN( ):- gives the minimum of all values for a group for rows.
MAX ( ):- gives the maximum of all values for a group of rows.
DBMS@Ch7 Page 15
JOINS:
A join combines columns and data from two or more tables (and in rare cases, of one
table with itself). The tables are all listed in FROM clause of the SELECT statement, and the
relationship between the two tables is specified in the WHERE clause, usually by a simple
equality. This is often called an
Equi-Join because it uses the equal sign in the WHERE clause. The tables can also be joined
using other forms of equality, such as >=, < and so on, then it is called a Non-Equi Join. If a
table is combined with itself then, it is called Self-Join.
SELECT E.last_name,D.name
Non-Equi-Join example:
Self-Join example
AND E.salary>M.salary
OUTER JOINS:An OUTER-JOIN is a method for intentionally retrieving selected rows for one
table that don’t match rows in the other table. (+) must immediately follow the join column of
the shorter table, as saying add an extra (NULL) row.
DBMS@Ch7 Page 16
List the name of departments and employees including which do not have any employee.
GROUP BY:
GROUP BY causes a SELECT to produce one summary row for all selected rows that
have identical values in one or more specified columns or expressions. Each expression in the
SELECT clause must be one of these things.
A constant
A function without parameters (sysdate, user)
A group function like SUM, AVG, MIN, MAX, COUNT
A column/expression matching identically to an expression in the GROUP BY clause.
GROUP BY department_id
HAVING CLAUSE:
UNION:
UNION combines two SELECT queries. It returns all distinct rows for both SELECT
statements. But there are some stipulations.
DBMS@Ch7 Page 17
GROUP BY department_id
UNION
SELECT department_id
UNION ALL:
When UNION ALL is used, it returns all rows for both SELECT statements, regardless
of duplicates.
GROUP BY department_id
UNION ALL
SELECT department_id
INTERSECT:
INTERSECT combines two queries and returns only those rows from the first SELECT
statement that are identical to at least one row from the second SELECT statement. The number
of columns and data types must be identical between SELECT statements.
SELECT department_id
FROM employee
GROUP BY department_id
INTERSECT
SELECT department_id
DBMS@Ch7 Page 18
FROM department d, location l
MINUS:
MINUS combines two queries. It returns only those rows from the first SELECT
statement that are not produced by the second SELECT statement (the first SELECT MINUS the
second SELECT). The number of columns and data types must be identical between SELECT
statements, although the names of
SELECT department_id
FROM employee
GROUP BY department_id
MINUS
SELECT department_id
ORDER BY POSITION:
The resultant rows from SELECT statements can also be sorted in ascending or
descending order by specifying the position of the column to be sorted.
(SELECT department_id,job_id
FROM employee
WHERE department_id=20
UNION
SELECT department_id,job_id
FROM employee
WHERE department_id=10)ORDER BY 2;
DBMS@Ch7 Page 19