Tuesday, 5 March 2013

Question

(b) What is Data Constraint? List out all type of constraint and Explain Foreign
Key in detail.
Answer:

SQL Constraints:

Constraints are the rules enforced on data columns on table. These 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 database.
Constraint




Input output constraints
Business rule constraints


There are two types of constraints:
1) Input output constraints.
    • Primary key constraint
    • Foreign key constraints
    • Unique key constraints
2) Business rule constraints.
    • Not null constraints
    • Check constraints
    • Default constraints

Constraints could be column level or table level. Column level constraints are applied only to one column where as table level constraints are applied to the whole table.
SQL Foreign key or Referential Integrity :
This constraint identifies any column referencing the PRIMARY KEY in another table. It establishes a relationship between two columns in the same table or between different tables. For a column to be defined as a Foreign Key, it should be a defined as a Primary Key in the table which it is referring. One or more columns can be defined as Foreign key.
Syntax :
[CONSTRAINT constraint_name] REFERENCES Referenced_Table_name(column_name)
Syntax to define a Foreign key at table level:
[CONSTRAINT constraint_name] FOREIGN KEY(column_name) REFERENCES referenced_table_name(column_name);
Example:
Lets use the "product" table and "order_items".
Foreign Key at column level:
CREATE TABLE product
( product_id number(5) CONSTRAINT pd_id_pk PRIMARY KEY,
product_name char(20),
supplier_name char(20),
unit_price number(10)
);
Foreign Key at table level:
CREATE TABLE order_items
( order_id number(5) ,
product_id number(5),
product_name char(20),
supplier_name char(20),
unit_price number(10)
CONSTRAINT od_id_pk PRIMARY KEY(order_id),
CONSTRAINT pd_id_fk FOREIGN KEY(product_id) REFERENCES product(product_id)
);

(c) What is SQL *Loader? Explain in Brief.
Answer:
SQL LOADER utility is used to load data from other data source into Oracle. For example, if you have a table in FOXPRO, ACCESS or SYBASE or any other third party database, you can use SQL Loader to load the data into Oracle Tables. SQL Loader will only read the data from Flat files. So If you want to load the data from FoxPro or any other database, you have to first convert that data into Delimited Format flat file or Fixed length format flat file, and then use SQL loader to load the data into Oracle.
Following is procedure to load the data from Third Party Database into Oracle using SQL Loader.
  1. Convert the Data into Flat file using third party database command.
  2. Create the Table Structure in Oracle Database using appropriate data types
  3. Write a Control File, describing how to interpret the flat file and options to load the data.
  4. Execute SQL Loader utility specifying the control file in the command line argument
SQL*Loader (sqlldr ) is the utility to use for high performance data loads.  The data can be loaded from any text file and inserted into the database.

Figure depicts the SQL*Loader architecture.  SQL*Loader reads a data file and a description of the data which is defined in the control file.  Using this information and any additional specified parameters (either on the command line or in the PARFILE), SQL*Loader loads the data into the database. 

During processing, SQL*Loader writes messages to the log file, bad rows to the bad file, and discarded rows to the discard file.

 Figure SQL*Loader Architecture 
The Data Control File
From SQL*Loader's perspective, the data in the data file is organized as records. A particular datafile can be in fixed record format, variable record format, or stream record format.
The Control File
The SQL*Loader control file contains information that describes how the data will be loaded.  It contains the table name, column datatypes, field delimiters, etc.  It simply provides the guts for all SQL*Loader processing. 

Manually creating control files is an error-prone process.  The following SQL script (controlfile.sql) can be used to generate an accurate control file for a given table.  The script accepts a table name and a date format (to be used for date columns), and generates a valid control file to use with SQL*Loader for that table.   
The Log File
The log file contains information about the SQL*loader execution.   It should be viewed after each SQL*Loader job is complete.  Especially interesting is the summary information at the bottom of the log, including CPU time and elapsed time.  The data below is a sample of the contents of the log file.

Discard file

The discard file contains records that didn't meet any of the record selection criteria.

The Bad File

The bad file contains records rejected, either by SQL*Loader or by Oracle.


parameter file
Tells SQL*Loader to read command-line parameter values from a text file. This text file is referred to as a parameter fil. PARFILE (parameter file).For example, PARFILE specifies the name of a file that contains commonly used command-line parameters.
(d) Explain Date Conversion function.
Answer:

TO_DATE: Converts a characters field to a date field.

SYNTAX:
TO_DATE(char [,fmt])


EXAMPLE:
INSERT INTO CUST_MSTR(CUST_NO, FNAME, MNAME, LNAME, DOB_INC)
VALUES(‘C1’,’Ivan’,Nelson’,’bayross’,
TO_DATE(’25-JUN-1952 10:55 A.M.’,’DD-MON-YY HH:MI A.M.’));

OUTPUT:
1 rows created.

1) ADD_MONTHS: returns date after adding the number of months specified
in the function.
SYNTAX:
ADD_MONTHS(d,n)
EXAMPLE:
SELECT ADD_MONTHS(SYSDATE,4) “Add Months” FROM DUAL;
OUTPUT:
Add Months
--------------------
01-NOV-04

2) LAST_DAY: returns the last date of the month specified with the function.
SYNTAX:
LAST_DAY(d)
EXAMPLE:
SELECT SYSDATE, LAST_DAY(SYSDATE) “LastDay” FROM DUAL;
OUTPUT:
SYSDATE LastDay
---------------------------------
01-JUL-04 31-JUL-04

3) MONTH_BETWEEN: Returns number of months between d1 and d2.
SYNTAX:
MONTHS_BETWEEN(d1, d2)
EXAMPLE:
SELECT MONTHS_BETWEEN(’02-FEB-92’,’02-JAN-92’) “Months” FROM DUAL;
OUTPUT:
Months
--------------
1

4) NEXT_DAY: Returns the date of the first weekday named bby char that is
after the date named by date char must be a ady of the week.
SYNTAX:
NEXT_DATE(date, char)
EXAMPLE:
SELECT NEXT_DAY(’06-JULY-02’,’Saturday’) “NEXT DAY” FROM DUAL;
OUTPUT:
NEXT DAY
-------------------
13-JULY-02

5) ROUND: Returns the date rounded to a specified unit of measure. If the
second parameter is omitted, the ROOUND function will round the date to
the nearest day.
SYNTAX:
ROUND(date, char)
EXAMPLE:
SELECT ROUND(TO_DATE(’01-JUL-04’0,’YYYY’) “Year” FROM DUAL;
OUTPUT:
Year
-------------------
01-JAN-05
6) NEW_TIME: Returns the date after converting if from time zone1 to a date
in time zone2.
SYNTAX:
NEW_TIME(date, zone1, zone2)
EXAMPLE:
SELECT NEW_TIME(TO_DATE(’2004/07/01 01:45’,’yyyy/mm/dd
HH24:MI’),’AST’,’MST’) “MST” FROM DUAL;
OUTPUT:
MST
-------------------
30-JUN-04
(e) How to delete duplicate records from the table. Explain with example.
Answer:

Delete Duplicate Records using SQL

By duplicate record means that every field in one record is identical to every field in a different record, i.e. a duplicate is where there is no way of telling two or more records apart. If you just need to remove records which are similar (i.e. one or more fields are identical but there are one or more fields which are different) then instead refer to how to delete similar records.
To check that you have duplicate records in your table do the following:
select count(*) from MyTable
and
select distinct * from MyTable
unfortunately SQL does not permit a select count(distinct). You have duplicate records if the number of records returned by the second query is less than the number of records returned by the first.
Unfortunately there is no way in SQL to delete one of these duplicates without deleting all of them. They are identical after all, so there is no SQL query that you could put together which could distinguish between them.
What you can do is to copy all the distinct records into a new table:
select distinct * from MyTable
This query will create a new table (NewTable in my example) containing all the records in the original table but without any records being duplicated. It will therefore preserve a single copy of those records which were duplicated.
Because this query creates (and populates) a new table, it will fail if the table already exists.

Delete Similar Records

To delete similar records, i.e. where the records are not the same but one field is the same and only one copy needs to be preserved, try the following SQL:
delete T1 from MyTable T1, MyTable T2
where T1.dupField = T2.dupField
and T1.uniqueField > T2.uniqueField
This will delete all records from the table MyTable which have the same value for the field dupField, leaving that record which has the lowest value in uniqueField.
The above SQL works on SQL-Server and MySQL but not in MS-Access. For MS-Access try:
delete from MyTable
where
uniqueField not in
(select min(uniqueField) from MyTable T2
where T2.
dupField=MyTable.dupField)
This syntax also works in SQLServer (but not in MySQL) but may not be as efficient for large tables.
Using Index to eliminate duplicate row
It's easy to introduce duplicate rows of data into Oracle tables by running a data load twice without the primary key or unique indexes created or enabled.

Here's how you remove the duplicate rows before the primary key or unique indexes can be created:
DELETE FROM our_table
WHERE rowid not in (SELECT MIN(rowid)
FROM our_table
GROUP BY column1, column2, column3... ;
Here column1, column2, column3 constitute the identifying key for each record.
Be sure to replace our_table with the table name from which you want to remove the duplicate rows. The GROUP BY is used on the columns that make the primary key for the table. This script deletes each row in the group after the first row.
(f) What is DBA? Discuss the basic duties of DBA.
Answer:
“A database administrator (DBA) is a person responsible for the design, implementation, maintenance and repair of an organization's database.” Or “The DBA is a person having central control over data and processing accessing that data.”

They are also known by the titles Database Coordinator or Database Programmer, and are closely related to the Database Analyst, Database Modeler.

The duties of a database administrator vary depending on job description, corporate and Information Technology (IT) policies and the technical features and capabilities of the DBMS being administered.
Duties of DBA

  1. Installation of new software: It is the job of the DBA to install new versions of DBMS software, application software, and other software related to DBMS administration. It is important that the DBA or other IS staff members test new software before it is moved into a production environment.
  2. Security administration: One of the main duties of the DBA is to monitor and administer DBMS security. This involves adding and removing users, administering quotas, auditing, and checking for security problems.
  3. Data analysis: The DBA analyzes data stored in the database and makes recommendations relating to performance and efficiency of that data storage.
  4. Database design: The DBA can be involved at the preliminary database-design stages, eliminating many problems that might occur.
  5. Configuration of hardware and software with the system Administrator: In many cases the system software can only be accessed by the system administrator. In this case, the DBA works closely with the system administrator to perform software installations, and to configure hardware and software so that it functions optimally with the DBMS.
  6. Data modeling and optimization: By modeling the data, it is possible to optimize the system layouts to take the most advantage of the I/O subsystem.
  7. Recoverability is one of the most important and vital duty of a Database Administrator. Any type of error such as, data entry error, hardware failure, software failure, bugs, virus etc. can result in corrupting database.
  8. Planning and implementing a sound backup and recovery strategy.
  9. DBA is responsible for create a separate tablespace within the database to hold user objects.
  10. DBA is also responsible for authorization of access data and integrity constraint specification.
Create table: (1) Pro_mst(Pno,Pname,price,SupId)(2) Supplier(SupId,Sname,Scity)
(3) Sales(SalesId,Pno,Salesdate,amount)
Constraint: (1) Add foreign key SupId to Pro_mst
(2) Add constraint for checking the amount greater than zero.
(3) Add Primary Key constraint for SupId
Solve: (1) Display the name of the supplier who supply maximum products
(2) Display the list of maximum sale product
Answer:
CREATE TABLE Supplier
(
SupId NUMBER(6) PRIMARY KEY,
Sname VARCHAR(15),
Scity VARCHAR(10)
);
CREATE TABLE Pro_mst
(
Pno NUMBER(6) PRIMARY KEY,
Pname VARCHAR(15),
Price NUMBER(8,2),
SupId NUMBER(6) REFERENCES Supplier
);
CREATE TABLE Sales
(
SalesId NUMBER(6) PRIMARY KEY,
Pno NUMBER(6) REFERENCES Pro_mst,
Salesdate DATE,
Amount NUMBER(8,2),
CHECK (Amount > 0)
);
Solution of Query:
    1. Display the name of the supplier who supply maximum products
Answer:
SELECT Supplier.Sname,max(Sales.Pno) From Supplier,Sales,Pro_mst
WHERE Sales.SupId=Supplier.SupId AND Pro_mst.Pno=Sales.Pno
GROUP BY Pno;

    1. Display the list of maximum sale product
Answer:
SELECT SalesId,sum(Pno) From Sales,Pro_mst
WHERE Pro_mst.Pno=Sales.Pno
GROUP BY Pno;


No comments:

Post a Comment