Oracle Database 12c SQL Questions and Answers
Table ORDER_ITEMS contains columns ORDER_ID, UNIT_PRICE and QUANTITY, of data type NUMBER
Statement 1:
SELECT MAX (unit price*quantity) "Maximum Order FROM order items;
Statement 2:
SELECT MAX (unit price*quantity "Maximum order" FROM order items GROUP BY order id;
Which two statements are true?
Options:
Statement 2 returns only one row of output.
Both the statement given the same output.
Both statements will return NULL if either UNIT PRICE or QUANTITY contains NULL,
Statement 2 may return multiple rows of output.
Statement 1 returns only one row of output.
Answer:
D, EExplanation:
Analyzing the given SQL statements on the ORDER_ITEMS table:
- D. Statement 2 may return multiple rows of output: Statement 2 groups the results by ORDER_ID, which means it calculates the maximum UNIT_PRICE * QUANTITY for each ORDER_ID, potentially returning multiple rows depending on the number of unique ORDER_IDs in the table.
- E. Statement 1 returns only one row of output: Statement 1 computes the maximum product of UNIT_PRICE and QUANTITY across all entries in the ORDER_ITEMS table, returning a single row with the maximum value.
Incorrect options:
- A: Since Statement 2 groups by ORDER_ID, it does not necessarily return just one row; it returns one row per ORDER_ID.
- B: These statements do not yield the same output; Statement 1 returns a single maximum value, while Statement 2 returns the maximum value per ORDER_ID.
- C: If either UNIT_PRICE or QUANTITY is NULL, the product for that row will be NULL, but the MAX function ignores NULL values in its calculation unless all rows are NULL, in which case it returns NULL.
Examine the description of the CUSTOMERS table:
Which two SELECT statements will return these results:
CUSTOMER_ NAME
--------------------
Mandy
Mary
Options:
SELECT customer_ name FROM customers WHERE customer_ name LIKE ' % a % ’ ;
SELECT customer_ name FROM customers WHERE customer name LIKE 'Ma%' ;
SELECT customer_ name FROM customers WHERE customer_ name='*Ma*';
SELECT customer_ name FROM customers WHERE UPPER (customer_ name ) LIKE 'MA*. ;
SELECT customer_ name FROM customers WHERE customer name LIKE 'Ma*';
SELECT customer_ name FROM customers WHERE UPPER (customer name) LIKE 'MA&';
SELECT customer_ name FROM customers WHERE customer_ name KIKE .*Ma*';
Answer:
B, DExplanation:
The SQL LIKE operator is used in a WHERE clause to search for a specified pattern in a column. Here are the evaluations of the options:
- A: The pattern ' % a % ’ will match any customer names that contain the letter 'a' anywhere in the name, not necessarily those starting with 'Ma'.
- B: This is correct as 'Ma%' will match any customer names that start with 'Ma'.
- C: In SQL, the wildcard character is '%' not '*', therefore, the pattern 'Ma' is incorrect.
- D: This is the correct syntax. 'UPPER (customer_ name ) LIKE 'MA%'' will match customer names starting with 'Ma' in a case-insensitive manner.
- E: Again, '*' is not a valid wildcard character in SQL.
- F: The character '&' is not a wildcard in SQL.
- G: The operator 'KIKE' is a typo, and '.Ma' is not valid SQL pattern syntax.
Which two are true about scalar subquery expressions?
Options:
You cannot correlate them with a table in the parent statement
You can use them as a default value for a column.
.You must enclose them in parentheses.
They can return at most one row.
They can return two columns.
Answer:
C, DExplanation:
Scalar subquery expressions in Oracle SQL have specific rules:
- Option C: You must enclose them in parentheses.
- Option D: They can return at most one row.
Options A, B, and E are incorrect based on Oracle SQL functionalities:
- Option A is incorrect because scalar subqueries can indeed be correlated with the parent query.
- Option B is true but not in the context of default constraints for table columns in the CREATE TABLE statement.
- Option E is incorrect because scalar subqueries can only return a single column by definition.
Examine these statements which execute successfully:
ALTER SESSION SET NLS_DATE_FORMAT = ‘DD-MON-YYYY HH24 MI: SS’
ALTER SESSION SET TIME_ ZONE = ‘-5:00’;
SELECT DBTIMEZONE, SYSDATE FROM DUAL
Examine the result:
If LOCALTIMESTAMP was selected at the same time what would it return?
Options:
11-JUL-2019 6,00,00,00000000 AM – 05:00
11-JUL-2019 11,00,00,00000000 AM
11-JUL-2019 6,00,00,000000 AM
11-JUL-2019 11,00,00,000000AM -05:00
Answer:
AExplanation:
The LOCALTIMESTAMP function in Oracle Database returns the current date and time in the session time zone. Given that the session time zone was set to -5:00 with the ALTER SESSION SET TIME_ZONE command, LOCALTIMESTAMP will return the date and time adjusted to this session time zone.
The SYSDATE function, on the other hand, returns the current date and time from the operating system of the database server, which is not affected by the session time zone setting. In the result shown, SYSDATE returns 11-JUL-2019 11:00:00, which reflects the system time zone, not the session time zone.
The time difference between the DBTIMEZONE (+00:00) and the session time zone (-5:00) is 5 hours. Since SYSDATE shows the time as 11:00:00 in the system time zone, the LOCALTIMESTAMP adjusted to the session time zone would show the time as 06:00:00.
The correct answer is A: 11-JUL-2019 6:00:00.00000000 AM – 05:00. This represents the local timestamp in the session time zone, which is 5 hours behind the DBTIMEZONE.
Please note that the exact format returned by LOCALTIMESTAMP includes the fractional seconds up to 9 decimal places, and the time zone offset is specified as part of the timestamp.
Examine this statement:
CREATE TABTE orders
(sarial_no NUMBER UNIQUE,
order_id NUMBER PRIMARY KEY ,
order_date DATE NOT NULL,
status VARCHAR2 (10) CHECK (status IN ('CREDIT', 'CASH')),
product_id NUMBER REFERENCES products (product_id),
order_ total NUMBER);
On which two columns of the table will an index be created automatically?
Options:
SERIAL_NO
ORDER_DATE
PRODUCT_ ID
ORDER TOTAL
ORDER_ ID
STATUS
Answer:
A, EExplanation:
An index is created automatically on columns that are defined with a UNIQUE constraint and a PRIMARY KEY constraint.
A. True. Since the serial_no column is defined with a UNIQUE constraint, Oracle will automatically create an index for this column.
E. True. The order_id column is defined with a PRIMARY KEY constraint, and Oracle automatically creates a unique index on the primary key column.
Which two are true about queries using set operators such as UNION?
Options:
An expression in the first SELECT list must have a column alias for the expression
CHAR columns of different lengths used with a set operator retum a vAacsua mhtoe e equals the longest CHAR value.
Queries using set operators do not perform implicit conversion across data type groups (e.g. character, numeric)
In a query containing multiple set operators INTERSECT always takes precedence over UNION and UNION ALL
All set operators are valid on columns all data types.
Answer:
B, DExplanation:
Set operators allow you to combine multiple queries into a single query. The key points for each option are:
A. An expression in the first SELECT list does not need to have a column alias; however, the column alias given to an expression in the first SELECT list is used as the column name of the output.
B. This statement is true. When CHAR columns of different lengths are combined with a set operator, Oracle will pad the shorter values with spaces to match the length of the longest value. This behavior is consistent with the SQL standard and Oracle's treatment of the CHAR datatype.
C. Oracle Database performs implicit conversion between compatible data types where necessary when using set operators. For example, a NUMBER can be implicitly converted to a VARCHAR2 and vice versa if the context requires it.
D. This is true. When multiple set operators are used in a single query, the INTERSECT operator takes precedence over the UNION and UNION ALL operators. This order of operation can be overridden by using parentheses.
E. Not all set operators work with all data types. For instance, LOB and LONG RAW data types cannot be used with set operators.
References:
- Oracle Database SQL Language Reference, 12c Release 1 (12.1): "Set Operators"
- Oracle Database SQL Language Reference, 12c Release 1 (12.1): "Data Types"
Examine the description of the PRODUCTS table:
Which three queries use valid expressions?
Options:
SELECT produet_id, unit_pricer, 5 "Discount",unit_price+surcharge-discount FROM products;
SELECT product_id, (unit_price * 0.15 / (4.75 + 552.25)) FROM products;
SELECT ptoduct_id, (expiry_date-delivery_date) * 2 FROM products;
SPLECT product_id, expiry_date * 2 FROM products;
SELEGT product_id, unit_price, unit_price + surcharge FROM products;
SELECT product_id,unit_price || "Discount", unit_price + surcharge-discount FROM products;
Answer:
B, C, EExplanation:
B. SELECT product_id, (unit_price * 0.15 / (4.75 + 552.25)) FROM products; C. SELECT product_id, (expiry_date - delivery_date) * 2 FROM products; E. SELECT product_id, unit_price, unit_price + surcharge FROM products;
Comprehensive and Detailed Explanation WITH all References:
A. This is invalid because "Discount" is a string literal and cannot be used without quotes in an arithmetic operation. Also, there is a typo in unit_pricer, and 'discount' is not a defined column in the table. B. This is valid. It shows a mathematical calculation with unit_price, which is of NUMBER type. Division and multiplication are valid operations on numbers. C. This is valid. The difference between two DATE values results in the number of days between them, and multiplying this value by a number is a valid operation. D. This is invalid because expiry_date is of DATE type and cannot be multiplied by a number. Also, there's a typo: "SPLECT" should be "SELECT". E. This is valid. Both unit_price and surcharge are NUMBER types, and adding them together is a valid operation. F. This is invalid because concatenation operator || is used between a number (unit_price) and a string literal "Discount", which is not enclosed in single quotes, and 'discount' is not a defined column in the table.
In SQL, arithmetic operations on numbers and date arithmetic are valid expressions. Concatenation is also a valid expression when used correctly between string values or literals. Operations that involve date types should not include multiplication or division by numbers directly without a proper interval type in Oracle SQL.
These rules are detailed in the Oracle Database SQL Language Reference, where expressions, datatype precedence, and operations are defined.
Which two join conditions in a from clause are non-equijoins?
Options:
tablet join table2 ON (table1.column = table2.column) where table2.column LIKE 'A'
table1 join table2 on (table1.column between table2.column] and table2.column2)
table1 natural JOIN table2
table1 join table2 using (column1, column2)
table1 join table2 ON (table1.column >= table2.column)
Answer:
B, EExplanation:
Equijoins are joins that use the equality operator (=) to match rows. Non-equijoins are joins that use operators other than the equality operator.
A. False. This condition is an equijoin as it uses the equality operator (=).
B. True. This join condition uses the BETWEEN operator, which is not based on equality.
C. False. A natural join is a type of equijoin where the join is made on all columns with the same names in both tables.
D. False. USING clause is used to specify an equijoin on one or more columns.
E. True. This join condition uses the greater than or equal to (>=) operator, making it a non-equijoin.
Which three items does a direction of a relationship contain?
Options:
an attribute
a cardinality
label
an optionality
a unique identifier
an entity
Answer:
B, C, DExplanation:
In data modeling and database design, the direction of a relationship typically includes:
- Option B: a cardinality
- Option C: label
- Option D: an optionality
Options A, E, and F are not part of the direction of a relationship:
- Option A: An attribute is a property or characteristic of an entity, not the direction of a relationship.
- Option E: A unique identifier uniquely identifies each instance of an entity, not a relationship's direction.
- Option F: An entity is a thing with distinct and independent existence in a database, usually mapped to a table, not a part of the direction of a relationship.
Examine this Statement which returns the name of each employee and their manager,
SELECT e.last name AS emp,,m.last_name AS mgr
FROM employees e JOIN managers m
ON e.manager_ id = m. employee_ id ORDER BY emp;
You want to extend the query to include employees with no manager. What must you add before JOIN to do this?
Options:
CROSS
FULL OUTER
LEFT OUTER
RIGHT OUTER
Answer:
CExplanation:
To include employees with no manager in the query results, a LEFT OUTER JOIN should be used. This type of join returns all records from the left table (employees), and the matched records from the right table (managers). The result is NULL from the right side if there is no match.
Here's the modified query:
SELECT e.last_name AS emp, m.last_name AS mgr FROM employees e LEFT OUTER JOIN managers m ON e.manager_id = m.employee_id ORDER BY emp;
This ensures that even if an employee does not have a manager (i.e., e.manager_id is NULL or there is no corresponding m.employee_id), that employee will still be included in the results.
Which statements is true about using functions in WHERE and HAVING?
Options:
using single-row functions in the WHERE clause requires a subquery
using single-row functions in the HAVING clause requires a subquery
using aggregate functions in the WHERE clause requires a subquery
using aggregate functions in the HAVING clause requires a subquery
Answer:
CExplanation:
Single-row functions can be used in the WHERE and HAVING clauses without requiring a subquery. However, aggregate functions, which operate on many rows to give one result per group, cannot be used in a WHERE clause unless a subquery is used because the WHERE clause is processed before the individual rows are aggregated into groups.
A. False. Single-row functions can be directly used in the WHERE clause.
B. False. Single-row functions can be directly used in the HAVING clause.
C. True. Aggregate functions cannot be used in the WHERE clause without a subquery because the WHERE clause filters individual rows before they are aggregated.
D. False. Aggregate functions are intended to be used in the HAVING clause, which is specifically for filtering groups of rows after they have been aggregated, and they do not require a subquery to be used there.
Which two statements are true about Oracle synonyms?
Options:
A synonym can have a synonym.
All private synonym names must be unique in the database.
Any user can create a PUBLIC synonym.
A synonym can be created on an object in a package.
A synonym has an object number.
Answer:
A, CExplanation:
Synonyms in Oracle Database are aliases for database objects.
A. Correct. A synonym can be created for another synonym, essentially chaining synonyms. B. Incorrect. Private synonyms must be unique within a schema. However, because each user has their own schema, multiple users can have private synonyms with the same name, each pointing to objects in their respective schemas. C. Correct. Any user with the necessary privileges can create a PUBLIC synonym, which is accessible to all users. D. Incorrect. A synonym cannot be created for an object within a package, but it can be created for the package itself. E. Incorrect. Synonyms, like views, do not have object numbers because they do not occupy space in the database as tables do.
References can be found in the Oracle Database SQL Language Reference documentation, which details the rules and functionality of synonyms.
Examine the description of the SALES table:
The SALES table has 5,000 rows.
Examine this statement:
CREATE TABLE sales1 (prod id, cust_id, quantity_sold, price)
AS
SELECT product_id, customer_id, quantity_sold, price
FROM sales
WHERE 1=1
Which two statements are true?
Options:
SALES1 is created with 1 row.
SALES1 has PRIMARY KEY and UNIQUE constraints on any selected columns which had those constraints in the SALES table.
SALES1 Is created with 5,000 rows.
SALES1 has NOT NULL constraints on any selected columns which had those constraints in the SALES table.
Answer:
A, DExplanation:
When creating a new table with a query, the statements that are true are:
- A. SALES1 is created with 1 row.This is incorrect actually; the given query with WHERE 1=1 will retrieve all rows from the sales table, not just one row. Therefore, SALES1 will be created with the same number of rows as in the SALES table, assuming there are no WHERE clause conditions limiting the rows.
- D. SALES1 has NOT NULL constraints on any selected columns which had those constraints in the SALES table.This is true. When a table is created using a CREATE TABLE AS SELECT statement, the NOT NULL constraints on the columns in the selected columns are preserved in the new table.
Options B and C are incorrect:
- B is incorrect because the primary key and unique constraints are not carried over to the new table when using the CREATE TABLE AS SELECT syntax.
- C is incorrect in the context of this scenario. However, if interpreted as a standalone statement (ignoring A), C would be the correct description of the outcome since WHERE 1=1 will not filter out any rows.
Examine this partial command:
CREATE TABLE cust(
cust_id NUMBER(2),
credit_limit NUMBER(10)
ORGANIZATION EXTERNAL
Which two clauses are required for this command to execute successfully?
Options:
the ACCESS PARAMETERS clause
the DEFAULT DIRECTORY clause
the access driver TYPE clause
the LOCATION clause
the REJECT LIMIT clause
Answer:
A, DExplanation:
When creating an external table, which allows you to access data in a flat file as though it is a table inside the database, certain clauses are required:
- A. the ACCESS PARAMETERS clause: This clause specifies the parameters required by the access driver to read the data files.
- D. the LOCATION clause: This clause specifies the location of the data files that make up the external table.
References:
- Oracle Database SQL Language Reference 12c, particularly the sections detailing the creation and management of external tables.
Which two queries execute successfully?
Options:
SELECT prod_id, exp_date FROM products
UNION ALL
SELECT prod_id, NULL FROM new_products;
SELECT prod_id, prod_name FROM products
INTERSECT
SELECT 100, prod_name FROM newproducts;
SELECT * FROM products
UNION
SELECT * FROM new_products;
SELECT k FROM products
MINUS
SELECT prod_id FROM new_products;
SELECT prod_id FROM products
UNION ALL
SELECT prod_id, prod_name FROM new_products;
Answer:
A, CExplanation:
For SQL queries involving set operations like UNION, UNION ALL, INTERSECT, and MINUS, the data types and number of columns in the SELECT statements being combined must be the same. Here is a breakdown of each query option:
- Option A: This query successfully combines results from two tables using UNION ALL, which combines all rows from both SELECT statements, including duplicates. Both queries select two columns (prod_id and exp_date, with exp_date being NULL in the second query). This is valid as the number of columns and their data types match.
- Option B: This query attempts to use INTERSECT, which returns only the rows common to both SELECT statements. However, the first SELECT statement chooses prod_id and prod_name, while the second only substitutes a constant value for prod_id without specifying from which table it selects prod_name. If "newproducts" (presumably a typo and should be "new_products") does not have the exact columns as "products", or if the data types do not match, it will fail.
- Option C: This query uses UNION, which removes duplicates from the combined dataset. The use of SELECT * assumes that both "products" and "new_products" tables have the same columns in the same order with matching data types. This query will succeed if those conditions are met.
- Option D: This query uses MINUS to subtract results of the second SELECT from the first. However, it fails because 'k' does not explicitly match a column name in "products", suggesting a potential error unless 'k' is indeed a valid column.
- Option E: This query fails because the first SELECT statement fetches only one column (prod_id) while the second fetches two columns (prod_id and prod_name). UNION ALL requires the same number of columns with compatible types in all SELECT statements involved.
Examine this statement which executes successfully:
Which three are true?
Options:
Regardless of salary,only if the employee id is less than 125,insert EMPLOYEE_ID,NANAGER_ID,SALARY into the MGR_HISTORY table.
If the salary is more than 20000 and the employee is less than 125,insert EMPLOYEE_ID and SALARY into the SPECIAL_SAL table.
Only if the salary is 20000 or less and the employee id is less than 125,insert EMPLOYEE_ID,MANAGER_ID,and SALARY into the MGR_HISTORY table.
Regardless of salary and employee id,insert EMPLOYEE_ID,MANAGER_ID,and SALARY into the MGR_HISTORY table.
If the salary is 20000 or less and the employee id is less than 125,insert EMPLOYEE_ID,HIRE_DATE,and SALARY into the SAL_HISTORY table.
Only if the salary is 20000 or less and the employee id is 125 or higher,insert EMPLOYEE_ID,MANAGER_ID,and SALARY into the MDR_HISTORY table.
Answer:
A, C, EExplanation:
The question describes a scenario with multiple conditional statements about data manipulation based on certain criteria related to employee_id and salary. The options detail different conditions and corresponding actions (insertions into various tables). Given the conditions specified in each option, here are the accurate answers based on logical deduction as Oracle SQL does not directly define these scenarios; instead, it provides the mechanisms (like IF conditions, WHERE clauses, etc.) to implement such logic:
- Option A: Regardless of salary, only if the employee id is less than 125, insert EMPLOYEE_ID, MANAGER_ID, SALARY into the MGR_HISTORY table.
- Option C: Only if the salary is 20000 or less and the employee id is less than 125, insert EMPLOYEE_ID, MANAGER_ID, and SALARY into the MGR_HISTORY table.
- Option E: If the salary is 20000 or less and the employee id is less than 125, insert EMPLOYEE_ID, HIRE_DATE, and SALARY into the SAL_HISTORY table.
Which two statements are true about the SET VERIFY ON command?
Options:
It displays values for variables created by the DEFINE command.
It can be used in SQL Developer and SQL*Plus.
It can be used only in SQL*plus.
It displays values for variables prefixed with &&.
It displays values for variables used only in the WHERE clause of a query.
Answer:
A, BExplanation:
The SET VERIFY ON command is related to how SQL*Plus and SQL Developer display information about substitution variables:
- A. It displays values for variables created by the DEFINE command: When VERIFY is set to ON, SQL*Plus and SQL Developer will display the old and new values of a substitution variable when it is redefined using the DEFINE command or when a new value is provided for it during the session.
- B. It can be used in SQL Developer and SQL*Plus: While traditionally associated with SQL*Plus, the SET VERIFY command is also supported in SQL Developer, allowing you to control the display of substitution variable values in both environments.
References:
- Oracle SQL*Plus User's Guide and Reference, especially the section on the SET command and substitution variables.
Which three statements are true?
Options:
A customer can exist in many countries.
The statement will fail if a row already exists in the SALES table for product 23.
The statement will fail because subquery may not be I contained in a values clause.
The SALES table has five foreign keys.
The statement will execute successfully and a new row will be inserted into the SALES table.
A product can have a different unit price at different times.
Answer:
A, C, FExplanation:
- A. A customer can exist in many countries. This is true as customers can have multiple addresses or operations in different countries, and a database design can reflect this by allowing multiple country entries for a single customer1.
- C. The statement will fail because subquery may not be I contained in a values clause. In Oracle Database 12c, a subquery cannot be used within the VALUES clause of an INSERT statement. The correct approach would be to use the subquery in conjunction with the INSERT INTO … SELECT syntax if multiple rows are derived from a subquery2.
- F. A product can have a different unit price at different times. It is common for products to have different unit prices at different times due to various factors such as promotions, discounts, or changes in cost price. This can be represented in a database by having a price history table or a similar mechanism to track the changes in price over time1.
Note: The other options are incorrect because:
- B. The statement about the SALES table failing if a row already exists for product 23 is not necessarily true. Oracle allows for multiple rows with the same product ID if the table is designed to handle such cases, like having a composite primary key or no constraints preventing duplicates.
- D. Without specific information about the SALES table’s design, we cannot verify the number of foreign keys it has.
- E. The statement about the successful execution and insertion of a new row into the SALES table is too vague without the context of the actual SQL statement being referred to.
You execute this query:
SELECT TO CHAR (NEXT_DAY(LAST_DAY(SYSDATE),’MON’ ),’ dd“Monday for” fmMonth rrr’) FROM DUAL;
What is the result?
Options:
It executes successfully but does not return any result.
It returns the date for the first Monday of the next month.
It generates an error.
It returns the date for the last Monday of the current month.
Answer:
BExplanation:
The query uses TO_CHAR and NEXT_DAY functions to format and determine dates:
- B. It returns the date for the first Monday of the next month: The function NEXT_DAY(LAST_DAY(SYSDATE), 'MON') finds the next Monday after the last day of the current month, effectively giving the first Monday of the next month. The TO_CHAR formatting is used to return this in a readable format.
Examine this statement which executes successfully:
CREATE view emp80 AS
SELECT
FROM employees
WHERE department_ id = 80
WITH CHECK OPTION;
Which statement will violate the CHECK constraint?
Options:
DELETE FROM emp80
WHERE department_ id = 90;
SELECT
FROM emp80
WHERE department_ id = 90;
SELECT
FROM emp80
WHERE department. id = 80;
UPDATE emp80
SET department. 1d =80;
WHERE department_ id =90;
Answer:
AExplanation:
In Oracle SQL, the WITH CHECK OPTION clause in a CREATE VIEW statement ensures that all data manipulation statements performed through the view must conform to the view's defining query.
- Option A: DELETE FROM emp80 WHERE department_id = 90;
Options B, C, and D do not violate the CHECK constraint because:
- Option B: A SELECT statement does not modify data, so it does not violate the CHECK OPTION.
- Option C: Selecting rows with department_id = 80 is consistent with the view’s definition.
- Option D: There is a syntax error, but assuming it meant to set department_id to 80 where it is currently 90, it still would not violate the CHECK constraint because the CHECK OPTION on a view does not prevent updates that do not change the rows to fall outside the view's filter. However, since department_id is supposed to be 80 as per the view definition, this update operation doesn't make logical sense, as there should be no rows with department_id = 90 to update.
The EMPLOYEES table contains columns EMP_ID of data type NUMBER and HIRE_DATE of data type DATE
You want to display the date of the first Monday after the completion of six months since hiring.
The NLS_TERRITORY parameter is set to AMERICA in the session and, therefore, Sunday is the first day of the week Which query can be used?
Options:
SELECT emp_id,NEXT_DAY(ADD_MONTHS(hite_date,6),'MONDAY') FROM employees;
SELECT emp_id,ADD_MONTHS(hire_date,6), NEXT_DAY('MONDAY') FROM employees;
SELECT emp_id,NEXT_DAY(MONTHS_BETWEEN(hire_date,SYSDATE),6) FROM employees;
SELECT emp_id,NEXT_DAY(ADD_MONTHS(hire_date,6),1) FROM employees;
Answer:
AExplanation:
The function ADD_MONTHS(hire_date, 6) adds 6 months to the hire_date. The function NEXT_DAY(date, 'day_name') finds the date of the first specified day_name after the date given. In this case, 'MONDAY' is used to find the date of the first Monday after the hire_date plus 6 months.
Option A is correct as it accurately composes both ADD_MONTHS and NEXT_DAY functions to fulfill the requirement.
Options B, C, and D do not provide a valid use of the NEXT_DAY function, either because of incorrect syntax or incorrect logic in calculating the required date.
The Oracle Database SQL Language Reference for 12c specifies how these date functions should be used.
Examine these statements and results:
SQL> SELECT COUNT(*) FROM emp
COUNT(*)
---------------------
14
sQL> CREATE GLOBAL TEMPORARY TABLE t emp As SELECT * FROM emp;
Table created
SQL> INSERT INTo temp SELECT * FROM emp;
14 rows created
SQL> COMMIT:
Commit complete*
SQL> INSERT INTo temp SELECT * EROM emp;
14. rows created
SQL> SELECT COUNT(*) FROM t emp
How many rows are retrieved by the last query?
Options:
28
0
14
42
Answer:
CExplanation:
Global temporary tables in Oracle Database are designed to hold temporary data for the duration of a session or a transaction.
Given that the global temporary table is created and then populated twice from the emp table without any mention of data deletion, one would initially think the count would be 28, since 14 rows are inserted twice. However, if the temporary table was created with the default ON COMMIT DELETE ROWS option, the rows are deleted at the end of the transaction, which is signified by the COMMIT operation.
Thus, after the first COMMIT, the temporary table would be empty. After the second INSERT, another 14 rows would be added. So, the last query would retrieve 14 rows unless a DELETE operation was committed.
Examine the description or the BOOKS_TRANSACTIONS table:
FOR customers whose income level has a value, you want to display the first name and due amount as 5% of their credit limit. Customers whose due amount is null should not be displayed.
Which query should be used?
Options:
SELECT cust_first_name, cust_credit_limit * . 05 AS DUE AMOUNT
FROM customers
WHERE cust income_level !=NULL
AND cust credit_level !=NULL;
SELECT cust_first_name, cust_credit_limit * . 05 AS DUE AMOUNT
FROM customers
WHERE cust income_level IS NOT NULL
AND due_amount IS NOT NULL;
SELECT cust_first_name, cust_credit_limit * . 05 AS DUE AMOUNT
FROM customers
WHERE cust income_level <> NULL
AND due_amount <> NULL;
SELECT cust_first_name, cust_credit_limit * . 05 AS DUE AMOUNT
FROM customers
WHERE cust_income_level IS NOT NULL
AND cust_credit_limit IS NOT NULL;
SELECT cust_first_name, cust_credit_limit * . 05 AS DUE AMOUNT
FROM customers
WHERE cust income_level !=NULL
AND due_amount !=NULL;
Answer:
DExplanation:
D: True. This query selects the first name and calculates the due amount as 5% of the credit limit from the customers table where the income level is not null and the credit limit is also not null. The IS NOT NULL operator is used to check for non-null values correctly.
- The IS NOT NULL operator is the correct way to check for non-null values in SQL. The <> NULL and != NULL comparisons are incorrect because NULL is not a value that can be compared using these operators; it represents the absence of a value.
- There is no due_amount column in the customers table according to the structure provided, so any WHERE clause referencing due_amount is irrelevant and incorrect. The due_amount is a derived column in the SELECT clause.
- The correct syntax to check for non-null values is IS NOT NULL, which is used in the WHERE clause of the correct answer.
References:
- The use of IS NOT NULL in the WHERE clause to filter out null values is documented in Oracle's SQL reference.
- NULL comparisons must be done with IS NULL or IS NOT NULL for correct logical evaluation in SQL.
Examine these SQL statements which execute successfully:
Which two statements are true after execution?
Options:
The primary key constraint will be enabled and DEFERRED.
The primary key constraint will be enabled and IMMEDIATE.
The foreign key constraint will be disabled.
The foreign key constraint will be enabled and DEFERRED.
The foreign key constraint will be enabled and IMMEDIATE.
Answer:
B, EExplanation:
After the execution of the given SQL statements:
- B. The primary key constraint will be enabled and IMMEDIATE. This is true. The last statement ENABLE CONSTRAINT emp_emp_no_pk; enables the primary key constraint immediately.
- E. The foreign key constraint will be enabled and IMMEDIATE. This is correct as well. The foreign key constraint emp_mgr_fk was not explicitly disabled, so it remains enabled and in the immediate checking mode.
Options A, C, and D are incorrect:
- A is incorrect because constraints are immediate by default; they are not deferred unless explicitly stated.
- C is incorrect because the foreign key constraint emp_mgr_fk was never disabled with the given statements.
- D is incorrect because there is no statement altering the foreign key constraint to a deferred state.
Which three statements are true about performing Data Manipulation Language (DML) operations on a view In an Oracle Database?
Options:
Insert statements can always be done on a table through a view.
The WITH CHECK clause has no effect when deleting rows from the underlying table through the view.
Views cannot be used to query rows from an underlying table if the table has a PRIPOARY KEY and the PRIMARY KEY columns are not referenced in the defining query of the view.
Views cannot be used to add or modify rows in an underlying table if the defining query of the view contains the DISTINCT keyword.
Views cannot be used to add on modify rows in an underlying table if the defining query of the view contains aggregating functions.
Views cannot be used to add rows to an underlying table if the table has columns with NOT NULL constraints lacking default values which are not referenced in the defining query of the view.
Answer:
D, E, FExplanation:
When performing DML operations on a view, certain restrictions apply:
- D. Views cannot be used to add or modify rows in an underlying table if the defining query of the view contains the DISTINCT keyword: If the defining query of a view contains the DISTINCT keyword, it cannot be used for certain DML operations, such as INSERT and UPDATE, because the set of rows it represents is not directly modifiable.
- E. Views cannot be used to add or modify rows in an underlying table if the defining query of the view contains aggregating functions: Aggregating functions create a result that summarises multiple rows and cannot be reversed to point to a single row for modification.
- F. Views cannot be used to add rows to an underlying table if the table has columns with NOT NULL constraints lacking default values which are not referenced in the defining query of the view: If a column with a NOT NULL constraint is not included in the view's defining query, and it does not have a default value, it is not possible to insert through the view because it would violate the NOT NULL constraint.
References:
- Oracle Database SQL Language Reference 12c, particularly the sections on views and the restrictions on DML operations through views.
Which three statements about roles are true?
Options:
Roles are assigned to roles using the ALTER ROLE statement.
A single user can be assigned multiple roles.
Roles are assigned to users using the ALTER USER statement.
A single role can be assigned to multiple users.
Privileges are assigned to a role using the ALTER ROLE statement.
A role is a named group of related privileges that can only be assigned to a user.
Privileges are assigned to a role using the GRANT statement.
Answer:
B, D, GExplanation:
Roles in Oracle Database are designed to simplify the management of privileges. The following statements about roles are true:
- B: A single user can indeed be assigned multiple roles. This allows for easy management of user privileges as they can be grouped into roles, and these roles can be granted to users.
- D: A single role can be assigned to multiple users. This is one of the primary purposes of roles, to provide an efficient way to grant the same set of privileges to different users.
- G: Privileges are granted to a role using the GRANT statement. This allows the role to encapsulate the privileges which can then be granted to users.
The incorrect options are:
- A: Roles cannot be assigned to other roles using the ALTER ROLE statement; they are granted to other roles using the GRANT statement.
- C: Roles are not assigned to users using the ALTER USER statement; roles are granted to users using the GRANT statement.
- E: Privileges are not assigned to a role using the ALTER ROLE statement; they are granted using the GRANT statement.
- F: A role is not limited to being assigned to just one user; it can be assigned to multiple users.
References:
- Oracle Documentation on Roles: Database Security Guide - Roles
- Oracle Documentation on the GRANT statement: SQL Language Reference - GRANT
Which two statements are true about the rules of precedence for operators?
Options:
Arithmetic operators with equal precedence are evaluated from left to right within an expression.
Multiple parentheses can be used to override the default precedence of operators in an expression.
The + binary operator has the highest precedence in an expression in a SQL statements.
NULLS influence the precedence of operators in an expression.
The concatenation operator || is always evaluated before addition and subtraction in an expression.
Answer:
A, BExplanation:
A. True, arithmetic operators of equal precedence are evaluated from left to right within an expression, according to the standard SQL operator precedence. B. True, multiple parentheses can be used in an expression to change the order of operations and override the default precedence of operators.
C, D, and E are not correct because: C. The + binary operator does not have the highest precedence; multiplication and division have higher precedence in SQL. D. NULLS do not influence the precedence of operators in an expression; they may affect the result of an operation but not the order in which operators are evaluated. E. The concatenation operator (||) has lower precedence than arithmetic operators in SQL expressions.
References:
- Oracle documentation on operator precedence: Oracle Database SQL Language Reference
Which statement fails to execute successfully?
A)
B)
C)
D)
Options:
Option A
Option B
Option C
Option D
Answer:
BExplanation:
In Oracle SQL, when performing a JOIN operation, the ON clause is used to specify the condition that relates the two tables being joined. The WHERE clause can be used to further filter the result set.
A) This is a valid join condition using the WHERE clause to filter the rows after the join has been made.
B) This statement will fail because the ON clause should only contain conditions that relate the two tables. The condition for filtering the departments table should be in the WHERE clause, not in the ON clause. This is a common mistake when writing JOIN statements.
C) This is a correct statement. The ON clause specifies how the tables are related and the WHERE clause specifies an additional filtering condition for the query.
D) This statement is also correct. It's similar to the first statement (A) and properly places the department_id filter in the ON clause, which is acceptable though not typically best practice as it can be less readable than using a WHERE clause for non-join conditions.
When the JOIN operation is executed, the database first pairs rows from the joined tables that meet the join condition specified by the ON clause. Then, it filters the result of the JOIN operation based on the condition specified in the WHERE clause.
References:
- Oracle Documentation on Joins: https://docs.oracle.com/database/121/SQLRF/queries006.htm#SQLRF52359
Which three statements are true about GLOBAL TEMPORARY TABLES?
Options:
GLOBAL TEMPORARY TABLE rows inserted by a session are available to any other session whose user has been granted select on the table.
A TRUNCATE command issued in a session causes all rows In a GLOBAL TEMPORARY TABLE for the issuing session to be deleted.
A DELETE command on a GLOBAL TEMPORARY TABLE cannot be rolled back.
A GLOBAL TEMPORARY TABLE's definition is available to multiple sessions.
Any GLOBAL TEMPORARY TABLE rows existing at session termination will be deleted.
GLOBAL TEMPORARY TABLE space allocation occurs at session start.
Answer:
B, D, EExplanation:
Global temporary tables (GTTs) in Oracle have unique properties related to session-based visibility and data persistence:
- B. A TRUNCATE command issued in a session causes all rows in a GLOBAL TEMPORARY TABLE for the issuing session to be deleted: True, TRUNCATE is session-specific for GTTs and will remove all rows inserted by the session that issues the TRUNCATE command.
- D. A GLOBAL TEMPORARY TABLE's definition is available to multiple sessions: The structure of a GTT is persistent and shared across sessions, but the data within is session-specific.
- E. Any GLOBAL TEMPORARY TABLE rows existing at session termination will be deleted: The data in GTTs is private for the session, and when the session ends, the data is deleted automatically.
References:
- Oracle Database Concepts and SQL Language Reference 12c, especially the sections on temporary tables.
A session's NLS_DATE_FORMAT is set to DD Mon YYYY .
Which two queries return the value 1 Jan 2019?
Options:
SELECT to_date(' 2019-01-01 ', 'YYYY -MM-DD' ) FROM DUAL;
SELECT DATE '2019-01-01' FROM DUAL ;
SELECT TO_CHAR('2019-01-01') FROM DUAL; 2019-01-01
SELECT '2019-01-01' FROM DUAL ; 2019-01-01
SELECT TO_ DATE('2019-01-01') FROM DUAL;
Answer:
BExplanation:
When the NLS_DATE_FORMAT is set to DD Mon YYYY, the database expects the date string to be in the format of day, abbreviated month name, and full year.
B. The query SELECT DATE '2019-01-01' FROM DUAL; correctly returns the value 1 Jan 2019 because the ANSI date literal DATE 'YYYY-MM-DD' is independent of the NLS_DATE_FORMAT parameter.
Option A is incorrect because the TO_DATE function requires the format model to match the string literal, which it does not in this case.
Option C is incorrect because TO_CHAR is used to convert a date to a string, not a string to a date.
Option D is incorrect because without specifying that the string is a date, the result is just a string and not a date value.
Option E is incorrect because TO_DATE without a format model relies on the NLS_DATE_FORMAT to interpret the string, and YYYY-MM-DD does not match DD Mon YYYY.
Examine this statement:
SELECT1 AS id,‘ John’ AS first_name, NULL AS commission FROM dual
INTERSECT
SELECT 1,’John’ null FROM dual ORDER BY 3;
What is returned upon execution?[
Options:
2 rows
0 rows
An error
1 ROW
Answer:
DExplanation:
Regarding the provided SQL INTERSECT query:
- D. 1 ROW: The INTERSECT operation will compare the two SELECT statements and return rows that are identical between them. Both queries are designed to return the same values ('1' for the ID, 'John' for the name, and NULL for the commission), hence one row that is identical between the two datasets will be returned.
Incorrect options:
- A: Only one identical row exists between the two datasets.
- B: There is an identical row; thus, it is not zero.
- C: There is no error in the syntax or execution of the query.
Which three statements are true about the DESCRIBE command?
Options:
It can be used from SQL Developer.
It can be used to display the structure of an existing view.
It can be used only from SQL*Plus.
It displays the NOT NULL constraint for any columns that have that constraint.
It displays all constraints that are defined for each column.
It displays the PRIMARY KEY constraint for any column or columns that have that constraint.
Answer:
A, B, DExplanation:
A: True. The DESCRIBE command can indeed be used from SQL Developer as well as other Oracle database tools such as SQL*Plus. This command is used to display the structure of a table, view, or other object, showing information such as column names, data types, and whether a column is nullable.
B: True. The DESCRIBE command can be used to display the structure of an existing view, showing similar information as it would for a table. This includes the columns, their data types, and other pertinent details.
D: True. When DESCRIBE is used, it does display the NOT NULL constraints for columns that have this constraint. This is part of the basic information about the structure of a table or view that can help developers understand the requirements of the data stored therein.
Which two statements are true about the ORDER BY clause?
Options:
Numeric values are displayed in descending order if they have decimal positions.
Only columns that are specified in the SELECT list can be used in the ORDER BY cause.
NULLS are not included in the sort operation.
Column aliases can be used In the ORDER BY cause.
Ina character sort, the values are case-sensitive.
Answer:
D, EExplanation:
The ORDER BY clause in Oracle SQL is used to sort the result set of a query by one or more columns, and it comes with its own set of rules and behaviors:
- D. Column aliases can be used In the ORDER BY clause: True, column aliases that are specified in the SELECT clause can be used in the ORDER BY clause to refer to the columns to sort the results by.
- E. In a character sort, the values are case-sensitive: Oracle sorts results in case-sensitive order by default when using the ORDER BY clause with character columns, unless otherwise specified by the NLS_SORT parameter.
References:
- Oracle Database SQL Language Reference 12c, which provides details on sorting query results using ORDER BY.
Viev the Exhibit and examine the structure of the PRODUCT INFORMATION and INVENTORIEStables.
You have a requirement from the supplies department to give a list containing PRODUCT _ID,SUPPLIER ID, and QUANTITY_ON HAND for all the products where in QUANTITY ON HAND is lessthan five.
Which two SQL statements can accomplish the task? (Choose two)
Options:
SELECT product id, quantity on hand, supplier id
FROM product information
NATURAL JOIN inventories AND quantity .on hand < 5;
SELECT i. product id, i. quantity .on hand, pi. supplier_id
FROM product_information pi JOIN inventories i
ON (pi. product. id=i. product id) AND quantity on hand < 5;
SELECT i. product_id, i. quantity_on hand, pi. supplier id
FROM product information pi JOIN inventories i USING (product id) AND quantity .on hand < 5;
SELECT i.product id, i. quantity on hand, pi. supplier id
FROM product information pi JOIN inventories i
ON (pi.product id=i. product id)WHERE quantity on hand < 5;
Answer:
B, DExplanation:
Given the requirement to list PRODUCT_ID, SUPPLIER_ID, and QUANTITY_ON_HAND for products with QUANTITY_ON_HAND less than five:
- B. This query correctly joins the two tables on PRODUCT_ID and filters rows where QUANTITY_ON_HAND is less than five. However, the syntax presented here might be incorrect due to improper placement of the condition within the ON clause; it should be in a WHERE clause.
- D. This query correctly joins the two tables on PRODUCT_ID and applies the condition in a WHERE clause, which is the proper way to filter rows after performing the join.
Incorrect options:
- A: The syntax uses NATURAL JOIN and AND incorrectly; also, conditions should be in a WHERE clause, not combined with the JOIN clause.
- C: Similar to A, this option incorrectly places a condition directly in the JOIN clause without using a WHERE clause.
Examine the description of the MEMBERS table;
SELECT city,last_name LNAME FROM members …
You want to display all cities that contain the string AN. The cities must be returned in ascending order, with the last names further sorted in descending order.
Which two clauses must you add to the query?
Options:
ORDER BY 1,2.
ORDER BY last_name DESC,city ASC
CORADER BY 1, LNAME DESC
WHERE city=’%AN%;
WHERE city LIKE ’%AN%;
WHERE city IN (’%AN%’)
Answer:
C, EExplanation:
To achieve the desired output for the query from the MEMBERS table:
- C. ORDER BY 1, LNAME DESC: This clause correctly sorts the results first by the first column (city) in ascending order by default, and then by the alias LNAME (last_name) in descending order.
- E. WHERE city LIKE '%AN%': This clause correctly filters the rows to include only those cities containing the string 'AN' anywhere in the city name, using the LIKE operator which is suitable for pattern matching.
Incorrect options:
- A: This would order both columns in ascending order, which does not meet the requirement for last_name to be in descending order.
- B: This misplaces the order priorities and uses explicit column names that contradict the sorting requirement specified.
- D: Incorrect syntax for a LIKE clause; equality operator cannot be used with wildcards.
- F: The IN operator is incorrectly used here with a pattern, which is not valid syntax.
The PROD_ID column is the foreign key in the SALES table.Which references the PRODUCTS table.
Similarly,the CUST_ID and TIME_ID columns are Also foreign keys in the SALES table referencing the CUSTOMERS and TIMES tables, respectively.
Evaluate the following CREATE TABLE command:
CREATE TABLE new_sales(prod_id, I cust_id, order_date DEFAULT SYSDATE)
AS SELECT I prod_id,cust_id,time_id FROM sales.
Which statement is true regarding the above command?
Options:
The NEW_SALES table would not get created because the DEFAULT value cannot be specified in the column definition.
The NEW_SALES table would get created and all the NOT NULL constraints defined on the specified columns would be passed to the new table.
The NEW_SALES table would not get created because the column names in the CREATE TABLE command and the SELECT clause I do not match.
The NEW_SALES table would get created and all the FOREIGN KEY constraints defined on the specified columns would be passed to the new table
Answer:
CExplanation:
The statement true regarding the CREATE TABLE command:
- C. The NEW_SALES table would not get created because the column names in the CREATE TABLE command and the SELECT clause do not match: The SQL command tries to create a table with columns prod_id, cust_id, and order_date, but the SELECT statement specifies columns prod_id, cust_id, and time_id. The mismatch in column names and the number of columns specified will prevent the table from being created.
Incorrect options:
- A: It is possible to specify a DEFAULT value in the column definition when creating a table with the CREATE TABLE AS SELECT syntax.
- B: Not all NOT NULL constraints (or any other constraints, for that matter) are automatically passed to the new table unless explicitly stated in the CREATE TABLE statement.
- D: FOREIGN KEY constraints are not automatically included when creating a table using the CREATE TABLE AS SELECT syntax; they would need to be added explicitly afterwards.
Examine the description of the PRODUCT_INFORMATION table:
Options:
SELECT (COUNT(list_price) FROM Product_intormation WHERE list_price=NULL;
SELECT count(nvl( list_price,0)) FROM product_information WHERE list_price is null;
SELECT COUNT(DISTINCT list_price) FROM product_information WHERE list_price is null.
BELECT COUNT(list_price) FROM product_information where list_price is NULL;
Answer:
BExplanation:
In SQL, when you want to count occurrences of null values using the COUNT function, you must remember that COUNT ignores null values. So, if you want to count rows with null list_price, you have to replace nulls with some value that can be counted. This is what the NVL function does. It replaces a null value with a specified value, in this case, 0.
A, C, and D options attempt to count list_price directly where it is null, but this will always result in a count of zero because COUNT does not count nulls. Option B correctly uses the NVL function to convert null list_price values to 0, which can then be counted. The WHERE list_price IS NULL clause ensures that only rows with null list_price are considered.
The SQL documentation confirms that COUNT does not include nulls in its count and NVL is used to substitute a value for nulls in an expression. So option B will give us the correct count of rows with a null list_price.
Which three statements are true about Oracle synonyms?
Options:
A synonym cannot be created for a PL /SQL package.
A SEQUENCE can have a synonym.
A synonym can be available to all users .
A synonym created by one user can refer to an object belonging to another user.
Any user can drop a PUBLIC synonym.
Answer:
B, C, DExplanation:
B. True. In Oracle, synonyms can be created for sequences, allowing them to be referenced with an alternative name. This can be particularly useful when sequences are accessed across different schemas.
C. True. Oracle provides the ability to create public synonyms which are available to all users in the database. A public synonym is accessible to any user that has the necessary privileges on the underlying object.
D. True. A synonym can be created by a user to refer to an object owned by another user, assuming that the creator of the synonym has the necessary privileges to access the object owned by the other user.
Whith three statements are true about built in data types?
Options:
A VARCHAR2 blank pads column values only if the data stored is non numeric and contains no special characlers
A BFILE stores unstructured binary data in operating systerm files
A CHAR column definition does not require the length to be specified
The default length for a CHAR column is always one character
A VARCHAR2 column definition does not require the length to be specified
A BLOB stores unstructured binary data within the database
Answer:
B, D, FExplanation:
The true statements about built-in data types in Oracle are:
- B: A BFILE is a data type in Oracle that allows for a read-only link to binary files stored outside the database in the operating system. This is correct as per Oracle's documentation.
- D: The default length for a CHAR column, when not specified, is one character. This is according to the Oracle SQL standard.
- F: A BLOB is used for storing binary data within the Oracle database, allowing for storage of large amounts of unstructured binary data.
The incorrect options are:
- A: A VARCHAR2 column does not blank-pad values; it is CHAR that may blank-pad to the fixed length.
- C: A CHAR column requires a length specification, although if omitted, the default is one character.
- E: A VARCHAR2 column requires a length specification; without it, the statement will fail.
References:
- Oracle Documentation on Data Types: Data Types
- Oracle Documentation on LOBs: LOBs
- Oracle Documentation on Character Data Types: Character Data Types
In your session, the NLS._DAE_FORMAT is DD- MM- YYYY.There are 86400 seconds in a day.Examine
this result:
DATE
02-JAN-2020
Which statement returns this?
Options:
SELECT TO_ CHAR(TO_ DATE(‘29-10-2019’) +INTERVAL ‘2’; MONTH + INTERVAL ‘5’; DAY -
INTERVAL ‘86410’ SECOND, ‘ DD-MON-YYYY’) AS "date"
FROM DUAL;
SELECT TO_ CHAR(TO_ DATE(‘29-10-2019’) + INTERVAL ‘3’ MONTH + INTERVAL ‘7’ DAY -
INTERVAL ‘360’ SECOND, ‘ DD-MON-YYYY’) AS "date"
FROM DUAL;
SELECT To CHAR(TO _DATE(‘29-10-2019’) + INTERVAL ‘2’ NONTH + INTERVAL ‘5’ DAY
INEERVAL ‘120’ SECOND, ‘ DD-MON-YYY) AS "date"
FROM DUAL;
SELECT-TO_CHAR(TO _DATE(‘29-10-2019’+ INTERVAL ‘2’ MONTH+INTERVAL ‘6’ DAYINTERVAL
‘120’ SECOND, ‘DD-MON-YY’) AS "daTe"
FROM DUAL;
SELECT-TO_CHAR(TO _DATE(‘29-10-2019’+ INTERVAL ‘2’ MONTH+INTERVAL ‘4’ DAYINTERVAL
‘120’ SECOND, ‘DD-MON-YY’) AS "daTe"
FROM DUAL;
Answer:
BExplanation:
To calculate the date from a given base date with intervals, Oracle allows you to add or subtract intervals from dates. Since the NLS_DATE_FORMAT is set to DD-MM-YYYY, the output is expected to be in that format.
Option B seems to calculate a date that is 3 months and 7 days ahead of October 29, 2019, and then subtracts 360 seconds (which is 6 minutes), resulting in a time that is still within the same day.
Here's how the calculation in option B would work out:
- Start date: 29-10-2019
- Add 3 months: 29-01-2020
- Add 7 days: 05-02-2020
- Subtract 360 seconds: Since it's only a few minutes, the date remains 05-02-2020.
However, this does not match the provided result of 02-JAN-2020. We would need to consider the exact amount of time being subtracted or added to find the correct answer.
But upon reviewing the options, they all have various syntax errors such as a missing TO_CHAR function, incorrect quotes, and date formats not matching the session's NLS_DATE_FORMAT. Therefore, we would need to correct these issues to find the right answer.
Which two queries execute successfully?
Options:
SELECT INTERVAL '1' DAY - SYSDATE FROM DUAL;
SELECT SYSTIMESTAMP + INTERVAL '1' DAY FROM DUAL;
SELECT INTERVAL '1' DAY - INTERVAL '1' MINUTE FROM DUAL;
select INTERVAL '1' DAY +INTERVAL '1' MONTH FROM DUAL;
SELECT SYSDATE “INTERRVAL '1' DAY FROM DUAL;
Answer:
B, CExplanation:
- A: This statement will not execute successfully because you cannot subtract a DAY interval from a DATE directly. SYSDATE needs to be cast to a TIMESTAMP first.
- B: This statement is correct. It adds an interval of '1' DAY to the current TIMESTAMP.
- C: This statement is correct. It subtracts an interval of '1' MINUTE from '1' DAY.
- D: This statement will not execute successfully. In Oracle, you cannot add intervals of different date fields (DAY and MONTH) directly.
- E: This statement has a syntax error with the quotes around INTERVAL and a misspelling, it should be 'INTERVAL'.
Oracle Database 12c SQL supports interval arithmetic as described in the SQL Language Reference documentation.
Which two statements are true about INTERVAL data types
Options:
INTERVAL YEAR TO MONTH columns only support monthly intervals within a range of years.
The value in an INTERVAL DAY TO SECOND column can be copied into an INTERVAL YEAR TO MONTH column.
INTERVAL YEAR TO MONTH columns only support monthly intervals within a single year.
The YEAR field in an INTERVAL YEAR TO MONTH column must be a positive value.
INTERVAL DAY TO SECOND columns support fractions of seconds.
INTERVAL YEAR TO MONTH columns support yearly intervals.
Answer:
A, EExplanation:
Regarding INTERVAL data types in Oracle Database 12c:
- A. INTERVAL YEAR TO MONTH columns only support monthly intervals within a range of years. This is true. The INTERVAL YEAR TO MONTH data type stores a period of time using years and months.
- E. INTERVAL DAY TO SECOND columns support fractions of seconds. This is true. The INTERVAL DAY TO SECOND data type can store days, hours, minutes, seconds, and fractional seconds.
Options B, C, D, and F are incorrect:
- B is incorrect because data types between INTERVAL DAY TO SECOND and INTERVAL YEAR TO MONTH are not compatible.
- C is incorrect as it incorrectly limits INTERVAL YEAR TO MONTH to a single year.
- D is incorrect; the YEAR field can be negative to represent a past interval.
- F is incorrect as INTERVAL YEAR TO MONTH supports intervals that can span multiple years, not just annual increments.
Which three statements are true about single row functions?
Options:
They can be used only in the where clause of a select statement.
They can accept only one argument.
They return a single result row per table.
The argument can be a column name, variable, literal or an expression.
They can be nested to any level.
The date type returned can be different from the data type of the argument.
Answer:
D, E, FExplanation:
Single-row functions in SQL operate on each row independently and can modify the returned value:
- Option A: Incorrect. Single row functions can be used in multiple parts of a SELECT statement, including SELECT, WHERE, and ORDER BY clauses.
- Option B: Incorrect. Single row functions can accept more than one argument, such as the CONCAT function, which can accept multiple string arguments.
- Option C: Incorrect. They return one result for each row processed, not per table.
- Option D: Correct. Single row functions can take various types of arguments including column names, literals, variables, and other expressions.
- Option E: Correct. Functions can be nested within other functions, allowing complex expressions and calculations.
- Option F: Correct. The data type of the result can differ from the arguments’ data types, such as the SUBSTR function returning a VARCHAR2 even when used on a number after converting it to a string.
Which two statements are true regarding the UNION ALL operators?
Options:
NULLS are not ignored during duplicate checking.
Duplicates are eliminated automatically by the UNION ALL operator
The names of columns selected in each SELECT statement must be identical.
The number of columns selected in each SELECT statement must be identical
The output is sorted by the UNION ALL operator.
Answer:
A, DExplanation:
The UNION ALL operator in SQL combines the results of two or more SELECT statements into a single result set:
- Option A: True. Since UNION ALL does not eliminate duplicates, it does not ignore NULLs during any duplicate checking; however, it's worth noting that UNION ALL does not perform duplicate checking at all.
- Option B: False. Unlike the UNION operator, UNION ALL does not eliminate duplicates; it includes all duplicates in the output.
- Option C: False. The column names do not need to be identical in each SELECT statement; however, the result set will use the column names from the first SELECT statement.
- Option D: True. For UNION ALL to work correctly, the number of columns and their data types in each SELECT statement must match, but the column names can differ.
- Option E: False. UNION ALL does not inherently sort the output; it merely combines the results as they are retrieved. Any sorting would need to be explicitly specified using an ORDER BY clause.
Which two statements are true about the DUAL table?
Options:
It can display multiple rows and columns.
It can be accessed only by the SYS user.
It can be accessed by any user who has the SELECT privilege in any schema
It can display multiple rows but only a single column.
It consists of a single row and single column of VARCHAR2 data type.
It can be used to display only constants or pseudo columns.
Answer:
C, EExplanation:
A. Incorrect. DUAL consists of a single row and column. B. Incorrect. DUAL is a special one-row, one-column table present by default in all Oracle database installations and can be accessed by any user with SELECT privilege. C. Correct. Any user with the SELECT privilege can select from the DUAL table. It is a dummy table used primarily for selecting a constant, pseudocolumn, or expression not involving any tables. D. Incorrect. DUAL has only one row and one column. E. Correct. The DUAL table has a single VARCHAR2 column called DUMMY, which has a value of 'X'. F. Incorrect. DUAL can be used for a variety of purposes, such as selecting system constants, user environment variables, expressions, and sequences.
This information is detailed in the Oracle Database SQL Language Reference, which describes the properties and uses of the DUAL table.
You need to calculate the number of days from 1st January 2019 until today.
Dates are stored in the default format of DD-MON-RR.
Which two queries give the required output?
Options:
SELECT SYSDATE-TO_DATE ('01-JANUARY-2019') FROM DUAL;
SELECT TO_DATE (SYSDATE, 'DD/MONTH/YYYY')-'01/JANUARY/2019' FROM DUAL;
SELECT ROUND (SYSDATE-TO_DATE ('01/JANUARY/2019')) FROM DUAL;
SELECT TO_CHAR (SYSDATE, 'DD-MON-YYYY')-'01-JAN-2019' FROM DUAL;
SELECT ROUND (SYSDATE- '01-JAN-2019') FROM DUAL:
Answer:
A, CExplanation:
To calculate the number of days between two dates in Oracle SQL, you can simply subtract the earlier date from the later date, and Oracle will return the number of days between them.
Option A uses SYSDATE to get the current date and TO_DATE to convert the string '01-JANUARY-2019' to a date using the default date format, which matches 'DD-MON-RR'. The subtraction here will correctly give the number of days between these two dates.
Option C is similar to A but includes the ROUND function, which is used to round the number to the nearest whole number. Since the difference between two dates in Oracle SQL is a decimal value representing the number of days and fractional days, rounding will give us the whole number of days, which is what we want.
Options B, D, and E are incorrect because they either use an invalid date format (the default format is 'DD-MON-RR', not 'DD/MONTH/YYYY' or 'DD-MON-YYYY'), perform invalid operations (such as subtracting a string from a date), or misuse SYSDATE.
You must find the number of employees whose salary is lower than employee 110.
Which statement fails to do this?
Options:
SELECT COUNT (*)
FROM employees
JOIN employees a
ON e. salary< a. salary
WHERE a. employee_ id= 110;
SELECT COUNT (* )
FROM employees
WHERE salary < (SELECT salary FROM employees WHERE employee 业id =
110) ;
SELECT COUNT (*)
FROM employees e
JOIN (SELECT salary FROM employees WHERE employee_ id= 110) a
ON e. salary< a. salary;
SELECT COUNT (* )
FROM employees e
WHERE e. salary < (SELECT a. salary FROM employees a WHERE e. employee_ id = 110);
Answer:
DExplanation:
In this context, the correct answers will provide a count of employees with a salary less than that of employee with ID 110. Let's evaluate the provided statements:
- A: This statement is incorrect due to a syntax error; it uses alias 'e' without defining it, and 'a' is also used incorrectly in the JOIN clause. It should have been written with proper aliases.
- B: This statement is correct as it uses a subquery to find the salary of employee ID 110 and compares it to the salaries of all employees to get the count.
- C: This statement is also correct as it creates a derived table with the salary of employee ID 110 and compares it with the salaries of the 'employees' table using a JOIN.
- D: This is the statement that fails. It is incorrect because the subquery references 'e.employee_id = 110', which will compare the salary of each employee to themselves if their ID is 110, not to the salary of employee 110 for all employees.
Which statement will execute successfully?
Options:
SELECT 1, 2 FROM DUAL
UNION
SELECT 3, 4 FROM DUAL
ORDER BY 1, 2;
SELECT 3 FROM DUAL
UNION
SELECT 4 FROM DUAL
ORDER BY 3 ;
SELECT 1, 2 FROM DUAL
UNION
SELECT 3, 4 FROM DUAL
ORDER BY 3, 4;
SELECT 1 FROM DUAL
UNION
SELECT 2 FROM DUAL
ORDER BY 1, 2;
Answer:
BExplanation:
B. True. This statement will execute successfully because it has a single column in the SELECT statements combined with UNION, and the ORDER BY clause is referencing a valid column in the result set.
A is incorrect because it uses an ORDER BY clause with two columns, which is not allowed when the SELECT statements have only one column each. C is incorrect for the same reason as A; it references columns that do not exist in the result set. D is incorrect because it attempts to ORDER BY a second column, which does not exist in the result of the union.
Examine this partial command:
Which two clauses are required for this command to execute successfully?
Options:
the DEFAULT DIRECTORY clause
the REJECT LIMIT clause
the LOCATION clause
the ACCESS PARAMETERS clause
the access driver TYPE clause
Answer:
C, EExplanation:
In Oracle Database 12c, when creating an external table using the CREATE TABLE ... ORGANIZATION EXTERNAL statement, there are certain clauses that are mandatory for the command to execute successfully.
- Statement C, the LOCATION clause, is required. The LOCATION clause specifies one or more external data source locations, typically a file or a directory that the external table will read from. Without this, Oracle would not know where to find the external data for the table.
- Statement E, the access driver TYPE clause, is also required. The access driver tells Oracle how to interpret the format of the data files. The most common access driver is ORACLE_LOADER, which allows the reading of data files in a format compatible with the SQL*Loader utility. Another option could be ORACLE_DATAPUMP, which reads data in a Data Pump format.
- Statements A, B, and D are not strictly required for the command to execute successfully, although they are often used in practice:
For reference, you can find more details in the Oracle Database SQL Language Reference for version 12c, under the CREATE TABLE statement for external tables.
Which two are true?
Options:
CONCAT joins two or more character strings together.
FLOOR returns the largest integer less than or equal to a specified number.
CONCAT joins two character strings together.
INSTR finds the offset within a string of a single character only.
INSTR finds the offset within a character string, starting from position 0.
FLOOR returns the largest positive integer less than or equal to a specified number.
Answer:
A, BExplanation:
The CONCAT function and FLOOR function in Oracle SQL have specific behaviors:
A. CONCAT function joins two or more character strings into one string, making this statement true.
B. FLOOR function returns the largest integer that is less than or equal to the specified number, making this statement true.
C. While CONCAT can join two strings together, this statement is incomplete as it can join more than two.
D. INSTR can find the offset of a substring within a string, not just a single character.
E. INSTR starts searching the string from position 1 in Oracle SQL, not position 0.
F. FLOOR does return the largest integer less than or equal to the specified number, but it can be any integer, not just positive ones.
References:
- Oracle Database SQL Language Reference, 12c Release 1 (12.1): "Single-Row Functions"
Examine this statement,which executes successfully:
In which order are the rows displayed?
Options:
sorted by DEPARTMENT_NAME
sorted by DEPARTMENT_NAME and AVGSAL
sorted by DEPARTMENT_NAME and MAXSAL
sorted by AVGSAL
Sorted by MAXSAL
Answer:
BExplanation:
Since the statement seems to imply that a sort operation involving department names and an average salary (AVGSAL) was executed, the best logical inference, given typical SQL query behavior and assuming a typical structure, is:
- B. sorted by DEPARTMENT_NAME and AVGSAL: Generally, when SQL queries involve grouping and aggregation, the ORDER BY clause (if explicitly mentioned or implied in your statement details) would sort by the grouping column first (DEPARTMENT_NAME) and then by any aggregated column such as average salary (AVGSAL). This order ensures that within each department, the rows are sorted according to the average salary.
Examine the BRICKS table:
You write this query:
SELECT
FROM bricks b1 CROSS JOIN bricks b2
WHERE b1. Weight < b2. Weight:
How many rows will the query return?
Options:
1
16
10
6
4
0
Answer:
DExplanation:
- A: Incorrect because the CROSS JOIN of the BRICKS table with itself will produce more than one row.
- B: Incorrect because CROSS JOINing a table with four rows with itself produces 16 rows, but the WHERE condition filters these down.
- C: Incorrect because while a CROSS JOIN of a table with four rows with itself produces 16 rows, this answer does not take into account the WHERE condition.
- D: Correct. The CROSS JOIN will result in 16 combinations (4x4), but the WHERE condition b1.weight < b2.weight will only be true for combinations where the second weight is greater than the first. Since there are 4 distinct weights, there are (42)=6(24)=6 combinations where one weight is less than the other.
- E: Incorrect because this does not account for the conditions specified in the WHERE clause.
- F: Incorrect because the query will return some rows due to the condition specified.
Examine the description of the EMPLOYEES table:
NLS_DATE_FORMAT is set to DD-MON-YY.
Which query requires explicit data type conversion?
Options:
SELECT salary + 120.50 FROM employees;
SELECT SUBSTR(join date, 1, 2)- 10 FROM employees;
SELECT join date 11.’11 salary FROM employees;
SELECT join date FROM employees where join date > *10-02-2018*;
SELECT join date + 20 FROM employees;
Answer:
DExplanation:
For the EMPLOYEES table and given that NLS_DATE_FORMAT is set to DD-MON-YY, the query that requires explicit data type conversion is:
- D. SELECT join_date FROM employees where join_date > '10-02-2018'; This query compares the JOIN_DATE column of type DATE with a string '10-02-2018'. The string must be explicitly converted to a DATE using the TO_DATE function with a format mask that matches the NLS_DATE_FORMAT or the string literal.
Options A, B, C, and E do not necessarily require explicit data type conversion:
- A does not require conversion because adding a number to a number column is a valid operation.
- B is syntactically incorrect; the correct function to extract a substring is SUBSTR(join_date, 1, 2) and that would require an explicit conversion since JOIN_DATE is a DATE and SUBSTR expects a string, but it seems to be a typo.
- C uses an invalid concatenation operation with the pipe symbols, which could be a typo or misunderstanding, but would not typically require a data type conversion.
- E requires implicit data type conversion because adding a number to a date is valid in Oracle, which adds the number as days to the date.
Examine this SQL statement:
SELECT cust_id, cus_last_name "Last Name"
FROM customers
WHERE country_id = 10
UNION
SELECT cust_id CUST_NO, cust_last_name
FROM customers
WHERE country_id = 30
Identify three ORDER BY clauses, any one of which can complete the query successfully.
Options:
ORDERBY 2, 1
ORDER BY "CUST_NO"
ORDER BY 2,cust_id
ORDER BY CUST_NO
ORDER BY "Last Name"
Answer:
A, EExplanation:
In SQL, the ORDER BY clause can refer to columns by their alias defined in the SELECT clause or by their positional number in the SELECT list. It's important to understand that after a UNION, the column names in the ORDER BY clause refer to the first SELECT statement's column names and aliases:
- Option A: ORDER BY 2, 1This is correct because it refers to the second and first columns in the first SELECT clause, which correspond to the aliases "Last Name" and cust_id, respectively.
- Option E: ORDER BY "Last Name"This is correct because "Last Name" is a valid alias defined in the first SELECT clause.
The other options fail for the following reasons:
- Option B: "CUST_NO" is not recognized in the ORDER BY clause because it's not an alias used in the first SELECT statement.
- Option C: Incorrect because 2, cust_id mixes positional reference with a column name that doesn't apply to both SELECT statements consistently.
- Option D: ORDER BY CUST_NO fails because CUST_NO is not an alias in the first SELECT clause.
Which is true about the & and && prefixes with substitution variables?
Options:
& can prefix a substitution variable name only in queries. DML
An & prefix to an undefined substitution variable, which is referenced twice in the same query, will prompt for a value twice .
The && prefix will not prompt for a value even if the substitution variable is not previously defined in the session.
An && prefix to an undefined substitution variable, which is referenced multiple times in multiple queries, will prompt for a value once per query.
Both & and && can prefix a substitution variable name in queries and DML statements.
Answer:
EExplanation:
E. True. Both & and && can prefix substitution variables in queries as well as in DML statements. & is used for defining a substitution variable that prompts the user every time the variable is encountered. && is used for a persistent substitution variable that, once defined in the session, will not prompt the user again for a value if used subsequently.
Which two are true about rollbacks?
Options:
The ROLLBACK statement does not release locks resulting from table updates.
Data Control L anguage (DCL) statements, such as GRANT and REVOKE, can be rolled back.
A transaction interrupted by a system failure is automatically rolled back.
If the ROLLBACK statement is used without TO SAVEPOINT, then all savepoints in the transaction are deleted .
Data consistency is not guaranteed after a rollback.
Answer:
C, DExplanation:
C. True. A transaction that is interrupted by a system failure is automatically rolled back by Oracle to ensure data consistency. This is part of the ACID (Atomicity, Consistency, Isolation, Durability) properties that Oracle adheres to.
D. True. A ROLLBACK without specifying a savepoint rolls back the entire transaction and removes all savepoints within that transaction. This restores the data to the state it was in at the beginning of the transaction.
Examine this query:
SELECT SUBSTR (SYSDATE,1,5) ‘Result’ FROM DUAL
Which statement is true?
Options:
It fails unless the expression is modified to TO-CHAR(SUNBSTR(SYSDATE,1,5)
It fails unless the expression is modified to SUBSTR (TO_ CHAR(SYSDATE),1,5)
It fails unless the expression is modified to SUBSTR (TO_ CHAR(TRUNC(SYSDATE)),1,5)
It executes successfully with an implicit data type conversion
Answer:
BExplanation:
In Oracle Database 12c, the SYSDATE function returns a date value in the current session's date format. The SUBSTR function is used to extract a substring from a string. However, SYSDATE is a DATE data type and not a string, so you cannot directly use SUBSTR on it. Therefore, SYSDATE must first be converted to a character data type using the TO_CHAR function before applying the SUBSTR function.
Therefore, the correct form of the query should be:
SELECT SUBSTR(TO_CHAR(SYSDATE), 1, 5) AS "Result" FROM DUAL;
This converts the current date and time to a string using the default date format and then extracts the first 5 characters from it.
Evaluate these commands which execute successfully CREATE SEQUENCE ord_seq
INCREMENT BY 1
START WITH 1
MAXVALUE 100000
CYCLE
CACHE 5000;
Create table ord_items(
ord_no number(4) default ord_seq.nextval not null,
Item_no number(3),
Qty number(3),
Expiry_date date,
Constraint it_pk primary key(ord_no,item_no),
Constraint ord_fk foreign key (ord_no) references orders(ord_no));
Which two statements are true about the ORD_ITEMS table and the ORD_SEQ sequence?
Options:
Any user inserting rows into table ORD_ITEMS must have been granted access to sequence ORD_SEQ.
Column ORD_NO gets the next number from sequence ORD_SEQ whenever a row is inserted into ORD_ITEMS and no explicit value is given for ORD_NO.
Sequence ORD_SEQ cycles back to 1 after every 5000 numbers and can cycle 20 times
IF sequence ORD_SEQ is dropped then the default value for column ORD_NO will be NULL for rows inserted into ORD_ITEMS.
Sequence ORD_SEQ is guaranteed not to generate duplicate numbers.
Answer:
B, DExplanation:
Sequences and default values in Oracle play a crucial role in providing unique values for table columns.
- Statement B is correct: When a row is inserted into ORD_ITEMS without an explicit value for ORD_NO, the ORD_NO column gets the next number from the ORD_SEQ sequence due to the DEFAULT ord_seq.nextval clause.
- Statement D is correct: If the ORD_SEQ sequence is dropped, Oracle would not be able to get the next value for ORD_NO from ORD_SEQ, and unless another default is specified, the default for ORD_NO would be NULL.
- Statements A, C, and E are incorrect for the following reasons:
Examine this incomplete query:
SELECT DATA’2019-01-01’+
FROM DUAL;
Which three clauses can replace
Options:
INTERVAL ‘12:00’
INTERVAL’0,5’DAY
INTERVAL’12’ HOUR
INTERVAL’720’MINUTE
INTERVAL’0 12’DAY TO HOUR
INTERVAL’11:60’HOUR TO MINUTE
Answer:
C, D, FExplanation:
In Oracle SQL, adding hours to a date can be done using the INTERVAL keyword with appropriate clauses:
- Option C: INTERVAL '12' HOUR
- Option D: INTERVAL '720' MINUTE
- Option F: INTERVAL '11:60' HOUR TO MINUTE
Options A, B, and E contain incorrect syntax or do not match the required addition of 22 hours as specified in the question.
You create a table by using this command:
CREATE TABLE rate_list (rate NUMBER(6,2));
Which two are true about executing statements?
Options:
INSERT INTO rate_list VALUES (-.9) inserts the value as -.9.
INSERT INTO rate_list VALUES (0.999) produces an error.
INSERT INTO rate_list VALUES (-10) produces an error.
INSERT INTO rate_list VALUES (87654. 556) inserts the value as 87654.6.
INSERT INTO rate_list VALUES (0.551) inserts the value as .55.
INSERT INTO rate_list VALUES (-99.99) inserts the value as 99.99.
Answer:
A, EExplanation:
The behavior of data insertion into a table with a specific numeric format in Oracle Database 12c can be explained as follows:
- A. INSERT INTO rate_list VALUES (-.9) inserts the value as -.9: This is correct. The value -.9 is within the precision defined by the table column (NUMBER(6,2)), where 6 is the total number of digits (including both sides of the decimal point), and 2 is the number of digits after the decimal point.
- E. INSERT INTO rate_list VALUES (0.551) inserts the value as .55: Oracle rounds the number to the nearest value that fits the specified scale of 2. Thus, 0.551 rounds down to 0.55.
References:
- Oracle Database SQL Language Reference 12c, particularly sections on data types and numeric precision.
You execute this command:
TRUNCATE TABLE depts;
Which two are true?
Options:
It retains the indexes defined on the table.
It drops any triggers defined on the table.
A Flashback TABLE statement can be used to retrieve the deleted data.
It retains the integrity constraints defined on the table.
A ROLLBACK statement can be used to retrieve the deleted data.
It always retains the space used by the removed rows
Answer:
A, DExplanation:
The TRUNCATE TABLE command in Oracle SQL is used to quickly delete all rows from a table:
- Option A:
- Option D:
Options B, C, E, and F are incorrect because:
- Option B: TRUNCATE does not drop triggers; it only removes all rows.
- Option C: Flashback Table cannot be used after a TRUNCATE because TRUNCATE is a DDL operation that does not generate undo data for flashback.
- Option E: A ROLLBACK cannot be used after a TRUNCATE because TRUNCATE is a DDL command that implicitly commits.
- Option F: TRUNCATE may deallocate the space used by the table, depending on the database version and specific options used with the TRUNCATE command.
Which two will execute successfully?
Options:
SELECT COALESCR('DATE', SYSDATE) FROM DUAL;
SELECT NVL('DATE',SYSDATE) FROM DUAL;
SELECT COALESCE(O,SYSDATE) TRCH DUAL;
SELECT NVL('DATE',200) FROM (SELECT NULL AS “DATE” FROM DUAL);
SELECT COALESCE('DATE',SYSDATE) FROM (SELECT NULL AS “DATE” FROM DUAL) ;
Answer:
DExplanation:
D. True. The NVL function can replace a NULL value with a specified value, and it does not require the data types to match exactly, allowing implicit conversion where possible. Here, 'DATE' is a string literal, and 200 is a number, and since the selected column is NULL, NVL will return 200.
The other options are incorrect because the COALESCE function requires all arguments to be of the same data type or at least compatible types that Oracle can implicitly convert. In A and E, the use of COALESCE with a string literal 'DATE' and SYSDATE (which is a date type) is not compatible without explicit conversion. Option C has a typo (TRCH instead of FROM) and is mixing data types incorrectly.
Examine the data in the CUST_NAME column of the CUSTOMERS table:
CUST_NAME
---------------------
Renske Ladwig
Jason Mallin
Samuel McCain
Allan MCEwen
Irene Mikkilineni
Julia Nayer
You want to display the CUST_NAME values where the last name starts with Mc or MC.
Which two WHERE clauses give the required result?
Options:
WHERE UPPER(SUBSTR(cust_name, INSTR(cust_name,’ ’) + 1)) LIKE UPPER('MC%')
WHERE SUBSTR(cust_name, INSTR(cust_name,’ ’) + 1) LIKE 'Mc%’ OR 'MC%’
WHERE INITCAP(SUBSTR(cust_name, INSTR(cust_name,’ ’) + 1)) IN (‘MC%’,’Mc%’)
WHERE INITCAP(SUBSTR(cust_name, INSTR(cust_name,’ ') + 1)) LIKE ‘Mc%’
WHERE SUBSTR(cust_name, INSTR(cust_name,’ ‘) + 1) LIKE ‘Mc%’
Answer:
A, EExplanation:
To find customer names where the last name starts with Mc or MC, the correct queries are:
- A. WHERE UPPER(SUBSTR(cust_name, INSTR(cust_name, ' ') + 1)) LIKE 'MC%'This query converts the substring of cust_name that comes after the first space (which should correspond to the last name) to uppercase and checks if it starts with 'MC', which will match both 'Mc' and 'MC'.
- E. WHERE SUBSTR(cust_name, INSTR(cust_name, ' ') + 1) LIKE 'Mc%'This query checks if the substring of cust_name after the first space starts with 'Mc'. However, this query will only match last names that start with 'Mc' and not 'MC' unless the database is using a case-insensitive collation.
Options B, C, and D are incorrect:
- B is incorrect because the syntax is not valid in Oracle SQL; the LIKE clause cannot be used to match multiple patterns in that way.
- C is incorrect because INITCAP would not only capitalize the first letter of 'mc' or 'Mc' but would lowercase all other letters, which is not the intended action.
- D is incorrect because, like option C, INITCAP is not the appropriate function for this use case and it will not correctly identify names that start with 'MC'.
Examine the data in the ENPLOYEES table:
Which statement will compute the total annual compensation tor each employee?
Options:
SECECT last_namo, (menthy_salary + monthly_commission_pct) * 12 AS annual_comp
FROM employees;
SELCECT last_namo, (monthly_salary * 12) + (monthly_commission_pct * 12) AS annual_comp
FROM employees
SELCECT last_namo, (monthly_salary * 12) + (menthy_salary * 12 * NVL
(monthly_commission_pct, 0)) AS annual_comp FROM employees
SELCECT last_namo, (monthly_salary * 12) + (menthy_salary * 12 * monthly_commission_pct)
AS annual_comp FROM employees
Answer:
CExplanation:
The correct statement for computing the total annual compensation for each employee is option C. This is because the monthly commission is a percentage of the monthly salary (indicated by the column name MONTHLY_COMMISSION_PCT). To calculate the annual compensation, we need to calculate the annual salary (which is monthly_salary * 12) and add the total annual commission to it.
Here's the breakdown of the correct statement, option C:
- (monthly_salary * 12) computes the total salary for the year.
- NVL(monthly_commission_pct, 0) replaces NULL values in the monthly_commission_pct column with 0, ensuring that the commission is only added if it exists.
- (monthly_salary * 12 * NVL(monthly_commission_pct, 0)) computes the annual commission by first determining the monthly commission (which is a percentage of the monthly salary), and then multiplying it by 12 to get the annual commission.
- Finally, (monthly_salary * 12) + (monthly_salary * 12 * NVL(monthly_commission_pct, 0)) adds the annual salary and the annual commission to get the total annual compensation.
The other options are incorrect:
- Option A is incorrect because it adds the monthly_commission_pct directly to the monthly_salary, which does not consider that monthly_commission_pct is a percentage.
- Option B is incorrect because it adds the commission percentage directly without first applying it to the monthly salary.
- Option D is incorrect because it does not handle the NULL values in the commission column, which would result in a NULL total annual compensation whenever the monthly_comission_pct is NULL.
References:
- Oracle Documentation on NVL function: NVL
- Oracle Documentation on Numeric Literals: Numeric Literals
Examine the description of the PRODUCTS table:
Which two statements execute without errors?
Options:
MERGE INTO new_prices n
USING (SELECT * FROM products) p
WHEN MATCHED THEN
UPDATE SET n.price= p.cost* 01
WHEN NOT MATCHED THEN
INSERT(n.prod_id, n.price) VALUES(p.prod_id, cost*.01)
WHERE(p.cost<200);
MERGE INTO new_prices n
USING (SELECT * FROM products WHERE cost>150) p
ON (n.prod_id= p.prod_id)
WHEN MATCHED THEN
UPDATE SET n.price= p.cost*.01
DELETE WHERE (p.cost<200);
MERGE INTO new_prices n
USING products p
ON (p.prod_id =n.prod_id)
WHEN NOT MATCHED THEN
INSERT (n.prod _id, n.price) VALUES (p.prod_id, cost*.01)
WHERE (p.cost<200);
MERGE INTO new_prices n
USING (SELECT * FROM products WHERE cost>150) p
ON (n.prod_id= p.prod_id)
WHEN MATCHED THEN
DELETE WHERE (p.cost<200)
Answer:
BExplanation:
B: True. This MERGE statement should execute without errors. It uses a conditionally filtered selection from the products table as a source to update or delete rows in the new_prices table based on whether the prod_id matches and the cost is greater than 150. The delete operation within a MERGE statement is allowed in Oracle when a WHEN MATCHED clause is specified.
The MERGE statement is correctly structured with a USING clause that includes a subquery with a valid WHERE condition, an ON condition that specifies how to match rows between the source and the target, and a WHEN MATCHED THEN clause that specifies the update and delete operations based on the cost condition.
References:Oracle SQL documentation specifies that within a MERGE statement, you can specify a WHEN MATCHED clause to update and/or delete rows in the target table based on the condition specified after the DELETE keyword.
Which three are key components of an Entity Relationship Model?
Options:
a table
an attribute
a unique identifier
an activity
a relationship
an entity
Answer:
B, E, FExplanation:
Key components of an Entity-Relationship Model (ERM) include:
- B. an attribute: Attributes are properties or characteristics of an entity, such as a person's name, date of birth, etc., and are essential in describing the data aspects of an entity in an ER model.
- E. a relationship: Relationships describe how entities interact with each other within the database structure, such as a customer placing an order.
- F. an entity: Entities are the key components of an ER model, representing objects or things within the domain that have a distinct existence, like 'Customer' or 'Order'.
Incorrect options:
- A: A table is a database structure used to implement an entity in relational databases, not a component of the ER model itself.
- C: While unique identifiers are crucial in database implementation (typically as primary keys), they are a specific attribute type, not a general component of ER models.
- D: An activity is not a component of an ER model; activities relate more to process models or behavioral models in systems design.
Which two are true about constraints?
Options:
Constraints are enforced only during INSERT operations.
A column with a foreign key constraint can never contain a null value.
All constraints can be defined at the table or column level.
A constraint can be disabled even if the constrained column contains data.
A column with a UNIQUE constraint can contain a NULL value.
Answer:
D, EExplanation:
A. False. Constraints are enforced during INSERT and UPDATE operations, and by the nature of their definition, they impact DELETE operations as well (in the case of referential constraints).
B. False. A column with a foreign key constraint can contain a NULL value unless it is also constrained to be NOT NULL.
C. False. Not all constraints can be defined at the column level. For example, some constraints such as FOREIGN KEY constraints are more commonly defined at the table level.
D. True. A constraint can be disabled regardless of whether the constrained column contains data. However, re-enabling the constraint requires that all data satisfy the constraint rules.
E. True. A column with a UNIQUE constraint can indeed contain a NULL value, as NULL is considered not equal to any value, including itself. This means that multiple rows with NULL values do not violate the UNIQUE constraint.
References:
- Oracle Documentation on Constraints: https://docs.oracle.com/database/121/SQLRF/clauses002.htm#SQLRF52271
- Oracle Documentation on Enabling and Disabling Constraints: https://docs.oracle.com/database/121/ADMIN/clustrct.htm#ADMIN13508
Which two are true about multiple table INSERT statements?
Options:
They always use subqueries.
They can transform a row from a source table into multiple rows in a target table.
The conditional INSERT FIRST statement always inserts a row into a single table.
The conditional INSERT ALL statement inserts rows into a single table by aggregating source rows.
The unconditional INSERT ALL statement must have the same number of columns in both the source and target tables.
Answer:
B, EExplanation:
B: True. Multiple table insert statements, specifically the conditional INSERT ALL, can transform a single row from the source table into multiple rows in one or more target tables depending on the conditions specified in the WHEN clauses.
E: True. The unconditional INSERT ALL statement will insert rows into multiple target tables without any conditions. However, it does not require the same number of columns in both the source and target tables. The INSERT ALL syntax allows you to specify different columns for each target table into which rows will be inserted.
Multiple table insert operations allow for complex insert scenarios, where based on the data, one can insert into different tables or multiple times into the same table based on different conditions.
References:Oracle SQL reference details the use of INSERT ALL and INSERT FIRST clauses for inserting into multiple tables based on conditions specified.
Which three privileges can be restricted to a subset of columns in a table?
Options:
ALTER
REFERENCES
UPDATE
SELECT
INDEX
INSERT
DELETE
Answer:
B, C, FExplanation:
B: True. The REFERENCES privilege can be granted on specific columns within a table. This is necessary when a user needs to define foreign key constraints that reference those particular columns.
C: True. The UPDATE privilege can be granted on specific columns, allowing users to update only designated columns within a table. This is useful for restricting write access to sensitive or critical data within a table.
F: True. The INSERT privilege can also be granted on specific columns, meaning a user can be permitted to insert data into only certain columns of a table. This helps in maintaining data integrity and controlling access to data fields based on user roles.
Which two are true about granting object privileges on tables, views, and sequences?
Options:
DELETE can be granted on tables, views, and sequences.
REFERENCES can be grantrd only on tables.
INSERT can be granted only on tables and sequences.
SELECT can be granted on tables, views, and sequences.
ALTER can be granted only on tables and sequences.
Answer:
B, DExplanation:
Object privileges applicable to tables, views, and sequences in Oracle are:
B. REFERENCES can be granted only on tables. It allows the grantee to create a foreign key that refers to the table.
D. SELECT can be granted on tables and views. This allows the grantee to perform a SELECT on the table or view.
A, C, and E are incorrect. Specifically:
- A is incorrect because DELETE cannot be granted on sequences; it is a privilege applicable to tables and views.
- C is incorrect because INSERT cannot be granted on sequences; INSERT is applicable only to tables and views.
- E is incorrect because ALTER is a privilege applicable to tables and indexes, not sequences.
References:
- Oracle Database SQL Language Reference, 12c Release 1 (12.1): "GRANT"
Examine the description of the PROMOTIONS TABLE:
You want to display the unique is promotion costs in each promotion category.
Which two queries can be used?
Options:
SELECT DISTINCT promo_category, promo_cost FROM promotions ORDER BY 1;
SELECT promo_cost, promo_category FROM promotions ORDER BY 1
SELECT promo_category, DISTINCT promo_cost FROM promotiong ORDER BY 2:
select DISTINCT promo_categoryIl ‘has’||promol_cost as COSTS FROM promotions ORDER BY 1:
SELECT DISTINCT promo_cost ||’in’IIDISTINCT promo_category promotions ORDER BY1:
Answer:
A, DExplanation:
For displaying unique promotion costs in each promotion category from the PROMOTIONS table:
- A. SELECT DISTINCT promo_category, promo_cost FROM promotions ORDER BY 1: This query correctly retrieves unique combinations of promo_category and promo_cost, sorting the results based on the promo_category.
- D. SELECT DISTINCT promo_category || ' has ' || promo_cost AS COSTS FROM promotions ORDER BY 1: This query correctly combines the category and cost into a single string for each unique combination, using string concatenation and the DISTINCT keyword to ensure uniqueness, sorting by the concatenated string.
Incorrect options:
- B: This does not ensure that the combinations of promo_cost and promo_category are unique because DISTINCT was not specified for both columns together.
- C: The syntax is incorrect; DISTINCT cannot be applied to a single column partway through a SELECT clause.
- E: This is syntactically incorrect as DISTINCT cannot be used twice in the way shown; it must apply to all columns if used at the beginning of a SELECT statement.
Which three are true about granting object privileges on tables, views, and sequences?
Options:
UPDATE can be granted only on tables and views.
DELETE can be granted on tables, views, and sequences.
REFERENCES can be granted only on tables and views.
INSERT can be granted on tables, views, and sequences.
SELECT can be granted only on tables and views.
ALTER can be granted only on tables and sequences.
Answer:
C, E, FExplanation:
In Oracle Database, object privileges are rights to perform a particular action on a specific object in the database. Here's why the other options are incorrect:
A. UPDATE can be granted on tables, views, and materialized views, but not sequences. B. DELETE cannot be granted on sequences because sequences do not store data that can be deleted. D. INSERT cannot be granted on sequences; sequences are used to generate numbers, not to be inserted into directly. C. REFERENCES allows the grantee to create a foreign key that references the table or the columns of the table. It is applicable only to tables and views. E. SELECT can indeed only be granted on tables and views (including materialized views). F. ALTER is an object privilege that can be granted on tables and sequences but not views.
For more details, one may refer to the Oracle Database SQL Language Reference documentation, which specifies the types of object privileges and the objects they apply to.
Which two statements about INVISIBLE indexes are true?
Options:
an INVISIBLE Index consumes no storage
You can only create one INVISIBLE index on the same column list
The query optimizer never considers INVISIBLE Indexes when determining execution plans
You use AlTER INDEX to make an INVISIBLE Index VISIBLE
All INSERT, UPDATE, and DELETE statements maintain entries in the index
Answer:
D, EExplanation:
INVISIBLE indexes are a feature in Oracle Database 12c and later versions that allow an index to be maintained but not used by the optimizer unless explicitly hinted.
A. False. An INVISIBLE index still consumes storage space as it is maintained in the background.
B. False. There is no such restriction. You can create multiple INVISIBLE indexes on the same column list.
C. False. The optimizer can consider INVISIBLE indexes if they are hinted at in the query.
D. True. You can alter the visibility of an index using the ALTER INDEX command to make an INVISIBLE index VISIBLE.
E. True. Even though they are invisible to the optimizer by default, all DML operations such as INSERT, UPDATE, and DELETE continue to maintain the index as they would with a VISIBLE index.
Examine the data in the CUST NAME column of the CUSTOMERS table:
CUST_NAME
------------------------------
Renske Ladwig
Jason Mallin
Samuel McCain
Allan MCEwen
Irene Mikkilineni
Julia Nayer
You want to display the CUST_NAME values where the last name starts with Mc or MC. Which two WHERE clauses give the required result?
Options:
WHERE INITCAP (SUBSTR(cust_name, INSTR(cust_name,'') +1)) IN ('MC%','Mc%)
WHERE UPPER (SUBSTR(cust_name, INSTR(cust_name, '') +1)) LIKE UPPER('MC%')
WHERE INITCAP(SUBSTR(cust_name, INSTR(cust_name,'') +1)) LIKE'Mc%'
WHERE SUBSTR(cust_name,INSTR(cust_name,'') +1) LIKE'Mc%' OR'MC%'
WHERE SUBSTR(cust_name, INSTR(cust_name,'') +1) LIKE'Mc%'
Answer:
B, CExplanation:
To find customers whose last names start with "Mc" or "MC", we need to ensure our SQL query correctly identifies and compares these prefixes regardless of case variations. Let's analyze the given options:
- Option B: WHERE UPPER(SUBSTR(cust_name, INSTR(cust_name, ' ') + 1)) LIKE UPPER('MC%')This clause uses UPPER to convert both the extracted substring (starting just after the first space, assuming it indicates the start of the last name) and the comparison string 'MC%' to uppercase. This ensures case-insensitive comparison. The LIKE operator is used to match any last names starting with "MC", which will correctly capture both "Mc" and "MC". This option is correct.
- Option C: WHERE INITCAP(SUBSTR(cust_name, INSTR(cust_name, ' ') + 1)) LIKE 'Mc%'This clause applies INITCAP to the substring, which capitalizes the first letter of each word and makes other letters lowercase. The result is compared to 'Mc%', assuming only the last name follows the space. This approach will match last names starting with "Mc" (like "McEwen"), but not "MC". However, considering we're looking for "Mc" specifically, this clause works under the assumption that "Mc" is treated as proper capitalization for these last names. Thus, it can also be considered correct, albeit less inclusive than option B.
The other options either use incorrect syntax or apply case-sensitive matches without ensuring that both "Mc" and "MC" are captured:
- Option A: Contains syntax errors (unmatched quotes and wrong use of IN).
- Option D: Uses case-sensitive match without combining both "Mc" and "MC".
- Option E: Only matches "Mc", which is too specific.
Examine these statements executed in a single Oracle session:
CREATE TABLE product (pcode NUMBER(2),pname VARCHAR2(20));
INSERT INTO product VALUES(1,'pen');
INSERT INTO product VALUES (2,'pencil');
INSERT INTO product VALUES(3,'fountain pen');
SAVEPOINT a;
UPDATE product SET pcode=10 WHERE pcode =1;
COMMIT;
DELETE FROM product WHERE pcode =2;
SAVEPOINT b;
UPDATE product SET pcode=30 WHERE pcode =3;
SAVEPOINT c;
DELETE FROM product WHERE pcode =10;
ROLLBACK TO SAVEPOINT b;
COMMIT;
Which three statements are true?
Options:
The code for pen is 10.
There is no row containing fountain pen.
There is no row containing pencil.
The code for pen is 1.
The code for fountain pen is 3
There is no row containing pen
Answer:
A, C, FExplanation:
- After creation and initial inserts, the pcode for 'pen' is updated to 10, and then committed.
- The 'pencil' row is deleted and not yet committed.
- A savepoint b is set after the deletion of the 'pencil' row.
- The 'fountain pen' pcode is updated to 30, followed by setting savepoint c.
- The 'pen' row (now with pcode 10) is deleted.
- A rollback to savepoint b reverts the deletion of 'pen' and the update to 'fountain pen', but not the deletion of 'pencil', which was committed earlier due to the scope of the savepoint.
- Therefore, after the final commit:
Which two statements are true about conditional INSERT ALL?
Options:
Each row returned by the subquery can be inserted into only a single target table.
It cannot have an ELSE clause.
The total number of rows inserted is always equal to the number of rows returned by the subquery
A single WHEN condition can be used for multiple INTO clauses.
Each WHEN condition is tested for each row returned by the subquery.
Answer:
D, EExplanation:
For conditional INSERT ALL in Oracle Database 12c:
- D. A single WHEN condition can be used for multiple INTO clauses. This is true. A single WHEN condition in a multi-table insert can direct the insertion of a single row source into multiple target tables.
- E. Each WHEN condition is tested for each row returned by the subquery. True, each row from the subquery is evaluated against each WHEN condition to determine into which table(s) the row should be inserted.
Options A, B, and C are incorrect:
- A is incorrect because a row can indeed be directed into multiple tables based on the conditions.
- B is incorrect as INSERT ALL can include an ELSE clause to handle rows that do not meet any of the specified conditions.
- C is incorrect because not every row from the subquery necessarily results in a row insertion; it depends on the conditions being met.
The INVOICE table has a QTY_SOLD column of data type NUMBER and an INVOICE_DATE column of data type DATE NLS_DATE_FORMAT is set to DD-MON-RR.
Which two are true about data type conversions involving these columns in query expressions?
Options:
invoice_date> '01-02-2019': uses implicit conversion
qty_sold ='05549821 ': requires explicit conversion
CONCAT(qty_sold, invoice_date): requires explicit conversion
qty_sold BETWEEN '101' AND '110': uses implicit conversion
invoice_date = '15-march-2019': uses implicit conversion
Answer:
A, EExplanation:
The statements regarding data type conversions and the treatment of literals in SQL expressions involve understanding implicit and explicit data conversions in Oracle SQL.
- Statement A is true as invoice_date > '01-02-2019' involves an implicit conversion of the string literal to a date type, based on the NLS_DATE_FORMAT setting, assuming the format matches.
- Statement E is true because, similarly to A, invoice_date = '15-march-2019' involves an implicit conversion where the string is automatically converted to a date type according to the Oracle NLS_DATE_FORMAT or an assumed default date format.
- Statements B, C, and D involve incorrect or misleading information:
Examine the description of the PRODCTS table which contains data:
Which two are true?
Options:
The PROD ID column can be renamed.
The PROD_ ID column data type can be changed to VARCHAR2 (2).
The EXPIRY DATE column data type can be changed to TIME STAMP.
The EXPIRY DATE column cannot be dropped.
The PROD NAME column cannot have a DEFAULT clause added to it.
Answer:
A, CExplanation:
- A: True, the name of a column can be changed in Oracle using the ALTER TABLE ... RENAME COLUMN command.
- B: False, you cannot change a column's data type from NUMBER to VARCHAR2 if the table contains data, unless the change does not result in data loss or inconsistency.
- C: True, it is possible to change a DATE data type column to TIMESTAMP because TIMESTAMP is an extension of DATE that includes fractional seconds. This operation is allowed if there is no data loss.
- D: False, any column that is not part of a primary key or does not have a non-deferrable constraint can generally be dropped unless it contains data that does not allow for such a change.
- E: False, the DEFAULT clause can be added to a column provided there is no data that contradicts the default value or it doesn't violate any constraints.
These statements are verified against the Oracle Database 12c SQL documentation, specifically the sections on data types, the ALTER TABLE command, and the use of literals in SQL expressions.
You execute this command:
TRUNCATE TABIE depts;
Which two are true?
Options:
A ROLLBACK statement can be used to retrieve the deleted data.
It drops any triggers defined on the table.
It retains the indexes defined on the table.
It retains the integrity constraints defined on the table,
It always retains the space used by the removed rows.
A FLASHBACK TABLE statement can be used to retrieve the deleted data.
Answer:
C, DExplanation:
When the TRUNCATE TABLE command is used:
- C. It retains the indexes defined on the table. This is true. The TRUNCATE TABLE operation does not drop the indexes on the table; it only removes all rows from the table.
- D. It retains the integrity constraints defined on the table. This is correct. The TRUNCATE TABLE operation does not affect the integrity constraints; it retains them.
Options A, B, E, and F are incorrect:
- A is incorrect because the TRUNCATE TABLE operation cannot be rolled back as it is a DDL operation and not a DML operation like DELETE.
- B is incorrect because TRUNCATE TABLE does not drop any triggers; they remain in place.
- E is incorrect as TRUNCATE TABLE may or may not release the space depending on whether the REUSE STORAGE clause is used.
- F is incorrect because FLASHBACK TABLE cannot be used to retrieve data after a TRUNCATE TABLE operation since it does not generate redo logs that FLASHBACK relies upon.
which three statements are true about indexes and their administration in an Oracle database?
Options:
The same table column can be part of a unique and non-unique index
A DESCENDING INDEX IS A type of function-based index
A DROP INDEX statement always prevents updates to the table during the drop operation
AN INVISIBLE INDEX is not maintained when DML is performed on its underlying table.
AN INDEX CAN BE CREATED AS part of a CREATE TABLE statement
IF a query filters on an indexed column then it will always be used during execution of query
Answer:
A, D, EExplanation:
A. True, a single table column can be included in both a unique index and a non-unique index, provided they are different indexes.
D. True, an invisible index is maintained during DML operations, which means it is updated when insert, update, or delete operations are performed on the table. However, it is not used by the optimizer by default for query execution unless explicitly hinted or the session is altered to consider invisible indexes.
E. True, an index can be specified in the CREATE TABLE statement using the INDEX clause to create an index on a specific column at the time of table creation.
B, C, and F are not correct: B. A descending index is simply an index that is sorted in descending order, not a type of function-based index. C. A DROP INDEX
Which three statements are true regarding single row subqueries?
Options:
They must be placed on the left side of the comparison operator or condition.
They must return a row to prevent errors in the SQL statement.
A SQL statement may have multiple single row subquery blocks.
They can be used in the HAVING clause.
They must be placed on the right side of the comparison operator or condition.
They can be used in the clause.
Answer:
C, D, EExplanation:
C: True. A SQL statement may include multiple single row subqueries in different parts of the statement, such as in the SELECT list, WHERE clause, or HAVING clause. Each subquery must independently satisfy the requirement of returning a single row to avoid runtime errors.
D: True. Single row subqueries can be used in the HAVING clause. This allows for filtering groups based on conditions evaluated against individual or aggregated values returned by the subquery. The subquery must return a single value to be valid in this context.
E: True. Single row subqueries are often placed on the right side of the comparison operator in a SQL condition. This positioning is typical because the left side often references a column or an expression related to the main query, while the subquery on the right side dynamically provides a value for comparison.
The ORDERS table has a column ORDER_DATE of date type DATE The default display format for a date is DD-MON-RR
Which two WHERE conditions demonstrate the correct usage of conversion functions?
Options:
WHERE ordet_date> TO_CHAR(ADD_MONTHS(SYSDATE, 6),'MON DD YYYY')
WHERE TO_CHAR(order_date,'MON DD YYYY') ='JAN 20 2019';
WHERE order_date> TO_DATE('JUL 10 2018','MON DD YYYY');
WHERE order_date IN (TO_DATE ('Oct 21 2018','MON DD YYYY'), TO_CHAR('Nov 21 2018','MON DD YYYY'));
WHERE order_date> TO_DATE(ADD_MONTHS(SYSDATE,6),'MON DD YYYY');
Answer:
CExplanation:
In SQL, the correct usage of conversion functions is crucial when performing operations on dates. Oracle uses the TO_DATE function to convert a string to a date, and the TO_CHAR function to convert dates or numbers to strings.
- Statement C is correct: WHERE order_date > TO_DATE('JUL 10 2018','MON DD YYYY'); is a proper use of the TO_DATE function. It converts the string 'JUL 10 2018' to a date type, with the format 'MON DD YYYY', which is then used to compare with the order_date.
- Statements A, B, D, and E are incorrect or misuse conversion functions:
Which two are true about using constraints?
Options:
A FOREIGN KEY column in a child table and the referenced PRIMARY KEY column in the parenttable must have the same names.
A table can have multiple PRIMARY KEY and multiple FOREIGN KEY constraints.
A table can have only one PRIMARY KEY and one FOREIGN KEY constraint.
PRIMARY KEY and FOREIGNY constraints can be specified at the column and at the table level
A table can have only one PRIMARY KEY but may have multiple FOREIGN KEY constraints.
NOT NULL can be specified at the column and at the table level.
Answer:
D, EExplanation:
In Oracle Database 12c, it is important to understand the behavior and properties of constraints.
A. This statement is false. A FOREIGN KEY column in a child table does not need to have the same name as the referenced PRIMARY KEY column in the parent table. What is required is that the data type is the same and that the values in the FOREIGN KEY column correspond to values in the PRIMARY KEY column of the parent table.
B. This statement is false. A table cannot have multiple PRIMARY KEY constraints. By definition, a PRIMARY KEY is a unique identifier for a row in a table, and there can only be one such identifier.
C. This statement is false for the same reasons as B; a table can have only one PRIMARY KEY. However, it can have multiple FOREIGN KEY constraints that reference PRIMARY KEYS in other tables.
D. This is true. PRIMARY KEY and FOREIGN KEY constraints can indeed be specified at the column level with the column definition or at the table level with the ALTER TABLE statement.
E. This is true. A table can have only one PRIMARY KEY constraint because it defines a unique row identifier. However, it can have multiple FOREIGN KEY constraints referencing keys in other tables, allowing for complex relational structures.
F. This statement is false. NOT NULL constraints are always defined at the column level, as they apply to individual columns. They cannot be specified at the table level.
References:
- Oracle Documentation on Constraints: https://docs.oracle.com/database/121/SQLRF/clauses002.htm#SQLRF52271
- Oracle Documentation on NOT NULL Constraints: https://docs.oracle.com/database/121/SQLRF/clauses002.htm#SQLRF52162
Which two are true about queries using set operators (UNION, UNION ALL, INTERSECT and MINUS)?
Options:
There must be an equal number of columns in each SELECT list.
The name of each column in the first SELECT list must match the name of the corresponding column in each subsequent SELECT list.
Each SELECT statement in the query can have an ORDER BY clause.
None of the set operators can be used when selecting CLOB columns.
The FOR UPDATE clause cannot be specified.
Answer:
A, EExplanation:
A. True. When using set operators, the number and order of columns must be the same in all SELECT statements involved in the query. The data types of those columns must also be compatible.
E. True. The FOR UPDATE clause cannot be specified in a subquery or a SELECT statement that is combined with another SELECT statement by using a set operator.
B is incorrect because the column names do not need to match; only the number and data types of the columns must be compatible. C is incorrect because only the final SELECT statement in the sequence of UNION/INTERSECT/MINUS operations can have an ORDER BY clause. D is incorrect because, as of Oracle 12c, UNION ALL can be used with CLOB columns, but UNION, INTERSECT, and MINUS cannot.
Which two statements are true about selecting related rows from two tables based on entity relationship diagram (ERD)?
Options:
Relating data from a table with data from the same table is implemented with a self join.
An inner join relates rows within the same table.
Rows from unrelated tables cannot be joined.
Implementing a relationship between two tables might require joining additional tables.
Every relationship between the two tables must be implemented in a Join condition.
Answer:
A, DExplanation:
Understanding the functionality of SQL joins and their application in a relational database:
- Option A: Correct. A self join is used to relate or compare rows within the same table. It typically involves using table aliases to distinguish the different instances of the table in the query.
- Option B: Incorrect. An inner join relates rows between two different tables based on a common condition, not within the same table.
- Option C: Incorrect. SQL allows joining of rows from any tables, whether directly related by foreign keys or not, as long as there is a logical condition that can relate their columns.
- Option D: Correct. Sometimes establishing a relationship between two specific tables might require joining through one or more intermediary tables, particularly in cases involving complex relationships or normalization.
- Option E: Incorrect. While joins are often used to implement relationships, not every logical relationship necessitates a join condition, especially if data from only one table is required or if multiple relations are possible but not relevant to the specific query.
You execute this command:
TRUNCATE TABLE dept;
Which two are true?
Options:
It drops any triggers defined on the table.
It retains the indexes defined on the table.
It retains the integrity constraints defined on the table.
A ROLLBACK statement can be used to retrieve the deleted data.
It always retains the space used by the removed rows.
A FLASHBACK TABLE statement can be used to retrieve the deleted data.
Answer:
B, CExplanation:
When using the TRUNCATE TABLE command in Oracle, several aspects of the table's structure and associated database objects are impacted. Here's an explanation of each option:
- A: Incorrect. TRUNCATE TABLE does not drop triggers associated with the table; they remain defined.
- B: Correct. Indexes on the table are retained and not dropped when you truncate a table. However, if the index is a domain index, it may be dropped depending on its type.
- C: Correct. Integrity constraints such as primary keys, foreign keys, etc., are retained unless they are on a disabled state where truncation can lead to constraint being dropped.
- D: Incorrect. A TRUNCATE TABLE operation cannot be rolled back. It is a DDL (Data Definition Language) operation and commits automatically.
- E: Incorrect. The TRUNCATE TABLE operation deallocates the space used by the data unless the REUSE STORAGE clause is specified.
- F: Incorrect. TRUNCATE TABLE operation removes all the rows in a table and does not log individual row deletions, thus FLASHBACK TABLE cannot be used to retrieve the data.
Which three statements are true about views in an Oracle database?
Options:
A SELECT statement cannot contain a where clause when querying a view containing a WHERE clause in its defining query
Rows inserted into a table using a view are retained in the table if the view is dropped
Views can join tables only if they belong to the same schema.
Views have no segment.
Views have no object number.
A view can be created that refers to a non-existent table in its defining query.
Answer:
B, D, FExplanation:
A view is a virtual table based on a SQL query.
A. This is incorrect because a SELECT statement querying a view can contain a WHERE clause, regardless of the view’s defining query. C. This is incorrect because views can join tables from different schemas, not just the same schema. B. Correct. The rows inserted into a base table via a view remain in the table even if the view is dropped because the view is just a window to the data in the base tables. D. Correct. Views do not require storage space other than for the definition of the view in the data dictionary, hence they have no segment. E. Incorrect. Views do not have object numbers because they are not database objects that occupy physical space. F. Correct. You can create a view that references non-existent tables; such a view would be considered invalid until the base table is created.
The Oracle Database Concepts guide provides information about views and their characteristics.
Which three statements are true about performing DML operations on a view with no INSTEAD OF triggers defined?
Options:
Insert statements can always be done on a table through a view.
The WITH CHECK clause has no effect when deleting rows from the underlying table through the view.
Delete statements can always be done on a table through a view.
Views cannot be used to add rows to an underlying table If the table has columns with NOT NULL constraints lacking default values which are not referenced in the defining query of the view.
Views cannot be used to query rows from an underlying table if the table has a PRIMARY KEY and the primary key columns are not referenced in the defining query of the view.
Views cannot be used to add or modify rows in an underlying table If the defining query of the view contains the DISTINCT keyword.
Answer:
D, FExplanation:
- A: Insert statements can be done through a view only if all NOT NULL constraints without default values of the base table are included in the view. Therefore, statement A is incorrect.
- B: The WITH CHECK OPTION ensures that all DML operations performed through the view result in data that conforms to the view’s defining query. It affects DELETE as well as other DML operations, making statement B incorrect.
- C: Similar to inserts, DELETE operations can be done through a view unless the view contains constructs that inherently do not support it, such as certain joins or set operations. Statement C is generally incorrect.
- D: If a view does not include all NOT NULL columns without defaults of the underlying table, it cannot be used to add rows because the missing columns will lack values. This makes statement D correct.
- E: This statement is incorrect as primary keys do not affect querying through views; they affect insert and update operations where uniqueness and non-nullability are enforced.
- F: If the defining query of a view includes DISTINCT, the view generally cannot be used to perform update or insert operations as it may not be able to uniquely determine rows. This makes statement F correct.
Which three are true?
Options:
LAST_DAY returns the date of the last day of the current ,month onlyu.
CEIL requires an argument which is a numeric data type.
ADD_MONTHS adds a number of calendar months to a date.
ADD_MONTHS works with a character string that can be implicitlyt converted to a DATE data type.
LAST_DAY return the date of the last day the previous month only.
CEIL returns the largest integer less than or equal to a specified number.
LAST_DAY returns the date of the last day of the month for the date argument passed to the function.
Answer:
C, D, GExplanation:
- A: LAST_DAY does not only return the last day of the current month; it returns the last day of the month based on the date argument passed to it, which may not necessarily be the current month. Thus, statement A is incorrect.
- B: CEIL requires a numeric argument and returns the smallest integer greater than or equal to that number. Thus, statement B is incorrect.
- C: ADD_MONTHS function adds a specified number of calendar months to a date. This statement is correct as per the Oracle documentation.
- D: ADD_MONTHS can work with a character string if the string can be implicitly converted to a DATE, according to Oracle SQL data type conversion rules. Therefore, statement D is correct.
- E: LAST_DAY does not specifically return the last day of the previous month; it returns the last day of the month for any given date. Thus, statement E is incorrect.
- F: CEIL returns the smallest integer greater than or equal to the specified number, not the largest integer less than or equal to it. Hence, statement F is incorrect.
- G: LAST_DAY returns the last day of the month for the date argument passed to the function, which aligns with the definition in Oracle's SQL reference. Therefore, statement G is correct.
Examine the description of the CUSTOMERS table:
Which three statements will do an implicit conversion?
Options:
SELECT * FROM customers WHERE TO_ CHAR (customer_ id) = '0001';
SELECT * FROM customers WHERE customer id = '0001';
SELECT * FROM customers WHERE customer_ id = 0001;
SELECT FROM customers WHERE insert date = '01-JAN-19';
SELECT. FROM customers WHERE insert_ date = DATE *2019-01-01';
SELECT. FRON customers WE TO DATE (Insert _ date) = DATE ‘2019-01-01’;
Answer:
B, D, EExplanation:
- A: No implicit conversion is done here because TO_CHAR is an explicit conversion from a numeric to a string data type.
- B: Implicit conversion happens here because the '0001' string will be automatically converted to a numeric data type to match the CUSTOMER_ID field.
- C: No implicit conversion is needed because 0001 is already a numeric literal.
- D: Implicit conversion occurs here because the string '01-JAN-19' will be converted to a date type to compare with INSERT_DATE.
- E: No implicit conversion; DATE is explicitly specified using the DATE keyword.
- F: Incorrect syntax, it has typographical errors and also TO_DATE is an explicit function, not an implicit conversion.
References for SQL functions, conversions, and the CROSS JOIN behavior can be found in the Oracle Database SQL Language Reference 12c documentation.
Which four statements are true about constraints on Oracle tables?
Options:
A Column can have only one CHECK Constraint.
A NOT NULL Constraint can be defined at the table level.
A UNIQUE constraint permits NULLS.
A PRIMARY KEY Constraint can be added after a table has been created and populated.
A CHECK Constraint can refer to values in other rows.
A UNIQUE Constraint can use a pre-existing index on the constrained column or columns.
A FOREIGN KEY Column can contain NULLS.
Answer:
C, D, F, GExplanation:
C: True. A UNIQUE constraint in Oracle SQL allows for the inclusion of NULL values; specifically, it permits multiple NULLs in a column or set of columns but ensures that all non-NULL values are unique.
D: True. A PRIMARY KEY constraint can indeed be added to a table after it has been created and even after it has been populated, as long as the existing data does not violate the primary key constraint rules (i.e., all values must be unique and not NULL).
F: True. A UNIQUE constraint can utilize a pre-existing index on the columns it covers. If a suitable index already exists, Oracle can use this index to enforce the constraint, optimizing performance and resource utilization.
G: True. Columns that are part of a FOREIGN KEY constraint can contain NULL values. This is permissible under SQL standards and Oracle implementation, as a NULL foreign key value is considered to not refer to any row in the referenced table and thus does not violate referential integrity.
Which three are true about subqueries?
Options:
A subquery can be used in a WHERE clause.
A subquery can be used in a HAVING clause.
=ANY can only evaluate the argument against a subcjuery if it returns two or more values.
A subquery cannot be used in a FROM clause.
< any returns true if the argument is less than the lowest value returned by the subquery.
A subquery cannot be used in the select list.
Answer:
A, B, DExplanation:
About the roles and behavior of subqueries in SQL:
- A. A subquery can be used in a WHERE clause: Subqueries are often used in WHERE clauses to filter rows based on a condition evaluated against a set of returned values.
- B. A subquery can be used in a HAVING clause: Similar to WHERE, subqueries can be used in HAVING clauses to filter groups based on aggregate conditions.
- D.
Incorrect options:
- C: =ANY evaluates true if the argument matches any single value returned by the subquery, irrespective of the number of values.
- E: A subquery can indeed be used in a FROM clause, known as a derived table or inline view.
- F:
- G: A subquery can be used in a SELECT list, particularly when the subquery is designed to return a single value (scalar subquery).
Which statement is true regarding the SESSION_PRIVS dictionary view?
Options:
It contains the object privileges granted to other users by the current user session.
It contains the system privileges granted to other users by the current User session.
It contains the current system privileges available in the user session.
It contains the current object privileges available in the user session.
Answer:
CExplanation:
Regarding the SESSION_PRIVS dictionary view:
- C. It contains the current system privileges available in the user session: This view displays the system privileges granted to the current user, making it a tool for understanding which actions the user is allowed to perform in the current session.
Incorrect options:
- A and B: SESSION_PRIVS does not contain information about privileges granted to or by other users; it specifically lists the privileges available to the current session.
- D: It does not contain object privileges; these are contained in other views such as USER_TAB_PRIVS.
Which two statements are true about outer Joins?
Options:
The outer join operator (+) can be used on both sides of the join condition in an outer join.
An outer join is used to retrieve only the rows that do not meet the join condition.
The IN operator cannot be used in a condition that Involves an outer join.
A condition representing an outer join cannot be linked to another condition using the or logical operator.
The outer join operator (+) is used next to the column of the table without the matching rows.
Answer:
D, EExplanation:
Regarding the usage and rules of outer joins in SQL, specifically Oracle SQL:
- D. A condition representing an outer join cannot be linked to another condition using the OR logical operator: In SQL, when using the Oracle-specific (+) notation for outer joins, it is not permitted to combine this condition with another using the OR operator. The use of (+) imposes restrictions to ensure the join logic is correctly interpreted.
- E. The outer join operator (+) is used next to the column of the table without the matching rows: The (+) symbol in Oracle's SQL syntax denotes the table that should include "null" where data does not exist to satisfy the join condition, effectively including rows that do not have a match in the joined table.
Incorrect options:
- A: The (+) operator cannot be used on both sides of a condition within the same join; it can only appear on one side to define which side of the join is the outer part.
- B: An outer join is used to retrieve all rows from one table and the matched rows from the other table; it does not solely retrieve rows that do not meet the join condition.
- C: The IN operator can be used in conditions involving an outer join, although specific rules and behaviors need to be considered depending on the SQL version and implementation.
Which two statements are true about CURRENT_TIMEITAMP?
Options:
The date is in the time zone of DBTIMEZONE.
The value varies depending on the setting of SESSIONTIMEZONE.
It returns the same date as CURRENT_DATE.
The time is in the time zone of DBTIMEZONE.
It returns a value of data type TIMESTAMP
It always returns the same value as SYSTIMESTAMP
Answer:
B, EExplanation:
B. True. CURRENT_TIMESTAMP returns the current date and time in the session time zone, which is determined by the SESSIONTIMEZONE setting.
E. True. CURRENT_TIMESTAMP returns a value of the data type TIMESTAMP WITH TIME ZONE.
A and D are incorrect because CURRENT_TIMESTAMP reflects the session time zone, not DBTIMEZONE. C is incorrect because CURRENT_DATE returns the current date with no time component, whereas CURRENT_TIMESTAMP includes both date and time. F is incorrect because SYSTIMESTAMP returns the current date and time from the system clock in the time zone of the database server, which can differ from the session's time zone affecting CURRENT_TIMESTAMP.
Examine this query which executes successfully:
SELECT job, deptno FROM emp
UNION ALL
SELECT job, deptno FROM jobs_ history;
What will be the result?
Options:
It will return rows common to both SELECT statements.
It will return rows from both SELECT statements after eliminating duplicate rows.
It will return rows that are not common to both SELECT statements.
It will return rows from both SELECT statements including duplicate rows.
Answer:
DExplanation:
The UNION ALL operator in SQL is used to combine the results of two or more SELECT statements:
- Option D: It will return rows from both SELECT statements including duplicate rows.
Options A, B, and C are incorrect as they describe behaviors of other set operators:
- Option A: Describes the behavior of INTERSECT, not UNION ALL.
- Option B: Describes the behavior of UNION, not UNION ALL.
- Option C: Describes the behavior of EXCEPT or MINUS, not UNION ALL.
Which two are true about the NVL, NVL2, and COALESCE functions?
Options:
The first expression in NVL2 is never returned.
NVL2 can have any number of expressions in the list.
COALESCE stops evaluating the list of expressions when it finds the first null value.
COALESCE stops evaluating the list of expressions when it finds the first non-null value.
NVL must have expressions of the same data type.
NVL can have any number of expressions in the list.
Answer:
D, EExplanation:
A. This statement is false. In NVL2, the first expression is returned if it is not null.
B. This statement is false. NVL2 takes exactly three arguments, not any number of expressions.
C. This statement is false. COALESCE stops evaluating its list of expressions as soon as it finds the first non-null value.
D. This is true. COALESCE returns the first non-null expression in its list.
E. This statement is true. NVL requires the first and second expressions to be of the same or compatible data types because it returns the first expression if it is not null, otherwise it returns the second.
F. This statement is false. NVL takes exactly two arguments, not any number.
References:
- Oracle Documentation on COALESCE: https://docs.oracle.com/database/121/SQLRF/functions040.htm#SQLRF00625
- Oracle Documentation on NVL: https://docs.oracle.com/database/121/SQLRF/functions130.htm#SQLRF00683
- Oracle Documentation on NVL2: https://docs.oracle.com/database/121/SQLRF/functions123.htm#SQLRF00682