How to rename a column in a query in ORACLE - sql

Is this query right for changing the name of a column in the employees table:
select first_name, rename_column('first_name' to 'empName') from employees;

there are two ways
1) give alias name to the column
SELECT first_name AS emp_name
FROM employee;
2) change column name
alter table employee
rename first_name to emp_name ;

To set an alias for a field use the following:
SELECT first_name AS "empName", hire_date AS "Tenure On December 31 2014"
FROM employees;

alter table employee
rename column first_name to emp_name ;

If you are going to change the name just in your current result-set, you can do following:
select first_name AS emp_name from employees;
if you are going to change the name permanently, you have to work with ALTER TABLE:
ALTER TABLE employees CHANGE first_name emp_name VARCHAR2(255);

Related

how can i Add commission_pct column in oracle

I put the schema manually, but there is no commission_pct column. How can i add it?
I can't find commission_pct data anywhere...
plz help me :(
select employee_id as 사원번호,
first_name || ' ' || last_name as 사원명,
nvl( salary + (salary * commission_pct), salary)*12 as 연봉,
department_id as 부서번호
from employees
where department_id in(30,50,60) and
nvl( salary + (salary * commission_pct), salary)*12 >= 20000 and
nvl( salary + (salary * commission_pct), salary)*12 <= 60000
order by 부서번호, 연봉 desc;```
ORA-00904: "COMMISSION_PCT": 부적합한 식별자
00904. 00000 - "%s: invalid identifier
That's kind of strange; how are you supposed to work with column that doesn't exist? Are you sure you're connected to right schema and have all tables you should?
As of your question, you'd add a new column into a table with alter table. Here's how: my employees table is a dummy one, it does not represent your table.
SQL> desc employees
Name Null? Type
----------------------------------------- -------- ----------------------------
EMPLOYEE_ID NOT NULL NUMBER
FIRST_NAME NOT NULL VARCHAR2(30)
LAST_NAME NOT NULL VARCHAR2(30)
HIRE_DATE NOT NULL DATE
SALARY NOT NULL NUMBER(8,2)
SQL> alter table employees add commision_pct number;
Table altered.
To set a value, you'd update table as
SQL> update employees set commision_pct = 15;
1 row updated.
SQL>

How to split the column into multiple column and insert new column into same table in snowflake

I am trying to split column into mulitple column and insert into same table using snowflake query.
EMP Table
ID NAME AGE
1 Ravi#Kumar 25
2 Virat#Singh 26
3 Rohit#Sharma 27
EMP Table after split
ID NAME F_NAME L_NAME AGE
1 Ravi#Kumar Ravi Kumar 25
2 Virat#Singh Viart Singh 26
3 Rohit#Sharma Rohit Sharma 27
I am able to select the data and spilt but I wanted to alter the existing table only.
Create source data.
create or replace table emp_source as
select ID, NAME, AGE
from (values
(1, 'Ravi#Kumar' , 25),
(2, 'Virat#Singh', 26),
(3, 'Rohit#Sharma', 27) t (ID, NAME, AGE)
);
We can split NAME using STRTOK as a slightly simpler alternative to REGEX_SUBSTR suggested by Tim Biegeleisen.
Select
ID,
strtok(NAME, '#',1) f_name,
strtok(NAME, '#',2) l_name,
AGE
from emp_source;
You could use computed/derived columns for this as the source column NAME contains the data you need per row:
computed/derived columns
create or replace table emp
(id bigint,
name varchar,
f_name varchar as strtok(NAME, '#',1),
l_name varchar as strtok(NAME, '#',2),
age integer
)
;
Insert the 3 source columns from source data into EMP table.
Insert into emp
Select id,name,age from emp_source;
Query EMP and the computed/Derived columns are calculated on the fly
Select * from emp;
If your EMP table is already created you could use alter table to switch them to derived/computed columns.
# Drop current columns if they already exist in table
alter table emp drop column f_name;
alter table emp drop column l_name;
# Add derived/computed columns
alter table emp add column f_name varchar as strtok(NAME, '#',1);
alter table emp add column l_name varchar as strtok(NAME, '#',2);
Now when you query the table the column values will be computed on the fly and returned, and you don't need to Update the table.
Note: No metadata is gathered on those columns, so if queries are likely to filter on them you may be better deriving them at Insert time or updating them. Also those columns will be computed for every query that selects them, so if they are used a lot it may also be better to UPDATE the table with the physical values
We can use REGEXP_SUBSTR() here:
SELECT
ID,
NAME,
REGEXP_SUBSTR(NAME, '([^#]+)', 1, 1, 'e', 1) AS F_NAME,
REGEXP_SUBSTR(NAME, '([^#]+)', 1, 2, 'e', 1) AS L_NAME,
AGE
FROM yourTable;
If you actually want to update your table, then add the F_NAME and L_NAME columns, and then use:
UPDATE yourTable
SET F_NAME = REGEXP_SUBSTR(NAME, '([^#]+)', 1, 1, 'e', 1),
L_NAME = REGEXP_SUBSTR(NAME, '([^#]+)', 1, 2, 'e', 1);

How to add a column to a table and have it displayed as the first column

I have table EMP with 2 columns ENM and EADD. Now I need to add a column EMPID but I want it to be displayed as the first column in the table, like EMPID, ENM, EADD.
Demo:
create table emp
( enm varchar2(20)
, eadd varchar2(100) );
alter table emp add empid number not null;
Describing emp gives:
Name Null? Type
------------------------------- -------- ----------------------------
ENM VARCHAR2(20)
EADD VARCHAR2(100)
EMPID NOT NULL NUMBER
Make all the columns except empid invisible and visible again:
begin
for r in (
select column_name
from user_tab_columns c
where c.table_name = 'EMP'
and c.column_name <> 'EMPID'
)
loop
execute immediate 'alter table emp modify '||r.column_name||' invisible';
execute immediate 'alter table emp modify '||r.column_name||' visible';
end loop;
end;
/
and now you have this:
Name Null? Type
------------------------------- -------- ----------------------------
EMPID NOT NULL NUMBER
ENM VARCHAR2(20)
EADD VARCHAR2(100)
As William Robertson suggests, using invisible and visible can be used to reorder columns. However if your table has a lot of fields this method can be obnoxious, especially if you are reordering multiple times during development.
There is always the tried and true method of dropping the table and recreating with the desired order.

How to solve single-row subquery returns more than one row

I have an employee table and it contains salary table. I want to give %10 increase to all current employees. I tried to update all employees' salary dates to specific date but I encountered problem with single-row subquery.
My database like this:
CREATE TYPE TEMPORAL_VARCHAR AS OBJECT (
VALID_TIME_LOWER_BOUND DATE,
VALID_TIME_UPPER_BOUND DATE,
VALUE_PART VARCHAR2(50) );
CREATE TYPE TEMPORAL_NUMBER AS OBJECT (
VALID_TIME_LOWER_BOUND DATE,
VALID_TIME_UPPER_BOUND DATE,
VALUE_PART NUMBER );
CREATE TYPE NAME_TYPE AS TABLE OF TEMPORAL_VARCHAR;
CREATE TYPE ADDRESS_TYPE AS TABLE OF TEMPORAL_VARCHAR;
CREATE TYPE DEPARTMENT_TYPE AS TABLE OF TEMPORAL_VARCHAR;
CREATE TYPE MANAGER_TYPE AS TABLE OF TEMPORAL_VARCHAR;
CREATE TYPE SALARY_TYPE AS TABLE OF TEMPORAL_NUMBER;
CREATE TABLE EMPLOYEE (
SSN NUMBER primary key,
NAME NAME_TYPE,
ADDRESS ADDRESS_TYPE ,
BIRTH_DATE DATE,
MANAGER MANAGER_TYPE ,
DEPARTMENT DEPARTMENT_TYPE,
SALARY SALARY_TYPE
)
NESTED TABLE NAME STORE AS NAME_TABLE,
NESTED TABLE ADDRESS STORE AS ADDRESS_TABLE,
NESTED TABLE MANAGER STORE AS MANAGER_TABLE,
NESTED TABLE DEPARTMENT STORE AS DEPARTMENT_TABLE,
NESTED TABLE SALARY STORE AS SALARY_TABLE
;
How to solve this problem? I tried to do this
UPDATE TABLE(
SELECT E.SALARY
FROM EMPLOYEE E
) SAL
SET SAL.VALID_TIME_UPPER_BOUND = '11.16.2015'
WHERE SAL.VALID_TIME_UPPER_BOUND = TO_DATE('12.31.9999','MM.DD.YYYY');
1st it can be duplicate
2nd see sample here
3rd in your code you need bring the where condition into select
UPDATE TABLE(
SELECT E.SALARY
FROM EMPLOYEE E
WHERE ssn in (SELECT ssn FROM EMPLOYEE e
WHERE to_date('01.01.2015','mm.dd.yyyy') in (
SELECT VALID_TIME_UPPER_BOUND FROM TABLE(e.salary)
)
)
) SAL
SET SAL.VALID_TIME_UPPER_BOUND = to_date('01.01.9999','mm.dd.yyyy')
test data
INSERT INTO EMPLOYEE(SSN, salary) values (1, SALARY_TYPE ());
INSERT INTO EMPLOYEE(SSN, salary) values (2, SALARY_TYPE ());
INSERT INTO EMPLOYEE(SSN, salary) values (3, SALARY_TYPE ());
INSERT INTO TABLE(SELECT salary FROM EMPLOYEE
WHERE ssn = 1)
VALUES (to_date('01.01.2005','mm.dd.yyyy'), to_date('01.01.2015','mm.dd.yyyy'), 1);
INSERT INTO TABLE(SELECT salary FROM EMPLOYEE
WHERE ssn = 2)
VALUES (to_date('02.02.2005','mm.dd.yyyy'), to_date('02.02.2015','mm.dd.yyyy'), 2);
INSERT INTO TABLE(SELECT salary FROM EMPLOYEE
WHERE ssn = 3)
VALUES (to_date('03.03.2005','mm.dd.yyyy'), to_date('03.03.2015','mm.dd.yyyy'), 3);
p.s do you really need the complexity?
I solved my problem using iteration like this
BEGIN
FOR employees IN (SELECT SSN FROM EMPLOYEE)
LOOP
UPDATE TABLE(
SELECT E.SALARY
FROM EMPLOYEE E
WHERE E.SSN = employees.SSN
) SAL
SET SAL.VALID_TIME_UPPER_BOUND = '11.16.2015'
WHERE SAL.VALID_TIME_UPPER_BOUND = TO_DATE('12.31.9999','MM.DD.YYYY');
END LOOP;
END;

Oracle SQL: Invalid table name when creating a trigger

I created this 4 tables:
create table terminatedEmployees (
empid number primary key,
dept number,
empname varchar2(50),
salary number
);
create table employees (
empid number primary key,
dept number,
empname varchar2(50),
salary number
);
create table payroll (
empid number primary key,
salary number,
CONSTRAINT fk_payemploy
FOREIGN KEY (empid)
REFERENCES employees(empid)
);
create table salaryAudit (
empid number primary key,
oldsal number,
newsal number,
datechanged date,
changedby varchar2(25),
CONSTRAINT fk_salaryaudit
FOREIGN KEY (empid)
REFERENCES employees(empid)
);
and now I'm trying to create a trigger in order to update two of them when employees table is updated:
CREATE TRIGGER trigger_updated_employees
AFTER UPDATE ON employees
FOR EACH ROW
when (old.salary != new.salary)
BEGIN
UPDATE INTO salaryAudit (newsal, oldsal)
VALUES(:new.salary, :old.salary);
UPDATE INTO payroll (salary)
VALUES(:new.salary);
END;
But I'm getting the error:
2/5 PL/SQL: SQL Statement ignored
2/12 PL/SQL: ORA-00903: invalid table name
4/5 PL/SQL: SQL Statement ignored
4/12 PL/SQL: ORA-00903: invalid table name
The three tables I'm calling in the trigger are ok and other triggers I created work...
Try something like this:
CREATE TRIGGER TRIGGER_UPDATED_EMPLOYEES
AFTER UPDATE ON EMPLOYEES
FOR EACH ROW
WHEN (OLD.SALARY <> NEW.SALARY)
BEGIN
MERGE INTO PAYROLL p
USING (SELECT :NEW.EMPID AS EMPID FROM DUAL) d
ON (p.EMPID = d.EMPID)
WHEN NOT MATCHED THEN
INSERT (EMPID, SALARY)
VALUES (:NEW.EMPID, :NEW.SALARY)
WHEN MATCHED THEN
UPDATE
SET SALARY = :NEW.SALARY;
MERGE INTO SALARYAUDIT a
USING (SELECT :NEW.EMPID AS EMPID FROM DUAL) d
ON (a.EMPID = d.EMPID)
WHEN NOT MATCHED THEN
INSERT (EMPID, OLDSAL, NEWSAL, DATECHANGED, CHANGEDBY)
VALUES (:NEW.EMPID, :OLD.SALARY, :NEW.SALARY, SYSDATE, 'SOME_USER')
WHEN MATCHED THEN
UPDATE
SET OLDSAL = :OLD.SALARY,
NEWSAL = :NEW.SALARY,
DATECHANGED = SYSDATE,
CHANGEDBY = 'SOME_USER';
END TRIGGER_UPDATED_EMPLOYEES;
Share and enjoy.
I got it working just correcting the UPDATE statements syntax and modifying the condition as #BobJarvis suggested, this is the final result:
CREATE TRIGGER trigger_updated_employees
AFTER UPDATE OF salary ON employees
FOR EACH ROW
when (old.salary <> new.salary)
BEGIN
UPDATE salaryAudit
SET (newsal, oldsal)
VALUES (:new.salary, :old.salary)
WHERE (salaryAudit.empid = old.empid);
UPDATE payroll
SET (salary)
VALUES (:new.salary)
WHERE (payroll.empid = old.empid);
END;
The concept is the same that #BobJarvis proposed but a lot simpler. Thanks