Create ACCOUNT table with PRIMARY KEY named ACCOUNT_PKEY on ACCOUNT_ID column
CREATE TABLE ACCOUNT
(
ACCOUNT_ID NUMBER(6) CONSTRAINT ACCOUNT_PKEY PRIMARY KEY,
ACCOUNT_NAME VARCHAR2(255),
BILLING_COUNTRY VARCHAR(50),
BILLING_CITY VARCHAR(50),
...
)
Create ACCOUNT table with PRIMARY KEY named ACCOUNT_PKEY on ACCOUNT_ID column
CREATE TABLE ACCOUNT
(
ACCOUNT_ID NUMBER(6) CONSTRAINT ACCOUNT_PKEY PRIMARY KEY,
ACCOUNT_NAME VARCHAR2(255),
BILLING_COUNTRY VARCHAR(50),
BILLING_CITY VARCHAR(50),
...
)
Labels: Oracle, Oracle Query, PL/SQL
Get employees have minimum salary in their departments.
SELECT ENAME, JOB, DEPTNO, SAL
FROM EMP
WHERE (SAL,DEPTNO) IN (SELECT MIN(SAL), DEPTNO
FROM EMP
GROUP BY DEPTNO)
Labels: Oracle, Oracle Query, PL/SQL
List all tables with their constraints and constraint types.
SELECT OWNER,
TABLE_NAME,
CONSTRAINT_NAME,
DECODE(CONSTRAINT_TYPE, 'C','Check',
'P','Primary Key',
'U','Unique',
'R','Foreign Key',
'V','With Check Option') TYPE,
STATUS
FROM dba_constraints
ORDER BY OWNER, TABLE_NAME, CONSTRAINT_NAME
Labels: Oracle, Oracle Query, PL/SQL
Get database objects that are modified in last 7 days.
SELECT OWNER,
OBJECT_NAME,
OBJECT_TYPE,
TO_CHAR(LAST_DDL_TIME,'YYYY/MM/DD HH24:MI:SS') LAST_MODIFIED_DATE,
TO_CHAR(CREATED,'YYYY/MM/DD HH24:MI:SS') CREATED_DATE,
STATUS
FROM dba_objects
WHERE (SYSDATE - LAST_DDL_TIME) < 7
Labels: Oracle, Oracle Query, PL/SQL
You have to use alias for self join.
List all accounts with their parent account.
SELECT t1.ACCOUNT_NAME, t2.ACCOUNT_NAME AS PARENT_ACCOUNT
FROM ACCOUNT t1, ACCOUNT t2
WHERE t1.PARENT_ACCOUNT_ID = t2.ACCOUNT_ID(+)
Use outer join here to list accounts without parents.
Labels: Oracle, Oracle Query, PL/SQL
List all accounts and their contacts, show contact with NULL value if an account has no contacts.
SELECT t1.ACCOUNT_NAME, t2.CONTACT_NAME
FROM ACCOUNT t1, CONTACT t2
WHERE t1.ACCOUNT_ID = t2.ACCOUNT_ID(+)
In SQL Server:
SELECT t1.ACCOUNT_NAME, t2.CONTACT_NAME
FROM ACCOUNT t1 LEFT JOIN
CONTACT t2 ON t1.ACCOUNT_ID = t2.ACCOUNT_ID
Labels: Oracle, Oracle Query, PL/SQL
System table of owner SYS, used to select one value from system function, user-defined function which return scalar value
SELECT SYSDATE FROM DUAL;
SYSDATE
---------
02-MAY-09
SELECT SYSDATE FROM ACCOUNT;
SYSDATE
---------
02-MAY-09
02-MAY-09
.......
SELECT fnGetAccountNameByAccountID(100000) FROM DUAL;
fnGetAccountNameByAccountID is a user-defined function to return scalar value (Account Name) based on AccountID parameter.
Labels: Oracle, Oracle Query, PL/SQL