Some Basic SQL Examples

27 Jan 2018

Table of Contents


insert

SQL
1
2
insert into emp (empno, ename, sal)
values (102, 'Ashi', 5000);

insert… select

SQL
1
2
3
insert into emp (empno, ename, sal)
select empno, ename, sal
from other_table;

update

SQL
1
2
3
4
update emp
set name = 'Fred,
sal = sal + (sal*10/100)
where empno = 102;

update… select

SQL
1
2
3
4
5
update emp
set city = (
  select city
  from dept
  where deptno = emp.deptno);

merge

SQL
1
2
3
4
5
merge into sales_history sh
  using sales s
  on (s.prod = sh.prod and s.month = sh.month)
  when matched then update set sh.amount = s.amount
  when not matched then insert values (prod, month, amount);

correlated subquery

SQL
1
2
3
4
5
6
select *
from customers c
where not exists (
  select 1
  from orders o
  where o.cust_id = c.cust_id);

delete… select

SQL
1
2
3
4
5
delete from your_table
where rowid not in (
  select min(rowid)
  from your_table
  group by column1, column2, column3);

select… rank

SQL
1
2
3
4
5
select
  product_name,
  list_price,
  rank() over(order by list_price desc)
from products;

select… rank partition

SQL
1
2
3
4
5
6
7
8
select
  product_name,
  list_price,
  category_id,
  rank() over (
    partition by category_id
    order by list_price desc) as price_rank
  from products

with… select

SQL
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
with cte_products as (
  select
    product_name,
    list_price,
    rank() over(order by list_price desc) as price_rank
  from products
)
select
  product_name,  
  list_price,
  price_rank
from cte_products
where price_rank <= 10;

select… listagg

SQL
1
2
3
4
5
6
select
  listagg(last_name, '; ')
    within group (order by hire_date, last_name) as "Emp_list",
  min(hire_date) as "Earliest"
from employees
where department_id = 30;