adbms file

25
Q1. Write the SQL To copy both the structure and data of Table- 1 into Table-2, Table-1 and Table-2 are given below? Table-1 Store_Information Store_Name Sales Txn_Date Los Angeles 1500 Jan-05- 1999 San Diego 250 Jan-07- 1999 Los Angeles 300 Jan-08- 1999 Boston 700 Jan-08- 1999 Table-2 Geography Region_Name Store_Name East Boston East New York West Los Angeles West San Diego Ans. Using SQL % Wildcard SELECT * From cutomers WHERE 1

Upload: shubham-gupta

Post on 09-Dec-2015

250 views

Category:

Documents


4 download

DESCRIPTION

Have funn in your life

TRANSCRIPT

Q1. Write the SQL To copy both the structure and data of Table-1 into Table-2, Table-1 and Table-2 are given below?

Table-1   Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

Table-2   Geography

Region_Name Store_Name

East Boston

East New York

West Los Angeles

West San Diego

Ans. Using SQL % Wildcard

SELECT * From cutomers WHERE

City LIKE ‘bor%

SELECT * from customers WHERE

City LIKE ‘%es’;

Q2. Write the SQL To copy the structure of Table-1 into Table-2 without any data .

1

Table-1   Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

Table-2   Geography

Region_Name Store_Name

East Boston

East New York

West Los Angeles

West San Diego

Ans. Using SQL _ Wildcard.

SELECT * from customers WHERE

City LIKE ‘_erlin’;

It will get you city which starting with any characters followed by ‘erlin’.

Q3. We want to find out sales by store, and we only want to see stores with sales listed in the report. Write the corresponding SQL query.

2

Table-A1   Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

Table-A2   Geography

Region_Name Store_Name

East Boston

East New York

West Los Angeles

West San Diego

Ans. Select Store_Information.Store _Name, SUM(Sales) as Sales

FROM Store_Information LEFT OUTER JOIN Geography ON Store_Information.Store

_Name = Geography.Store _Name GROUP BY Store_Information.Store _Name;

Q4. What is Wildcard in sql ? Explain different types of wild card with example.

Ans. A wildcard have the following characterstics:

1. A Wildcard character can be used to substitute for any other character in SQL.2. In SQL Wildcard characterstics are used with the SQL LIKE operate.3. SQL wildcards are used to search for data within a table.

Wildcards Description

3

% A substitute for ZEROS or more characters

_ A substitute for single characters

[charlist] Sets and range of chars to match

[^charlist] or [!charlist]

Match only chars NOT specified within the brackets.

Q5. if we want to get the lowest sales from the following table, Write the corresponding SQL query.

Table- Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

Ans. SELECT MIN(sales) from Store_Information;

MIN(Sales)

OUTPUT: 250

Q6. Write the SQL statement is a Cartesian join between the Store_Information and the Geography tables:

Table - Store_Information

4

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

Table - Geography

Region_Name Store_Name

East Boston

East New York

West Los Angeles

West San Diego

Ans.SELECT * From Store_Information , Geography;

Q7. We want to find out sales by store, and we want to see the results for all stores regardless whether there is a sale in the Store_Information table. To do this, we can use the following SQL statement using LEFT OUTER JOIN: Write tha SQL statement.

Table   Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

5

Boston 700 Jan-08-1999

Table   Geography

Region_Name Store_Name

East Boston

East New York

West Los Angeles

West San Diego

Ans. SELECT A1.Store_Name Store, SUM(A2.Sales)

SALES FROM Geography A1

Left OUTER JOIN Store_Information A2

ON A1.Store_Name = A2.Store_Name

GROUP BY A1.Store_Name;

Q8. Let's assume that we have the following table, and we want to create an index on the column Last_Name. Write tha SQL statement

Table Customer

Column Name Data Type

First_Name char(50)

Last_Name char(50)

Address char(50)

City char(50)

Country char(25)

Birth_Date datetime

6

Ans. CREATE INDEX IDX_CUSTOMER_LAST_NAME

ON Customer(Last_Name);

Q9. We want to find out all the dates where there is a sales transaction at a store as well as all the dates where there is a sale over the internet. To do so, we use the following SQL statement:

Table   Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

Table Internet_Sales

Txn_Date Sales

Jan-07-1999 250

Jan-10-1999 535

Jan-11-1999 320

Jan-12-1999 750

Ans. SELECT Txn_Date FROM Store_Information INNER JOIN Internet_Sales ON Store_Information.Txn_Date = Internet_Sales .Txn_Date Sales;

Q10. Assume we have two tables: The first table is User_Address, which maps each user to a ZIP code; the second table is User_Score, which records all the scores of each user. The question is, how to write a SQL query to find the number of users who scored higher than 200 for each ZIP code?

7

Ans. SELECT count(User_Name) FROM User_Address INNER JOIN User_Score ON User_Adress.User_Name = User_Score.User_Name where User_Score > 200 GROUP BY User_Zip;

Q11 . Let's assume that we have the following two tables, and we want to find out all the dates where there are both store sales and internet sales. Write the SQL statement.

Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

Table Internet_Sales

Txn_Date Sales

Jan-07-1999 250

Jan-10-1999 535

Jan-11-1999 320

Jan-12-1999 750

Ans. SELECT TXN_Date FROM Store_information

INTERSECT SELECT

TXN_Date FROM

Internet_Sales;

Q12. Write the SQL query to show the two highest sales amounts in Table Store_Information.

Table   Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

8

San Diego 250 Jan-07-1999

San Francisco 300 Jan-08-1999

Boston 700 Jan-08-1999

Ans. SELECT MAX(Sales) FROM Store_Information LIMIT 0,2;

Q13.Write the following SQL query ?The query will be executed with specific problem and corresponding result.

Q 1. Explain SQL INSTR?

Ans. The INSTR functions search string for substring. The function returns an integer indicating the position of the character in string that is the first character of this occurrence. INSTR calculates strings using characters as defined by the input character set. INSTRB uses bytes instead of characters. INSTRC uses Unicode complete characters. INSTR2 uses UCS2 code points. INSTR4 uses UCS4 code points.

SELECT INSTR('CORPORATE FLOOR','OR', 3, 2)

"Instring" FROM DUAL;

OUTPUT:

Instring

----------

14

Q2. Explain SQL CONCATENATE?

Ans. CONCAT returns char1 concatenated with char2. Both char1 and char2 can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is in the same character set as char1. Its datatype depends on the datatypes of the arguments.

In concatenations of two different datatypes, Oracle Database returns the datatype that results in a lossless conversion. Therefore, if one of the arguments is a LOB, then the returned value is a LOB. If one of the arguments is a national datatype, then the returned value is a national datatype.

Example:

SELECT CONCAT(CONCAT(last_name, '''s job category is '),

9

job_id) "Job"

FROM employees

WHERE employee_id = 152;

OUTPUT:

Job

------------------------------------------------------

Hall's job category is SA_REP

Q3. Explain SQL SUBSTRING?

Ans. The SUBSTR functions return a portion of char, beginning at character position, substring_length characters long. SUBSTR calculates lengths using characters as defined by the input character set.  If position is 0, then it is treated as 1.

1. If position is positive, then Oracle Database counts from the beginning of char to find the first character.

2. If position is negative, then Oracle counts backward from the end of char.3. If substring_length is omitted, then Oracle returns all characters to the end of char.

If substring_length is less than 1, then Oracle returns null.

Examples

The following example returns several specified substrings of "ABCDEFG":

SELECT SUBSTR('ABCDEFG',3,4) "Substring"

FROM DUAL;

OUTPUT:

Substring

---------

CDEF

Q4. Explain SQL RTRIM?

Ans. RTRIM removes from the right end of char all of the characters that appear in set. This function is useful for formatting the output of a query.

10

If you do not specify set, then it defaults to a single blank. If char is a character literal, then you must enclose it in single quotes. RTRIM works similarly toLTRIM.

Examples

SELECT RTRIM('BROWNING: ./=./=./=./=./=.=','/=.') "RTRIM example" FROM DUAL;

OUTPUT:

RTRIM exam

----------

BROWNING:

Q5. Explain SQL LTRIM?

Ans. LTRIM removes from the left end of char all of the characters contained in set. If you do not specify set, it defaults to a single blank. If char is a character literal, then you must enclose it in single quotes. Oracle Database begins scanning char from its first character and removes all characters that appear in setuntil reaching a character not in set and then returns the result.

Examples

The following example trims the redundant first word from a group of product names in the oe.products table:

SELECT product_name, LTRIM(product_name, 'Monitor ') "Short Name"

FROM products

WHERE product_name LIKE 'Monitor%';

OUTPUT:

PRODUCT_NAME Short Name

-------------------- ---------------

Monitor 17/HR 17/HR

Monitor 17/HR/F 17/HR/F

Monitor 17/SD 17/SD

Monitor 19/SD 19/SD

Q6. Explain SQL LENGTH ?

Ans. The LENGTH functions return the length of char. LENGTH calculates length using characters as defined by the input character set. LENGTHB uses bytes instead of characters. LENGTHC uses Unicode complete characters. LENGTH2 uses UCS2 code points. LENGTH4 uses UCS4 code points.

11

Examples

The following example uses the LENGTH function using a single-byte database character set:

SELECT LENGTH('CANDIDE') "Length in characters"

FROM DUAL;

OUTPUT:

Length in characters

--------------------

7

Q7. Explain SQL REPLACE?

Ans. REPLACE returns char with every occurrence of search_string replaced with replacement_string. If replacement_string is omitted or null, then all occurrences of search_string are removed. If search_string is null, then char is returned.

Examples

The following example replaces occurrences of J with BL:

SELECT REPLACE('JACK and JUE','J','BL') "Changes"

FROM DUAL;

OUTPUT:

Changes

--------------

BLACK and BLUE

Q8. Explain SQL TO DATE?

Ans. TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype to a value of DATE datatype. The fmt is a datetime model format specifying the format of char. If you omit fmt, then char must be in the default date format. If fmt is J, for Julian, then char must be an integer.

Examples

The following example converts a character string into a date:

SELECT TO_DATE(

'January 15, 1989, 11:00 A.M.',

'Month dd, YYYY, HH:MI A.M.',

12

'NLS_DATE_LANGUAGE = American')

FROM DUAL;

OUTPUT:

TO_DATE('

---------

15-JAN-89

Q9. Explain SQL UNION?

Ans. UNION returns the results of two queries minus the duplicate rows. The following two tables represent the teams:

INPUT:

SQL> SELECT * FROM FOOTBALL;

OUTPUT:

NAME -------------------- ABLE BRAVO CHARLIE DECON EXITOR FUBAR GOOBER 7 rows selected.

Q10. Explain UNION ALL?

Ans. UNION ALL works just like UNION except it does not eliminate duplicates.

SQL> SELECT NAME FROM SOFTBALL

2 UNION ALL

3 SELECT NAME FROM FOOTBALL;

OUTPUT:

NAME

--------------------

ABLE

BAKER

CHARLIE

DEAN

ANKLE

13

BAKLE

CHARLSE

DEANIAL

ANGEL

HADYEN

LEWIS

STUART

12 rows selected.

Q 11. Explain SQL INTERSECT?

Ans. The SQL INTERSECT clause/operator is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement. This means INTERSECT returns only common rows returned by the two SELECT statements.

Syntax:

SELECT column1 [, column2 ]

FROM table1 [, table2 ]

[WHERE condition]

INTERSECT

SELECT column1 [, column2 ]

FROM table1 [, table2 ]

[WHERE condition]

Q12. Explain SQL DECODE?

Ans. DECODE compares expr to each search value one by one. If expr is equal to a search, then Oracle Database returns the corresponding result. If no match is found, then Oracle returns default. If default is omitted, then Oracle returns null.

The maximum number of components in the DECODE function, including expr, searches, results, and default, is 255.

Examples

This example decodes the value warehouse_id. If warehouse_id is 1, then the function returns 'Southlake'; ifwarehouse_id is 2, then it returns 'San Francisco'; and so forth. If warehouse_id is not 1, 2, 3, or 4, then the function returns 'Non domestic'.

SELECT product_id,

DECODE (warehouse_id, 1, 'Southlake',

14

2, 'San Francisco',

3, 'New Jersey',

4, 'Seattle',

'Non domestic') "Location"

FROM inventories

WHERE product_id < 1775

ORDER BY product_id, "Location";

Q13. Explain SQL SUBQUERY?

Ans. A subquery is a query whose results are passed as the argument for another query. Subqueries enable you to bind several queries together.

Q14. Explain SQL IDENTITY ?

Ans. SQL IDENTITY attribute, used to derive unique values.

Q15. Explain SQL LIMIT?

Ans. By setting a limit, you can prevent queries from consuming excessive computer resources.

For example, joining three large tables without meeting the join-matching conditions could create a huge internal table that would be inefficient to process.

Q16. Explain AUTO INCREMENT?

Ans. The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows:

CREATE TABLE animals (

id MEDIUMINT NOT NULL AUTO_INCREMENT,

name CHAR(30) NOT NULL,

PRIMARY KEY (id)

);

INSERT INTO animals (name) VALUES

('dog'),('cat'),('penguin'),

('lax'),('whale'),('ostrich');

SELECT * FROM animals;

15

Which returns:

ID NAME

1 Cat

2 Camel

3 Penguin

4 Lax

Q17. Explain SQL NEXTVAL ?

Ans. Returns the next value in a sequence. Calling NEXTVAL after creating a sequence initializes the sequence with its default value, incrementing a positive value for ascending sequences, and decrementing a negative value for descending sequences. Thereafter, calling NEXTVAL increments the sequence value. NEXTVAL is used in INSERT, COPY, and SELECT statements to create unique values.

Syntax

[[db-name.]schema.]sequence_name.NEXTVAL

NEXTVAL('[[db-name.]schema.]sequence_name')

Q18. Explain SQL NULL VALUES?

Ans. If a column in a table is optional, we can insert a new record or update an existing record without adding a value to this column. This means that the field will be saved with a NULL value.

SQL Working with NULL Values

Look at the following "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola   Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari   Stavanger

Suppose that the "Address" column in the "Persons" table is optional. This means that if we insert a record with no value for the "Address" column, the "Address" column will be saved with a NULL value.

16

Q19. Explain SQL ISNULL(), IFNULL() ?

Ans. IS NULL() is used to return a Null Value.

SQL> SELECT *

2 FROM PRICE

3 WHERE WHOLESALE IS NULL;

OUTPUT:

ITEM WHOLESALE

-------------- ----------

ORANGES

IS NULL() is used to Check whether a value is a Null Value.

Q20. Explain SQL INLINE VIEW?

Ans. An in-line view is a nested query that is specified in the FROM clause. An in-line view selects data from one or more tables to produce a temporary in-memory table. This virtual table exists only during the query. An in-line view is a SELECT statement within a SELECT statement, which we call a nested statement. Nested SELECT statements sound complex but they are not.

Q21. Explain SQL SEQUENCE?

Ans. Each sequence can be granted access control information, so that they can be referenced, or altered and dropped. The sequence name is used to fetch the value of the sequence, using two special suffixes, called pseudo columns, which either force the return of a new value (NEXTVAL), or return the current value (CURRVAL) for the current session.

SELECT privilege on sequence

USAGE privilege on sequence schema

Examples

The following example creates an ascending sequence called my_seq, starting at 101:

CREATE SEQUENCE my_seq START 101;

The following command generates the first number in the sequence:

SELECT NEXTVAL('my_seq');

OUTPUT:

nextval

---------

101

(1 row)

17

Q22. Explain SQL MEDIAN?

Ans. MEDIAN is an inverses distribution function that assumes a continuous distribution model. It takes a numeric or datetime value and returns the middle value or an interpolated value that would be the middle value once the values are sorted. Nulls are ignored in the calculation.

This function takes as arguments any numeric datatype or any nonnumeric datatype that can be implicitly converted to a numeric datatype. If you specify onlyexpr, then the function returns the same datatype as the numeric datatype of the argument.

Q23. Explain SQL CASE?

Ans. The SQL CASE expression normally is composed of case-operand, when-condition and resultexpression. They must be valid sql-expressions. The syntax format goes like the following:

CASE<case-operand>

WHEN when condition THEN result-expression

<WHEN when-condition THEN result-expression>...

<ELSE result-expression>

END.

Q24. Explain SQL RANK ?

Ans. RANK calculates the rank of a value in a group of values. The return type is NUMBER.

1. Rows with equal values for the ranking criteria receive the same rank. Oracle Database then adds the number of tied rows to the tied rank to calculate the next rank. Therefore, the ranks may not be consecutive numbers. This function is useful for top-N and bottom-N reporting.

2. As an aggregate function, RANK calculates the rank of a hypothetical row identified by the arguments of the function with respect to a given sort specification. The arguments of the function must all evaluate to constant expressions within each aggregate group, because they identify a single row within each group.

3. As an analytic function, RANK computes the rank of each row returned from a query with respect to the other rows returned by the query, based on the values of the value_exprs in the order_by_clause.

Aggregate Example

The following example calculates the rank of a hypothetical employee in the sample table hr.employees with a salary of $15,500 and a commission of 5%:

SELECT RANK(15500, .05) WITHIN GROUP

(ORDER BY salary, commission_pct) "Rank"

FROM employees;

18

OUTPUT:

Rank

----------

105

Q25. Explain SQL MINUS?

Ans. Minus returns the rows from the first query that were not present in the second. For example:

SQL> SELECT * FROM FOOTBALL

2 MINUS

3 SELECT * FROM SOFTBALL;

OUTPUT:

NAME

--------------------

BRAVO

DECON

Q26. Explain SQL EXISTS?

Ans. EXISTS takes a subquery as an argument and returns TRUE if the subquery returns anything and FALSE if the result set is empty. For example:

INPUT/OUTPUT:

SELECT NAME, ORDEREDON

FROM ORDERS

WHERE EXISTS

(SELECT *

FROM ORDERS

WHERE NAME ='TRUE WHEEL')

NAME ORDERED ON

========== ===========

19

TRUE WHEEL 15-MAY-1996

TRUE WHEEL 19-MAY-1996

TRUE WHEEL 2-SEP-1996

TRUE WHEEL 30-JUN-1996

BIKE SPEC 30-JUN-1996

20