SQL UNIT IV
SQL UNIT IV
SQL-UNIT-IV
Introduction
What is SQL?
Dr. E. F. Codd published the paper, "A Relational Model of Data for Large
Shared Data Banks", in June 1970 in the Association of Computer
Machinery (ACM) journal, Communications of the ACM. Codd's model is
now accepted as the definitive model for relational database
management systems (RDBMS). The language, Structured English Query
Language (SEQUEL) was developed by IBM Corporation, Inc., to use
Codd's model. SEQUEL later became SQL (still pronounced "sequel"). In
1979, Relational Software, Inc. (now Oracle) introduced the first
commercially available implementation of SQL. Today, SQL is accepted
as the standard RDBMS language.
Commands in SQL
There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
Note:
NUMBER
This data type is used to declare numeric integer or decimal fields while
creating the table. This syntax of this data type is as follows…
Syntax
NUMBER(L,D)
In the above syntax L represents total length including the sign and
decimal places and D represents the decimal places after the period.
INTEGER
This data type is used to declare numeric integer data items only. It can
also be used as short cut notation as INT. This data type cannot be used
to declare decimal data items.
SMALLINT
Just like INTEGER, but limited to integer values up to six digits. If your
integer values are small, use SMALLINT instead of INT.
DECIMAL
This data type is used to declare float point data items while creating
tables. The syntax is as follows…
Syntax
DECIMAL(L,D)
Character Data Types
CHAR
This data type is used to declare fixed length character data items upto
255 characters.
VARCHAR Or VARCHAR2
This data type is used to declare variable length character data items
upto 2000 characters.
DATE
This data type is used to store date in Julian Date format. The Oracle
data format is DD-MON-YY for example 01-JAN-21.
o CREATE
o ALTER
o TRUNCATE
o RENAME
o DROP
Syntax:
Example:
Syntax:
EXAMPLE
Syntax:
Example:
Syntax
Example
e. DROP: It is used to delete both the structure and records stored in the
table.
Syntax
Example
EXAMPLES
EXAMPLES
EXAMPLE
SELECT COUNT(*) FROM EMP;
Output is 14
EXAMPLE
Output is 29025
MIN: It is used to return the minimum value of the given column name.
EXAMPLE
Output is 800
MAX: It is used to return the maximum value of the given column name.
EXAMPLE
Output is 5000
AVG: It is used to ruturn the average value of the given column name.
EXAMPLE
Output is 2073.21429
Q) Explain Data Manipulation Language commands in SQL?
o INSERT
o UPDATE
o DELETE
Syntax:
Or
For example:
Syntax:
UPDATE BOOK
SET SUBJECT = 'Database Management System Concepts'
WHERE BOOK_Id = 1001;
Syntax:
For example:
The ALTER TABLE statement is also used to add and drop various
constraints on an existing table.
SYNTAX
EXAMPLE
SYNTAX
EXAMPLE
SYNTAX
EXAMPLE
SYNTAX
EXAMPLE
DROPPING CONSTRAINTS
SYNTAX
EXAMPLE
SYNTAX
EXAMPLE
SYNTAX
EXAMPLE
Constraints can be specified when the table is created with the CREATE
TABLE statement, or after the table is created with the ALTER TABLE
statement.
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table.
This ensures the accuracy and reliability of the data in the table. If there
is any violation between the constraint and the data action, the action is
aborted.
Constraints can be column level or table level. Column level constraints
apply to a column, and table level constraints apply to the whole table.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you
cannot insert a new record, or update a record without adding a value to
this field.
The following SQL ensures that the "ID", "LastName", and "FirstName"
columns will NOT accept NULL values when the "Persons" table is
created:
Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
SQL UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for
uniqueness for a column or set of columns.
However, you can have many UNIQUE constraints per table, but only one
PRIMARY KEY constraint per table.
The following SQL creates a UNIQUE constraint on the "ID" column when
the "Persons" table is created:
Primary keys must contain UNIQUE values, and cannot contain NULL
values.
A table can have only ONE primary key; and in the table, this primary key
can consist of single or multiple columns (fields).
SQL PRIMARY KEY on CREATE TABLE
The following SQL creates a PRIMARY KEY on the "ID" column when the
"Persons" table is created:
A FOREIGN KEY is a field (or collection of fields) in one table that refers
to the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the
table containing the candidate key is called the referenced or parent
table.
Notice that the "PersonID" column in the "Orders" table points to the
"PersonID" column in the "Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the
"Persons" table.
The FOREIGN KEY constraint also prevents invalid data from being
inserted into the foreign key column, because it has to be one of the
values contained in the table it points to.
The CHECK constraint is used to limit the value range that can be placed
in a column.
The following SQL sets a DEFAULT value for the "City" column when the
"Persons" table is created:
To join tables, simply list the tables in the from clause of the
SELECT statement. The join condition is generally composed of an
equality comparison between foreign key and the primary key of related
tables. Hence, in the join condition where clause consists of common
attribute used to link tables. The following query is used to join VENDOR
and PRODUCT tables based on the common field V_CODE.
SELECT P_CODE,P_DESC,P_PRICE,V_NAME,V_CONTACT,V_AREACODE,
WHERE PRODUCT.V_CODE=VENDOR_V_CODE;
1. Inner Joins
2. Self-Join
3. Outer Joins
4. Cross Join
1. INNER JOINS
WHERE EMP.DEPTNO=DEPT.DEPTNO;
Returns only the rows that meet the join condition in the WHERE
clause(Old Style)Only rows with matching values are selected.
NATURAL JOIN
Returns only the rows with matching values in the matching columns.
The matching columns must have the same names and similar data
types.
JOIN…USING CLAUSE
Returns only the rows with matching values in the columns indicated in
the USING clause.
JOIN…ON CLAUSE
Returns only the rows that meet the join condition indicated in the ON
clause.
2. SELF JOIN
A table which joins to itself is called self-join.
Old Style SELF JOIN
SELECT E1.ENAME||’ WORKING UNDER ’||E2.ENAME ”EMPLOYEES AND
THEIR MANAGERS” FROM EMP E1,EMP E2
WHERE E1.MGR=E2.EMPNO
3. OUTER JOINS
Returns rows with matching values and includes all rows from the left
table EMP with unmatched values.
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
UNION Operation
UNION is used to combine the results of two or
more SELECT statements. However it will eliminate duplicate rows from
its resultset. In case of union, number of columns and datatype must be
same in both the tables, on which UNION operation is being applied.
Example of UNION
1 abhi
2 adam
ID Name
2 adam
3 Chester
ID NAME
1 abhi
2 adam
3 Chester
UNION ALL
This operation is similar to Union. But it also shows the duplicate rows.
ID NAME
1 abhi
2 adam
ID NAME
2 adam
3 Chester
Union All query will be like,
SELECT * FROM First
UNION ALL
SELECT * FROM Second;
The result set table will look like,
ID NAME
1 abhi
2 adam
2 adam
3 Chester
INTERSECT
Intersect operation is used to combine two SELECT statements, but it
only retuns the records which are common from
both SELECT statements. In case of Intersect the number of columns and
datatype must be same.
NOTE: MySQL does not support INTERSECT operator.
Example of Intersect
The First table,
ID NAME
1 abhi
2 adam
ID NAME
2 adam
3 Chester
2 adam
MINUS
The Minus operation combines results of two SELECT statements and
return only those in the final result, which belongs to the first set of the
result.
Example of Minus
The First table,
ID NAME
1 abhi
2 adam
The Second table,
ID NAME
2 adam
3 Chester
ID NAME
1 abhi
Creating Views
Database views are created using the CREATE VIEW statement. Views
can be created from a single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege
according to the specific implementation.
The basic CREATE VIEW syntax is as follows −
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a similar
way as you use them in a normal SQL SELECT query.
Example
Rows of data can be inserted into a view. The same rules that apply to
the UPDATE command also apply to the INSERT command.
Here, we cannot insert rows in the CUSTOMERS_VIEW because we have
not included all the NOT NULL columns in this view, otherwise you can
insert rows in a view in a similar way as you insert them in a table.
Rows of data can be deleted from a view. The same rules that apply to
the UPDATE and INSERT commands apply to the DELETE command.
Following is an example to delete a record having AGE = 22.
Obviously, where you have a view, you need a way to drop the view if it
is no longer needed. The syntax is very simple and is given below −
DROP VIEW Viewname;
Following is an example to drop the CUSTOMERS_VIEW from the
CUSTOMERS table.
WHERE ENAME=’SMITH’;
The above query is used to display the senior employee in the EMP Table
i.e., it displays the details of the employee SMITH.
The above query is used to display the employee details who is getting
highest salary in the EMP Table i.e., it displays the details of the
employee KING.
Characteristics of Sub-Query
The above Sub-Query creates PROD table with PRODUCT table structure
and its data (records).
Run-time mismatch
Processing mismatch
Conventional programming languages (COBOL, ADA, FORTRAN, PASCAL,
C, C++ & PL/I) process and data element at a time. Even arrays & files
also process the data element by element. Where as in Visual Studio.net
adopted new technologies such as Object oriented extensions that help
the programmer manipulate the data sets in cohesive manner.
Note:
void main()
int CustId,OrderId;
char SalesPerson[20],Status[6];
printf(‘Enter OrderId:”);
scanf(“%d”,&OrderId);
EXEC SQL
END-EXEC;
printf(“Customer Id:%d\n”,CustId);
printf(“SalesPerson:%s\n”,SalesPerson);
printf(“Status:%s\n”,Status);