Oracle Database 11g – SQL Exams Syllabus ”; Previous Next (Oracle Certified Oracle Database 11g Administrator) Oracle Database 11g: SQL Fundamentals certification exams has a defined Syllabus to check your expertise. As per Oracle Official website, following is the list of chapters and covered topic to be examined in the certification exams. Retrieving Data Using the SQL SELECT Statement List the capabilities of SQL SELECT statements Execute a basic SELECT statement Restricting and Sorting Data Limit the rows that are retrieved by a query Sort the rows that are retrieved by a query Use ampersand substitution to restrict and sort output at runtime Using Single-Row Functions to Customize Output Describe various types of functions available in SQL Use character, number, and date functions in SELECT statements Using Conversion Functions and Conditional Expressions Describe various types of functions available in SQL Use character, number, and date functions in SELECT statements Reporting Aggregated Data Using the Group Functions Identify the available group functions Describe the use of group functions Group data by using the GROUP BY clause Include or exclude grouped rows by using the HAVING clause Displaying Data from Multiple Tables Write SELECT statements to access data from more than one table using equijoins and nonequijoins Join a table to itself by using a self-join View data that generally does not meet a join condition by using outer joins Generate a Cartesian product of all rows from two or more tables Using Subqueries to Solve Queries Define subqueries Describe the types of problems that the subqueries can solve List the types of subqueries Write single-row and multiple-row subqueries Using the Set Operators Describe set operators Use a set operator to combine multiple queries into a single query Control the order of rows returned Manipulating Data Describe each data manipulation language (DML) statement Insert rows into a table Update rows in a table Delete rows from a table Control transactions Using DDL Statements to Create and Manage Tables Categorize the main database objects Review the table structure List the data types that are available for columns Create a simple table Explain how constraints are created at the time of table creation Describe how schema objects work Creating Other Schema Objects Create simple and complex views Retrieve data from views Create, maintain, and use sequences Create and maintain indexes Create private and public synonyms Print Page Previous Next Advertisements ”;
Category: sql Certificate
SQL – Conversion Functions
SQL – Conversion Functions Questions ”; Previous Next 1. What will be the outcome of the following query? SELECT ROUND(144.23,-1) FROM dual; 140 144 150 100 Answer: A. The ROUND function will round off the value 144.23 according to the specified precision -1 and returns 140. Examine the structure of the EMPLOYEES table as given and answer the questions 2 and 3 that follow. SQL> DESC employees Name Null? Type ———————– ——– —————- EMPLOYEE_ID NOT NULL NUMBER(6) FIRST_NAME VARCHAR2(20) LAST_NAME NOT NULL VARCHAR2(25) EMAIL NOT NULL VARCHAR2(25) PHONE_NUMBER VARCHAR2(20) HIRE_DATE NOT NULL DATE JOB_ID NOT NULL VARCHAR2(10) SALARY NUMBER(8,2) COMMISSION_PCT NUMBER(2,2) MANAGER_ID NUMBER(6) DEPARTMENT_ID NUMBER(4) 2. You are currently located in New Jersey and have connected to a remote database in San Diego. You issue the following command. SELECT ROUND (sysdate-hire_date,0) FROM employees WHERE (sysdate-hire_date)/180 = 2; What is the outcome of this query? An error because the ROUND function cannot be used with Date arguments. An error because the WHERE condition expression is invalid. Number of days since the employee was hired based on the current San Diego date and time. Number of days since the employee was hired based on the current New Jersey date and time. Answer: C. The SYSDATE function will take the current time of the database which it is connecting to remotely. You must perform basic arithmetic operation to adjust the time zone. 3. You need to display the names of the employees who have the letter ”s” in their first name and the letter ”t” at the second position in their last name. Which query would give the required output? SELECT first_name, last_name FROM employees WHERE INSTR(first_name,”s”) 0 AND SUBSTR(last_name,2,1) = ”t”; SELECT first_name, last_name FROM employees WHERE INSTR(first_name,”s”) ”” AND SUBSTR(last_name,2,1) = ”t”; SELECT first_name, last_name FROM employees WHERE INSTR(first_name,”e”) IS NOT NULL AND SUBSTR(last_name,2,1) = ”t”; SELECT first_name, last_name FROM employees WHERE INSTR(first_name,”e”) 0 AND SUBSTR(last_name,LENGTH(first_name),1) = ”t”; Answer: A. The INSTR function returns the position of a given character in the required string. The SUBSTR function returns set of characters from the string from a given starting and end position. 4. Which of the following statements is true regarding the COUNT function? COUNT (*) counts duplicate values and NULL values in columns of any data type. COUNT function cannot work with DATE datatypes. COUNT (DISTINCT job_id) returns the number of rows excluding rows containing duplicates and NULL values in the job_id column. A SELECT statement using the COUNT function with a DISTINCT keyword cannot have a WHERE clause. Answer: A. The COUNT(*) function returns the number of rows in a table that satisfy the criteria of the SELECT statement, including duplicate rows and rows containing null values in any of the columns. If a WHERE clause is included in the SELECT statement, COUNT(*) returns the number of rows that satisfy the condition in the WHERE clause. In contrast, COUNT(expr) returns the number of non-null values that are in the column identified by expr. COUNT(DISTINCT expr) returns the number of unique, non-null values that are in the column identified by expr. 5. Which of the following commands is used to count the number of rows and non-NULL values in Oracle database? NOT NULL INSTR SUBSTR COUNT Answer: D. The COUNT (ALL column_name) is used to count number of rows excluding NULLs. Similarly, COUNT(*) is used to count the column values including NULLs. 6. What will be the outcome of the query given below? SELECT 100+NULL+999 FROM dual; 100 999 NULL 1099 Answer: C. Any arithmetic operation with NULL results in a NULL. 7. Which of the following statements are true regarding the single row functions? They accept only a single argument. They can be nested only to two levels. Arguments can only be column values or constants. They can return a data type value different from the one that is referenced. Answer: D. Single row functions can take more than one argument and the return type can be different from the data type of the inputs. 8. Which of the below queries will format a value 1680 as $16,80.00? SELECT TO_CHAR(1680.00,”$99G99D99”) FROM dual; SELECT TO_CHAR(1680.00,”$9,999V99”) FROM dual; SELECT TO_CHAR(1680.00,”$9,999D99”) FROM dual; SELECT TO_CHAR(1680.00,”$99G999D99”) FROM dual; Answer: A, D. The format model $99G999D99 formats given number into numeric, group separator, and decimals. Other format elements can be leading zeroes, decimal position, comma position, local currency, scientific notation, and sign. 9. Determine the output of the below query. SELECT RPAD(ROUND(”78945.45”),10,”*”) FROM dual; 78945***** **78945.45 The function RPAD cannot be nested with other functions 78945.45**** Answer: A. The LPAD(string, num, char) and RPAD(string, num, char) functions add a character to the left or right of a given string until it reaches the specified length (num) after padding. The ROUND function rounds the value 78945.45 to 78945 and then pads it with ”*” until length of 10 is reached. 10. Which of the following commands allows you to substitute a value whenever a NULL or non-NULL value is encountered in an SQL query? NVL NVLIF NVL2 LNNVL Answer: C. The NVL2 function takes minimum three arguments. The NVL2 function checks the first expression. If it is not null, the NVL2 function returns the second argument. If the first argument is null, the third argument is returned. 11. Which of the following type of single-row functions cannot be incorporated in Oracle DB? Character Numeric Conversion None of the above Answer: D. The types of single-row functions like character, numeric, date, conversion and miscellaneous as well as programmer-written can be incorporated in Oracle DB. 12. Out of the below clauses, where can the single-row functions be used? SELECT WHERE ORDER BY All of the above Answer: D. Single row function can be used in SELECT statement, WHERE clause and ORDER BY clause. 13. What is true regarding the NVL function in Oracle DB? The syntax of NVL is NVL (exp1, exp2) where exp1 and exp2 are expressions. NVL (exp1, exp2) will return the value of exp2 if the expression exp1 is NULL. NVL
SQL – Using the Set Operators ”; Previous Next Set operators are used to join the results of two (or more) SELECT statements.The SET operators available in Oracle 11g are UNION,UNION ALL,INTERSECT,and MINUS. The UNION set operator returns the combined results of the two SELECT statements.Essentially,it removes duplicates from the results i.e. only one row will be listed for each duplicated result.To counter this behavior,use the UNION ALL set operator which retains the duplicates in the final result.INTERSECT lists only records that are common to both the SELECT queries; the MINUS set operator removes the second query”s results from the output if they are also found in the first query”s results. INTERSECT and MINUS set operations produce unduplicated results. All the SET operators share the same degree of precedence among them.Instead,during query execution, Oracle starts evaluation from left to right or from top to bottom.If explicitly parentheses are used, then the order may differ as parentheses would be given priority over dangling operators. Points to remember – Same number of columns must be selected by all participating SELECT statements.Column names used in the display are taken from the first query. Data types of the column list must be compatible/implicitly convertible by oracle. Oracle will not perform implicit type conversion if corresponding columns in the component queries belong to different data type groups.For example, if a column in the first component query is of data type DATE, and the corresponding column in the second component query is of data type CHAR,Oracle will not perform implicit conversion, but raise ORA-01790 error. Positional ordering must be used to sort the result set. Individual result set ordering is not allowed with Set operators. ORDER BY can appear once at the end of the query. For example, UNION and INTERSECT operators are commutative, i.e. the order of queries is not important; it doesn”t change the final result. Performance wise, UNION ALL shows better performance as compared to UNION because resources are not wasted in filtering duplicates and sorting the result set. Set operators can be the part of sub queries. Set operators can”t be used in SELECT statements containing TABLE collection expressions. The LONG, BLOB, CLOB, BFILE, VARRAY,or nested table are not permitted for use in Set operators.For update clause is not allowed with the set operators. UNION When multiple SELECT queries are joined using UNION operator, Oracle displays the combined result from all the compounded SELECT queries,after removing all duplicates and in sorted order (ascending by default), without ignoring the NULL values. Consider the below five queries joined using UNION operator.The final combined result set contains value from all the SQLs. Note the duplication removal and sorting of data. SELECT 1 NUM FROM DUAL UNION SELECT 5 FROM DUAL UNION SELECT 3 FROM DUAL UNION SELECT 6 FROM DUAL UNION SELECT 3 FROM DUAL; NUM ——- 1 3 5 6 To be noted, the columns selected in the SELECT queries must be of compatible data type. Oracle throws an error message when the rule is violated. SELECT TO_DATE(”12-OCT-03”) FROM DUAL UNION SELECT ”13-OCT-03” FROM DUAL; SELECT TO_DATE(”12-OCT-03”) FROM DUAL * ERROR at line 1: ORA-01790: expression must have same datatype as corresponding expression UNION ALL UNION and UNION ALL are similar in their functioning with a slight difference. But UNION ALL gives the result set without removing duplication and sorting the data. For example,in above query UNION is replaced by UNION ALL to see the effect. Consider the query demonstrated in UNION section. Note the difference in the output which is generated without sorting and deduplication. SELECT 1 NUM FROM DUAL UNION ALL SELECT 5 FROM DUAL UNION ALL SELECT 3 FROM DUAL UNION ALL SELECT 6 FROM DUAL UNION ALL SELECT 3 FROM DUAL; NUM ——- 1 5 3 6 3 INTERSECT Using INTERSECT operator, Oracle displays the common rows from both the SELECT statements, with no duplicates and data arranged in sorted order (ascending by default). For example,the below SELECT query retrieves the salary which are common in department 10 and 20.As per ISO SQL Standards, INTERSECT is above others in precedence of evaluation of set operators but this is not still incorporated by Oracle. SELECT SALARY FROM employees WHERE DEPARTMENT_ID = 10 INTRESECT SELECT SALARY FROM employees WHERE DEPARTMENT_ID = 20 SALARY ——— 1500 1200 2000 MINUS Minus operator displays the rows which are present in the first query but absent in the second query, with no duplicates and data arranged in ascending order by default. SELECT JOB_ID FROM employees WHERE DEPARTMENT_ID = 10 MINUS SELECT JOB_ID FROM employees WHERE DEPARTMENT_ID = 20; JOB_ID ————- HR FIN ADMIN Matching the SELECT statement There may be the scenarios where the compound SELECT statements may have different count and data type of selected columns. Therefore, to match the column list explicitly, NULL columns are inserted at the missing positions so as match the count and data type of selected columns in each SELECT statement. For number columns, zero can also be substituted to match the type of the columns selected in the query. In the below query, the data type of employee name (varchar2) and location id (number) do not match. Therefore, execution of the below query would raise error due to compatibility issue. SELECT DEPARTMENT_ID “Dept”, first_name “Employee” FROM employees UNION SELECT DEPARTMENT_ID, LOCATION_ID FROM departments; ERROR at line 1: ORA-01790: expression must have same datatype as corresponding expression Explicitly, columns can be matched by substituting NULL for location id and Employee name. SELECT DEPARTMENT_ID “Dept”, first_name “Employee”, NULL “Location” FROM employees UNION SELECT DEPARTMENT_ID, NULL “Employee”, LOCATION_ID FROM departments; Using ORDER BY clause in SET operations The ORDER BY clause can appear only once at the end of the query containing compound SELECT statements.It implies that individual SELECT statements cannot have ORDER BY clause. Additionally, the sorting can be based on the columns which appear in the first SELECT query only. For this reason, it is recommended to sort the compound query using column positions. The compund
SQL Certificate – Useful Resources ”; Previous Next The following resources contain additional information on SQL Certificate. Please use them to get more in-depth knowledge on this topic. Useful Links on SQL Certificate ANSI SQL − Database Language SQL (Proposed revised text of DIS 9075) July 1992 (Second Informal Review Draft). Structured Query Language (SQL): − DB2 resource for SQL users. Oracle SQL Developer − Oracle SQL Developer is a free and fully supported graphical tool for database development. SQL at Wikipedia − A small article on SQL, worth to go through it. MySQL Official Website − Here you can download the latest MySQL release, get the MySQL news update. The mailing list is also a great resources for anyone who want to build dynamic websites using MySQL. MySQL and PERL − Its a tutorial from Tutorials Point which explains you how to use MySQL along with PERL and DBI module. Here you will learn all the required MySQL operations alongwith examples. Useful Books on SQL Certificate To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
SQL – Using the Set Operators Questions ”; Previous Next 1.Which SET operator does the following figure indicate? UNION UNION ALL INTERSECT MINUS Answer: A. Set operators are used to combine the results of two (or more) SELECT statements.Valid set operators in Oracle 11g are UNION, UNION ALL, INTERSECT, and MINUS. When used with two SELECT statements, the UNION set operator returns the results of both queries.However,if there are any duplicates, they are removed, and the duplicated record is listed only once.To include duplicates in the results,use the UNION ALL set operator.INTERSECT lists only records that are returned by both queries; the MINUS set operator removes the second query”s results from the output if they are also found in the first query”s results. INTERSECT and MINUS set operations produce unduplicated results. 2.Which SET operator does the following figure indicate? UNION UNION ALL INTERSECT MINUS Answer: B. UNION ALL Returns the combined rows from two queries without sorting or removing duplicates. sql_certificate 3.Which SET operator does the following figure indicate? UNION UNION ALL INTERSECT MINUS Answer: C. INTERSECT Returns only the rows that occur in both queries” result sets, sorting them and removing duplicates. 4.Which SET operator does the following figure indicate? UNION UNION ALL INTERSECT MINUS Answer: D. MINUS Returns only the rows in the first result set that do not appear in the second result set, sorting them and removing duplicates. 5.What is true about SET operators? They change values of rows They combine the results of only two component queries into one result They combine the results of 10 component queries into two result sets. They combine the results of two or more component queries into one result Answer: D. Set operators are used to combine the results of two (or more) SELECT statements. Valid set operators in Oracle 11g are UNION, UNION ALL, INTERSECT, and MINUS. 6.What are the queries containing SET operators called? Sub-queries Co-related sub-queries GROUP BY queries Compound queries Answer: D. 7.What is true about the UNION operator? It returns rows from the combined queries along with NULL values It returns rows for the combined queries after eliminating duplicates It returns rows for the combined queries along with duplicate values It returns rows for the combined queries ignoring the NULL values Answer: B. UNION Returns the combined rows from two queries, sorting them and removing duplicates. 8.What is true about the UNION ALL operator? It returns rows from the combined queries along with NULL values It returns rows for the combined queries after eliminating duplicates It returns rows for the combined queries along with duplicate values It returns rows for the combined queries ignoring the NULL values Answer: C. UNION ALL Returns the combined rows from two queries without sorting or removing duplicates. 9.What is true about the INTERSECT operator? It returns rows from the combined queries along with NULL values It returns rows for the combined queries after eliminating duplicates It returns the common rows from the combined queries None of the above Answer: C. INTERSECT Returns only the rows that occur in both queries” result sets, sorting them and removing duplicates. 10.What is true about the MINUS operator? It returns rows from the first query but not from the second query It returns rows for the second query but not from the first query It returns duplicate rows for the combined queries It returns rows for the combined queries ignoring the NULL values Answer: A. MINUS Returns only the rows in the first result set that do not appear in the second result set, sorting them and removing duplicates. 11.What is the precedence of the set operators UNION, UNION ALL, INTERSECT and MINUS? UNION, UNION ALL, INTERSECT and MINUS MINUS, UNION, UNION ALL and INTERSECT INTERSECT, MINUS, UNION ALL, UNION Equal precedence Answer: D. SET operators have an equal precedence. 12.What is the order of evaluation of set operators? Left to Right Right to Left Random Evaluation Top to Bottom Answer: A, D. Assuming that there are no grouping of queries using parentheses, the SET operators will be evaluated from top to bottom and left to right horizontally. 13.In which of the following cases, parenthesis should be specified? When INTERSECT is used with other set operators When UNION is used with UNION ALL When MINUS is used for the queries None of the above Answer: A. Using parenthesis will explicitly change the order of evaluation when INTERSECT is used with other operators. 14.What is true about the SELECT clause when SET operators are used? There is no restriction on the columns being selected The columns, expressions used in the SELECT clause must match in number in the combined queries The columns, expressions used in the SELECT clause must be N in the first query and N-1 in the subsequent combined queries Both B and C Answer: B. All the combined should have the same no. of columns when using SET operators. The corresponding columns in the queries that make up a compound query must be of the same data type group. 15.What is true about the SET operators? The SELECT clause should have the same number of columns, data types can be different The SET operators can be used only for combining two queries The data type of each column in the 2nd query must match the data type of its corresponding column in the first query. None of the above Answer: C. All the combined should have the same no. of columns when using SET operators. The corresponding columns in the queries that make up a compound query must be of the same data type group. 16.Where can the ORDER BY clause be used in case when SET operators are used? In each of the queries being combined In the first query only At the very end of the compound query None of the above Answer: C. If the ORDER BY clause is used in between any of the queries joined using SET operators, it will throw
SQL – Restricting and Sorting Data ”; Previous Next The essential capabilities of SELECT statement are Selection, Projection and Joining. Displaying specific columns from a table is known as a project operation. We will now focus on displaying specific rows of output. This is known as a select operation. Specific rows can be selected by adding a WHERE clause to a SELECT query. As a matter of fact, the WHERE clause appears just after the FROM clause in SELECT query hierarchy. The sequence has to be maintained in all scenarios. If violated, Oracle raises an exception. Syntax: SELECT *|{[DISTINCT] column| expression [alias],..} FROM table [WHERE condition(s)] In the syntax, WHERE clause is the keyword [condition] contains column names, expressions, constants, literals and a comparison operator. Suppose that your manager is working on the quarterly budget for your organization. As part of this activity, it is necessary to produce a listing of each employee”s essential details, but only for employees that are paid at least $25,000 annually. The SQL query below accomplishes this task. Note the use of the WHERE clause shown in bold text. SELECT Employee_ID, Last_Name, First_Name, Salary FROM employees WHERE Salary >= 25000; EMPLOYEE_ID LAST_NAME FIRST_NAME SALARY ———- ————— ————— ———– 88303 Jones Quincey $30,550.00 88404 Barlow William $27,500.00 88505 Smith Susan $32,500.00 3 rows selected Points to be noted – A SELECT clause can contain only one WHERE clause. However, multiple filter conditions can be appended to WHERE clause using AND or OR operator. The columns, literals or expressions in a predicate clause must be of similar or interconvertible data types. Column alias cannot be used in the WHERE clause. Character literals must be enclosed within single quotation marks and are case sensitive. Date literals must be enclosed within single quotation marks and are format sensitive. Default format is DD-MON-RR. Comparison Operators Comparison operators are used in predicates to compare one term or operand with another term. SQL offers comprehensive set of equality, inequality and miscellaneous operators. They can be used depending on the data and filter condition logic in the SELECT query. When you use comparison operators in a WHERE clause, the arguments (objects or values you are comparing) on both sides of the operator must be either a column name, or a specific value. If a specific value is used, then the value must be either a numeric value or a literal string. If the value is a character string or date, you must enter the value within single quotation marks (” ”). Oracle has nine comparison operators to be used in equality or inequality conditions. Operator Meaning = equal to < less than > greater than >= greater than or equal to <= less than or equal to != not equal to <> not equal to Other Oracle operators are BETWEEN..AND, IN, LIKE, and IS NULL. The BETWEEN Operator The BETWEEN operator can be used to compare a column value within a definite range. The specified range must have a lower and upper limit where both are inclusive during comparison. Its use is similar to composite inequality operator (<= and >=). It can be used with numeric, character and date type values. For example, the WHERE condition SALARY BETWEEN 1500 AND 2500 in a SELECT query will list those employees whose salary is between 1500 and 2500. The IN Operator The IN operator is used to test a column value in a given set of value. If the column can be equated to any of the values from the given set, the condition is validated. The condition defined using the IN operator is also known as the membership condition. For example, the WHERE condition SALARY IN (1500, 3000, 2500) in a SELECT query will restrict the rows where salary is either of 1500, 3000 or 2500. The LIKE Operator The LIKE operator is used for pattern matching and wildcard searches in a SELECT query. If a portion of the column value is unknown, wildcard can be used to substitute the unknown part. It uses wildcard operators to build up the search string, thus search is known as Wildcard search. These two operators are Percentile (”%”) and Underscore (”_”). Underscore (”_”) substitutes a single character while percentile (”%”) replaces more than one characters. They can be used in combination as well. For example, the below SELECT query lists the first names of those employees whose last name starts with ”SA”. SELECT first_name FROM employees WHERE last_name LIKE ”SA%”; IS (NOT) NULL Conditions To be noted, NULL values cannot be tested using equality operator. It is because NULL values are unknown and unassigned while equality operator tests for a definite value. The IS NULL operator serves as equality operator to check NULL values of a column. For example, the WHERE condition COMMISSION_PCT IS NULL in a SELECT query will list employees who don”t have commission percentage. Logical Operators Multiple filter conditions can be added to the WHERE clause predicate. More than one condition can be combined together using logical operators AND, OR and NOT. AND: joins two or more conditions, and returns results only when all of the conditions are true. OR: joins two or more conditions, and it returns results when any of the conditions are true. NOT: negates the expression that follows it. The AND operator links two or more conditions in a WHERE clause and returns TRUE only if all the conditions are true. Suppose that a manager needs a list of female employees. Further, the list should only include employees with last names that begin with the letter “E” or that come later in the alphabet. Additionally, the result table should be sorted by employee last name. There are two simple conditions to be met. The WHERE clause may be written as: WHERE Gender = ”F” AND last_name > ”E”. SELECT last_name “Last Name”, first_name “First Name”, Gender “Gender” FROM employees WHERE Gender = ”F” AND last_name > ”E” ORDER BY last_name; The OR operator links more than
SQL – Using Conditional Expressions ”; Previous Next General Functions General functions are used to handle NULL values in database. The objective of the general NULL handling functions is to replace the NULL values with an alternate value. We shall briefly see through these functions below. NVL The NVL function substitutes an alternate value for a NULL value. Syntax: NVL( Arg1, replace_with ) In the syntax, both the parameters are mandatory. Note that NVL function works with all types of data types. And also that the data type of original string and the replacement must be in compatible state i.e. either same or implicitly convertible by Oracle. If arg1 is a character value, then oracle converts replacement string to the data type compatible with arg1 before comparing them and returns VARCHAR2 in the character set of expr1. If arg1 is numeric, then Oracle determines the argument with highest numeric precedence, implicitly converts the other argument to that data type, and returns that data type. The SELECT statement below will display ”n/a” if an employee has been not assigned to any job yet i.e. JOB_ID is NULL. Otherwise, it would display the actual JOB_ID value. SELECT first_name, NVL(JOB_ID, ”n/a”) FROM employees; NVL2 As an enhancement over NVL, Oracle introduced a function to substitute value not only for NULL columns values but also for NOT NULL columns. NVL2 function can be used to substitute an alternate value for NULL as well as non NULL value. Syntax: NVL2( string1, value_if_NOT_null, value_if_null ) The SELECT statement below would display ”Bench” if the JOB_CODE for an employee is NULL. For a definite not null value of JOB CODE, it would show constant value ”Job Assigned”. SQL> SELECT NVL2(JOB_CODE, ”Job Assigned”, ”Bench”) FROM employees; NULLIF The NULLIF function compares two arguments expr1 and expr2. If expr1 and expr2 are equal, it returns NULL; else, it returns expr1. Unlike the other null handling function, first argument can”t be NULL. Syntax: NULLIF (expr1, expr2) Note that first argument can be an expression that evaluates to NULL, but it can”t be the literal NULL. Both the parameters are mandatory for the function to execute. The below query returns NULL since both the input values, 12 are equal. SELECT NULLIF (12, 12) FROM DUAL; Similarly, below query return ”SUN” since both the strings are not equal. SELECT NULLIF (”SUN”, ”MOON”) FROM DUAL; COALESCE COALESCE function, a more generic form of NVL, returns the first non-null expression in the argument list. It takes minimum two mandatory parameters but maximum arguments has no limit. Syntax: COALESCE (expr1, expr2, … expr_n ) Consider the below SELECT query. It selects the first not null value fed into address fields for an employee. SELECT COALESCE (address1, address2, address3) Address FROM employees; Interestingly, the working of COALESCE function is similar to IF..ELSIF..ENDIF construct. The query above can be re-written as – IF address1 is not null THEN result := address1; ELSIF address2 is not null THEN result := address2; ELSIF address3 is not null THEN result := address3; ELSE result := null; END IF; Conditional Functions Oracle provides conditional functions DECODE and CASE to impose conditions even in SQL statement. The DECODE function The function is the SQL equivalence of IF..THEN..ELSE conditional procedural statement. DECODE works with values/columns/expressions of all data types. Syntax: DECODE (expression, search, result [, search, result]… [, default]) DECODE function compares expression against each search value in order. If equality exists between expression and search argument, then it returns the corresponding result. In case of no match, default value is returned, if defined, else NULL. In case of any type compatibility mismatch, oracle internally does possible implicit conversion to return the results. As a matter of fact, Oracle considers two nulls to be equivalent while working with DECODE function. SELECT DECODE(NULL,NULL,”EQUAL”,”NOT EQUAL”) FROM DUAL; DECOD —– EQUAL If expression is null, then Oracle returns the result of the first search that is also null. The maximum number of components in the DECODE function is 255. SELECT first_name, salary, DECODE (hire_date, sysdate,”NEW JOINEE”,”EMPLOYEE”) FROM employees; CASE expression CASE expressions works on the same concept as DECODE but differs in syntax and usage. Syntax: CASE [ expression ] WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2 … WHEN condition_n THEN result_n ELSE result END Oracle search starts from left and moves rightwards until it finds a true condition, and then returns result expression associated with it. If no condition is found to be true, and an ELSE clause exists, then Oracle returns result defined with else. Otherwise, Oracle returns null. The maximum number of arguments in a CASE expression is 255. All expressions count toward this limit, including the initial expression of a simple CASE expression and the optional ELSE expression. Each WHEN … THEN pair counts as two arguments. To avoid exceeding this limit, you can nest CASE expressions so that the return_expr itself is a CASE expression. SELECT first_name, CASE WHEN salary < 200 THEN ”GRADE 1” WHEN salary > 200 AND salary < 5000 THEN ”GRADE 2” ELSE ”GRADE 3” END CASE FROM employees; ENAM CASE —- ——- JOHN GRADE 2 EDWIN GRADE 3 KING GRADE 1 Print Page Previous Next Advertisements ”;
SQL – The SQL SELECT Statement Questions ”; Previous Next 1. Identify the capabilities of SELECT statement. Projection Selection Data Control Transaction Answer: A, B. The SELECT statement can be used for selection, projection and joining. 2. Determine the capability of the SELECT statement demonstrated in the given query. SELECT e.ename, d.dname FROM emp e, dept d WHERE e.deptno = d.deptno AND e.sal > 1000; Selection Filtering Joining Projection Answer: A, C, D. Projection is including only the required columns in query, while Selection is selecting only the required data. Joining means combining two tables together through a connecting column. 3. Which of the following clause is used to suppress duplicates in a SELECT statement? INTERSECT DUPLICATE DISTINCT UNIQUE Answer: C, D. Duplicate data can be restricted with the use of DISTINCT or UNIQUE in the SELECT statement. 4. Chose the statements which correctly specify a rule to write a SQL statement SQL statements are case sensitive Keywords can be abbreviated to build a standard SQL statements are case in-sensitive clauses must be placed together Answer: C.SQL statements are not case sensitive. 5. Determine the output of the below query – SELECT ”5+7” FROM dual; 12 5+7 5 7 Answer: B.Oracle treats the values within double quotes as string expressions. 6. Write a query to display employee details (Name, Department, Salary and Job) from EMP table. SELECT ename, deptno, sal, job FROM emp; SELECT * FROM emp; SELECT DISTINCT ename, deptno, sal, job FROM emp; SELECT ename, deptno, sal FROM emp; Answer A.Select the required from the tables each separated by a comma. 7. Which of the below queries displays employees” name and new salary after the increment of 1000? SELECT ename, sal FROM emp; SELECT ename, sal=sal+1000 FROM emp; SELECT ename, sal+1000 FROM emp; SELECT ename, 1000 FROM emp; Answer: C. Basic arithmetic calculations can be done using the columns in SELECT statements. 8. Determine the output of the below query SELECT 36/2-5*10 FROM dual; 130 -32 -120 175 Answer: B. Multiplication and Division occur before addition and subtraction. 9. Determine the output of the below query SELECT (100-25)/15*(20-3) FROM dual; 0.294 -85 63.67 85 Answer: D. Expression within the brackets are executed before the divisions and multiplications in the expression. 10. Chose the statements which correctly define a NULL value. NULL is a special value with zero bytes NULL is no value or unknown value NULL is represented by a blank space NULL is not same as zero Answer: B, D.NULL is NO VALUE but neither same as zero nor as blank or space character. 11. Determine the output of the below query SELECT sal + NULL FROM emp WHERE empno = 7369; sal + NULL NULL 0 1250 Answer: B. Any arithmetic operation with NULL results in NULL. 12. Which of the below statements define column alias correctly? A column alias renames a column heading A column alias is an alternate column in a table A column alias can be specified during table definition A column alias immediately follows the column or expression in the SELECT statement Answer: A, D. Column Alias can be used to name an expression in the SELECT statement. 13. Specify the column alias NEWSAL for the expression containing salary in the below SQL query SELECT ename, job, sal + 100 FROM emp; (sal + 100) AS NEWSAL (sal + 100) NEWSAL (sal + 100) IS NEWSAL sal + 100 IS NEWSAL Answer: A, B.Use ”AS” to signify new alias to a column expression. 14. Specify the column alias “New Salary” for the expression containing salary in the below SQL query SELECT ename, job, sal + 100 FROM emp; (sal + 100) AS New Salary (sal + 100) “New Salary” (sal + 100) IS New Salary sal + 100 as “New Salary” Answer: B, D. Column alias with space and special characters must be enquoted within double quotes. 15. Which command is used to display the structure of a table? LIST SHOW DESCRIBE STRUCTURE Answer: C.DESCRIBE is used to show the table structure. 16. Predict the output when below statement is executed in SQL* Plus? DESC emp Raises error “SP2-0042: unknown command “desc emp” – rest of line ignored.” Lists the columns of EMP table Lists the EMP table columns, their data type and nullity Lists the columns of EMP table along with their data types Answer: C. DESCRIBE is used to show the table structure along with table columns, their data type and nullity 17. Which of the below statements are true about the DESCRIBE command? It can be used in SQL*Plus only It can be used in both SQL*Plus as well as SQL Developer It doesn”t works for object tables It doesn”t works for SYS owned tables Answer: B. 18. Which of the below alphanumeric characters are used to signify concatenation operator in SQL? + || – :: Answer: B.In SQL, concatenation operator is represented by two vertical bars (||). 19. Which of the below statements are correct about the usage of concatenation operator in SQL? It creates a virtual column in the table It generates a character expression as the result of concatenation of one or more strings It creates a link between two character columns It can be used to concatenate date expressions with other columns Answer: B, D. Concatenation operator joins two values as an expression. 20. Predict the output of the below query SELECT ename || NULL FROM emp WHERE empno = 7369 SMITH SMITH NULL SMITHNULL ORA-00904: “NULL”: invalid identifier Answer: A. Concatenation with NULL results into same value. 21. Predict the output of the below query SELECT 50 || 0001 FROM dual 500001 51 501 5001 Answer: C. The leading zeroes in the right operand of expression are ignored by Oracle. 22. You execute the below query SELECT e.ename||” departments”s name is:”|| d.dname FROM emp e, dept d where e.deptno=d.deptno; And get the exception – ORA-01756: quoted string not properly terminated. Which of the following solutions can permanently resolve the problem?