Check if table contains any data
This one can be written in multiple ways. You can create count(*) on a table to know number of rows. But this query is more efficient given the fact that we are only interested in knowing if table has any data.
SELECT 1
FROM TABLE_NAME
WHERE ROWNUM = 1;
Oracle Delete Query
Oracle update query is used to delete records of a table from database. For example:
delete from customers where id=101;
Get position of 'o' in name 'John' from employee table
Select instr(FIRST_NAME,'o') from employee where first_name = 'John'
Oracle Truncate Query
Oracle update query is used to truncate or remove records of a table. It doesn't remove structure. For example:
truncate table customers;
Get First_Name from employee table after replacing 'o' with '$'
select REPLACE(FIRST_NAME,'o','$') from employee
Oracle Drop Query
Oracle drop query is used to drop a table or view. It doesn't have structure and data. For example:
drop table customers;
Get Joining Date,Time including milliseconds from employee table
select to_char(JOINING_DATE,'dd/mm/yyyy HH:mi:ss.ff') from
EMPLOYEE . Column Data Type should be “TimeStamp”
Oracle Create Query
Oracle create query is used to create a table, view, sequence, procedure and function. For example:
CREATE TABLE customers
( id number(10) NOT NULL,
name varchar2(50) NOT NULL,
city varchar2(50),
CONSTRAINT customers_pk PRIMARY KEY (id)
);
Oracle Alter Query
Oracle alter query is used to add, modify, delete or drop colums of a table. Let's see a query to add column in customers table:
ALTER TABLE customers
ADD age varchar2(50);
How to add column in a table
Syntax:
ALTER TABLE table_name
ADD column_name column-definition;
Example:
Consider that already existing table customers. Now, add a new column customer_age into the table customers.
ALTER TABLE customers
ADD customer_age varchar2(50);
Now, a new column "customer_age" will be added in customers table.
How to add multiple columns in the existing table
Syntax:
ALTER TABLE table_name
ADD (column_1 column-definition,
column_2 column-definition,
...
column_n column_definition);
Example
ALTER TABLE customers
ADD (customer_type varchar2(50),
customer_address varchar2(50));
Now, two columns customer_type and customer_address will be added in the table customers.
Write a SQL query to find the products which have continuous increase in sales every year?
Solution:
Here “Iphone” is the only product whose sales are increasing every year.
STEP1: First we will get the previous year sales for each product. The SQL query to do this is
SELECT P.PRODUCT_NAME,
S.YEAR,
S.QUANTITY,
LEAD(S.QUANTITY,1,0) OVER (
PARTITION BY P.PRODUCT_ID
ORDER BY S.YEAR DESC
) QUAN_PREV_YEAR
FROM PRODUCTS P,
SALES S
WHERE P.PRODUCT_ID = S.PRODUCT_ID;
Here the lead analytic function will get the quantity of a product in its previous year.
STEP 2: We will find the difference between the quantities of a product with its previous year’s quantity. If this difference is greater than or equal to zero for all the rows, then the product is a constantly increasing in sales. The final query to get the required result is
SELECT PRODUCT_NAME
FROM
(
SELECT P.PRODUCT_NAME,
S.QUANTITY -
LEAD(S.QUANTITY,1,0) OVER (
PARTITION BY P.PRODUCT_ID
ORDER BY S.YEAR DESC
) QUAN_DIFF
FROM PRODUCTS P,
SALES S
WHERE P.PRODUCT_ID = S.PRODUCT_ID
)A
GROUP BY PRODUCT_NAME
HAVING MIN(QUAN_DIFF) >= 0;
PRODUCT_NAME
------------
IPhone
Write a SQL query to find the products which does not have sales at all?
Solution:
“LG” is the only product which does not have sales at all. This can be achieved in three ways.
Method 1: Using left outer join.
SELECT P.PRODUCT_NAME
FROM PRODUCTS P
LEFT OUTER JOIN
SALES S
ON (P.PRODUCT_ID = S.PRODUCT_ID);
WHERE S.QUANTITY IS NULL
PRODUCT_NAME
------------
LG
Method 2: Using the NOT IN operator.
SELECT P.PRODUCT_NAME
FROM PRODUCTS P
WHERE P.PRODUCT_ID NOT IN
(SELECT DISTINCT PRODUCT_ID FROM SALES);
PRODUCT_NAME
------------
LG
Method 3: Using the NOT EXISTS operator.
SELECT P.PRODUCT_NAME
FROM PRODUCTS P
WHERE NOT EXISTS
(SELECT 1 FROM SALES S WHERE S.PRODUCT_ID = P.PRODUCT_ID);
PRODUCT_NAME
------------
LG
Write a SQL query to find the products whose sales decreased in 2012 compared to 2011?
Solution:
Here Nokia is the only product whose sales decreased in year 2012 when compared with the sales in the year 2011. The SQL query to get the required output is
SELECT P.PRODUCT_NAME
FROM PRODUCTS P,
SALES S_2012,
SALES S_2011
WHERE P.PRODUCT_ID = S_2012.PRODUCT_ID
AND S_2012.YEAR = 2012
AND S_2011.YEAR = 2011
AND S_2012.PRODUCT_ID = S_2011.PRODUCT_ID
AND S_2012.QUANTITY < S_2011.QUANTITY;
PRODUCT_NAME
------------
Nokia
Write a query to select the top product sold in each year?
Solution:
Nokia is the top product sold in the year 2010. Similarly, Samsung in 2011 and IPhone, Samsung in 2012. The query for this is
SELECT PRODUCT_NAME,
YEAR
FROM
(
SELECT P.PRODUCT_NAME,
S.YEAR,
RANK() OVER (
PARTITION BY S.YEAR
ORDER BY S.QUANTITY DESC
) RNK
FROM PRODUCTS P,
SALES S
WHERE P.PRODUCT_ID = S.PRODUCT_ID
) A
WHERE RNK = 1;
Get number of days left in current month
Below query calculates number of days left in current month.
SELECT SYSDATE,
LAST_DAY (SYSDATE) "Last",
LAST_DAY (SYSDATE) - SYSDATE "Days left"
FROM DUAL;
Get number of days between two dates
Use this query to get difference between two dates in number of days.
SELECT ROUND ( (MONTHS_BETWEEN ('01-Feb-2014', '01-Mar-2012') * 30), 0)
num_of_days
FROM DUAL;
OR
SELECT TRUNC(sysdate) - TRUNC(e.hire_date) FROM employees;
Use second query if you need to find number of days since some specific date. In this example number of days since any employee is hired.
Display each months start and end date upto last month of the year
This clever query displays start date and end date of each month in current year. You might want to use this for certain types of calculations.
SELECT ADD_MONTHS (TRUNC (SYSDATE, 'MONTH'), i) start_date,
TRUNC (LAST_DAY (ADD_MONTHS (SYSDATE, i))) end_date
FROM XMLTABLE (
'for $i in 0 to xs:int(D) return $i'
PASSING XMLELEMENT (
d,
FLOOR (
MONTHS_BETWEEN (
ADD_MONTHS (TRUNC (SYSDATE, 'YEAR') - 1, 12),
SYSDATE)))
COLUMNS i INTEGER PATH '.');
Get number of seconds passed since today (since 00:00 hr)
SELECT (SYSDATE - TRUNC (SYSDATE)) * 24 * 60 * 60 num_of_sec_since_morning
FROM DUAL;
Get number of seconds left today (till 23:59:59 hr)
SELECT (TRUNC (SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_left
FROM DUAL;
Check if a table exists in the current database schema
A simple query that can be used to check if a table exists before you create it. This way you can make your create table script rerunnable. Just replace table_name with actual table you want to check. This query will check if table exists for current user (from where the query is executed).
SELECT table_name
FROM user_tables
WHERE table_name = 'TABLE_NAME';
Check if a column exists in a table
Simple query to check if a particular column exists in table. Useful when you tries to add new column in table using ALTER TABLE statement, you might wanna check if column already exists before adding one.
SELECT column_name AS FOUND
FROM user_tab_cols
WHERE table_name = 'TABLE_NAME' AND column_name = 'COLUMN_NAME';
Showing the table structure
This query gives you the DDL statement for any table. Notice we have pass ‘TABLE’ as first parameter. This query can be generalized to get DDL statement of any database object. For example to get DDL for a view just replace first argument with ‘VIEW’ and second with your view name and so.
SELECT DBMS_METADATA.get_ddl ('TABLE', 'TABLE_NAME', 'USER_NAME') FROM DUAL;
Getting current schema
Yet another query to get current schema name.
SELECT SYS_CONTEXT ('userenv', 'current_schema') FROM DUAL;
Changing current schema
Yet another query to change the current schema. Useful when your script is expected to run under certain user but is actually executed by other user. It is always safe to set the current user to what your script expects.
ALTER SESSION SET CURRENT_SCHEMA = new_schema;
Database version information
Returns the Oracle database version.
SELECT * FROM v$version;
Database default information
Some system default information.
SELECT username,
profile,
default_tablespace,
temporary_tablespace
FROM dba_users;
Database Character Set information
Display the character set information of database.
SELECT * FROM nls_database_parameters;
Get Oracle version
SELECT VALUE
FROM v$system_parameter
WHERE name = 'compatible';
Store data case sensitive but to index it case insensitive
Now this ones tricky. Sometime you might querying database on some value independent of case. In your query you might do UPPER(..) = UPPER(..) on both sides to make it case insensitive. Now in such cases, you might want to make your index case insensitive so that they don’t occupy more space. Feel free to experiment with this one.
CREATE TABLE tab (col1 VARCHAR2 (10));
CREATE INDEX idx1
ON tab (UPPER (col1));
ANALYZE TABLE a COMPUTE STATISTICS;
Resizing Tablespace without adding datafile
Yet another DDL query to resize table space.
ALTER DATABASE DATAFILE '/work/oradata/STARTST/STAR02D.dbf' resize 2000M;
This one can be written in multiple ways. You can create count(*) on a table to know number of rows. But this query is more efficient given the fact that we are only interested in knowing if table has any data.
SELECT 1
FROM TABLE_NAME
WHERE ROWNUM = 1;
Oracle Delete Query
Oracle update query is used to delete records of a table from database. For example:
delete from customers where id=101;
Get position of 'o' in name 'John' from employee table
Select instr(FIRST_NAME,'o') from employee where first_name = 'John'
Oracle SQL Queries Most Frequently Asked In ServiceNow Written Test Interview |
Oracle Truncate Query
Oracle update query is used to truncate or remove records of a table. It doesn't remove structure. For example:
truncate table customers;
Get First_Name from employee table after replacing 'o' with '$'
select REPLACE(FIRST_NAME,'o','$') from employee
Oracle Drop Query
Oracle drop query is used to drop a table or view. It doesn't have structure and data. For example:
drop table customers;
Get Joining Date,Time including milliseconds from employee table
select to_char(JOINING_DATE,'dd/mm/yyyy HH:mi:ss.ff') from
EMPLOYEE . Column Data Type should be “TimeStamp”
Oracle Create Query
Oracle create query is used to create a table, view, sequence, procedure and function. For example:
CREATE TABLE customers
( id number(10) NOT NULL,
name varchar2(50) NOT NULL,
city varchar2(50),
CONSTRAINT customers_pk PRIMARY KEY (id)
);
Oracle Alter Query
Oracle alter query is used to add, modify, delete or drop colums of a table. Let's see a query to add column in customers table:
ALTER TABLE customers
ADD age varchar2(50);
How to add column in a table
Syntax:
ALTER TABLE table_name
ADD column_name column-definition;
Example:
Consider that already existing table customers. Now, add a new column customer_age into the table customers.
ALTER TABLE customers
ADD customer_age varchar2(50);
Now, a new column "customer_age" will be added in customers table.
How to add multiple columns in the existing table
Syntax:
ALTER TABLE table_name
ADD (column_1 column-definition,
column_2 column-definition,
...
column_n column_definition);
Example
ALTER TABLE customers
ADD (customer_type varchar2(50),
customer_address varchar2(50));
Now, two columns customer_type and customer_address will be added in the table customers.
Write a SQL query to find the products which have continuous increase in sales every year?
Solution:
Here “Iphone” is the only product whose sales are increasing every year.
STEP1: First we will get the previous year sales for each product. The SQL query to do this is
SELECT P.PRODUCT_NAME,
S.YEAR,
S.QUANTITY,
LEAD(S.QUANTITY,1,0) OVER (
PARTITION BY P.PRODUCT_ID
ORDER BY S.YEAR DESC
) QUAN_PREV_YEAR
FROM PRODUCTS P,
SALES S
WHERE P.PRODUCT_ID = S.PRODUCT_ID;
Here the lead analytic function will get the quantity of a product in its previous year.
STEP 2: We will find the difference between the quantities of a product with its previous year’s quantity. If this difference is greater than or equal to zero for all the rows, then the product is a constantly increasing in sales. The final query to get the required result is
SELECT PRODUCT_NAME
FROM
(
SELECT P.PRODUCT_NAME,
S.QUANTITY -
LEAD(S.QUANTITY,1,0) OVER (
PARTITION BY P.PRODUCT_ID
ORDER BY S.YEAR DESC
) QUAN_DIFF
FROM PRODUCTS P,
SALES S
WHERE P.PRODUCT_ID = S.PRODUCT_ID
)A
GROUP BY PRODUCT_NAME
HAVING MIN(QUAN_DIFF) >= 0;
PRODUCT_NAME
------------
IPhone
Write a SQL query to find the products which does not have sales at all?
Solution:
“LG” is the only product which does not have sales at all. This can be achieved in three ways.
Method 1: Using left outer join.
SELECT P.PRODUCT_NAME
FROM PRODUCTS P
LEFT OUTER JOIN
SALES S
ON (P.PRODUCT_ID = S.PRODUCT_ID);
WHERE S.QUANTITY IS NULL
PRODUCT_NAME
------------
LG
Method 2: Using the NOT IN operator.
SELECT P.PRODUCT_NAME
FROM PRODUCTS P
WHERE P.PRODUCT_ID NOT IN
(SELECT DISTINCT PRODUCT_ID FROM SALES);
PRODUCT_NAME
------------
LG
Method 3: Using the NOT EXISTS operator.
SELECT P.PRODUCT_NAME
FROM PRODUCTS P
WHERE NOT EXISTS
(SELECT 1 FROM SALES S WHERE S.PRODUCT_ID = P.PRODUCT_ID);
PRODUCT_NAME
------------
LG
Write a SQL query to find the products whose sales decreased in 2012 compared to 2011?
Solution:
Here Nokia is the only product whose sales decreased in year 2012 when compared with the sales in the year 2011. The SQL query to get the required output is
SELECT P.PRODUCT_NAME
FROM PRODUCTS P,
SALES S_2012,
SALES S_2011
WHERE P.PRODUCT_ID = S_2012.PRODUCT_ID
AND S_2012.YEAR = 2012
AND S_2011.YEAR = 2011
AND S_2012.PRODUCT_ID = S_2011.PRODUCT_ID
AND S_2012.QUANTITY < S_2011.QUANTITY;
PRODUCT_NAME
------------
Nokia
Write a query to select the top product sold in each year?
Solution:
Nokia is the top product sold in the year 2010. Similarly, Samsung in 2011 and IPhone, Samsung in 2012. The query for this is
SELECT PRODUCT_NAME,
YEAR
FROM
(
SELECT P.PRODUCT_NAME,
S.YEAR,
RANK() OVER (
PARTITION BY S.YEAR
ORDER BY S.QUANTITY DESC
) RNK
FROM PRODUCTS P,
SALES S
WHERE P.PRODUCT_ID = S.PRODUCT_ID
) A
WHERE RNK = 1;
Get number of days left in current month
Below query calculates number of days left in current month.
SELECT SYSDATE,
LAST_DAY (SYSDATE) "Last",
LAST_DAY (SYSDATE) - SYSDATE "Days left"
FROM DUAL;
Get number of days between two dates
Use this query to get difference between two dates in number of days.
SELECT ROUND ( (MONTHS_BETWEEN ('01-Feb-2014', '01-Mar-2012') * 30), 0)
num_of_days
FROM DUAL;
OR
SELECT TRUNC(sysdate) - TRUNC(e.hire_date) FROM employees;
Use second query if you need to find number of days since some specific date. In this example number of days since any employee is hired.
Display each months start and end date upto last month of the year
This clever query displays start date and end date of each month in current year. You might want to use this for certain types of calculations.
SELECT ADD_MONTHS (TRUNC (SYSDATE, 'MONTH'), i) start_date,
TRUNC (LAST_DAY (ADD_MONTHS (SYSDATE, i))) end_date
FROM XMLTABLE (
'for $i in 0 to xs:int(D) return $i'
PASSING XMLELEMENT (
d,
FLOOR (
MONTHS_BETWEEN (
ADD_MONTHS (TRUNC (SYSDATE, 'YEAR') - 1, 12),
SYSDATE)))
COLUMNS i INTEGER PATH '.');
Get number of seconds passed since today (since 00:00 hr)
SELECT (SYSDATE - TRUNC (SYSDATE)) * 24 * 60 * 60 num_of_sec_since_morning
FROM DUAL;
Get number of seconds left today (till 23:59:59 hr)
SELECT (TRUNC (SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_left
FROM DUAL;
Check if a table exists in the current database schema
A simple query that can be used to check if a table exists before you create it. This way you can make your create table script rerunnable. Just replace table_name with actual table you want to check. This query will check if table exists for current user (from where the query is executed).
SELECT table_name
FROM user_tables
WHERE table_name = 'TABLE_NAME';
Check if a column exists in a table
Simple query to check if a particular column exists in table. Useful when you tries to add new column in table using ALTER TABLE statement, you might wanna check if column already exists before adding one.
SELECT column_name AS FOUND
FROM user_tab_cols
WHERE table_name = 'TABLE_NAME' AND column_name = 'COLUMN_NAME';
Showing the table structure
This query gives you the DDL statement for any table. Notice we have pass ‘TABLE’ as first parameter. This query can be generalized to get DDL statement of any database object. For example to get DDL for a view just replace first argument with ‘VIEW’ and second with your view name and so.
SELECT DBMS_METADATA.get_ddl ('TABLE', 'TABLE_NAME', 'USER_NAME') FROM DUAL;
Getting current schema
Yet another query to get current schema name.
SELECT SYS_CONTEXT ('userenv', 'current_schema') FROM DUAL;
Changing current schema
Yet another query to change the current schema. Useful when your script is expected to run under certain user but is actually executed by other user. It is always safe to set the current user to what your script expects.
ALTER SESSION SET CURRENT_SCHEMA = new_schema;
Database version information
Returns the Oracle database version.
SELECT * FROM v$version;
Database default information
Some system default information.
SELECT username,
profile,
default_tablespace,
temporary_tablespace
FROM dba_users;
Database Character Set information
Display the character set information of database.
SELECT * FROM nls_database_parameters;
Get Oracle version
SELECT VALUE
FROM v$system_parameter
WHERE name = 'compatible';
Store data case sensitive but to index it case insensitive
Now this ones tricky. Sometime you might querying database on some value independent of case. In your query you might do UPPER(..) = UPPER(..) on both sides to make it case insensitive. Now in such cases, you might want to make your index case insensitive so that they don’t occupy more space. Feel free to experiment with this one.
CREATE TABLE tab (col1 VARCHAR2 (10));
CREATE INDEX idx1
ON tab (UPPER (col1));
ANALYZE TABLE a COMPUTE STATISTICS;
Resizing Tablespace without adding datafile
Yet another DDL query to resize table space.
ALTER DATABASE DATAFILE '/work/oradata/STARTST/STAR02D.dbf' resize 2000M;
Post a Comment