Sql Basis Flashcards
(46 cards)
Sql NOT
Select * from employee where NOT gender=‘female’
Sql BETWEEN
Select * from employee where age between 20 and 25
Sql COUNT
Select count(*) from employee
5 sql string function
ltrim(), lower(),upper(), reverse(), substring(string,start,lenght)
Sql AVG
Select avg(age) from employee
Average age, group by dept
Select avg(age),dpmt from employee group by dpmt order by avg(age) desc
Group by dpmt, avg(salary) when avg salary>100k
Select avg(salary),dptm from employee group by dpmt having avg(salary)>100000 order by avg(salary) desc.
GROUP BY - HAVING - ORDER
Having must be used in conjonction of group by
Sql TRUNCATE
Truncate table employee;
- delete all records
Sql INNER JOIN
Records only matching in the 2 tables
Select employee.name, employee.dpmt,department.name,department.location from employee inner join department on employee.dpmt=department.name
Sql FULL JOIN
All records from both tables
Sql LEFT JOIN
All records from first table and matching records from table 2
Delete command with join
Delete employee where dept. Loc=NY
Delete employee from employee join department on employee.dept=department.name where department.location=‘NY’
Sql UNION
Records from 2 tables without duplicate
Select… union select…
UNION ALL : with duplicate
Sql Operator merging 2 select
Union : no duplicate
Union all: with duplicate
Except: remove record from second table
Intersect: common columns from the 2 tables
Create VIEW
Create VIEW myView as
Select x from y where z
Drop a view
Drop view myview
Alter, add column
Alter table employee
Add dob date;
Alter table, drop column
Alter table employee
Drop column dob;
Sql merge
Merge employee_target T Using employee_source S On T.id=S.id When matched Then update set T.age=S.age, t.salary=... When not matched by target Then insert (age,salary...) values (S.age, S.salary...) When not matched by source Then delete;
Scalar valued function
Create function addfive(@num as int) Returns int As Begin Return(@num+5) End
To call it:
Select dbo.addfive(10)
Table valued function (gender)
Create function selectGender(@gender as varchar(20)) returns table
As
Return
( select * from employee where e_gender=@gender)
—to use it:
Select * from dbo.selectGender(‘male’)
Temporary table definition
Stored in tempdb. Deleted as soon ad the session is terminated, syntax is the same than create normal table but with a # before the name
Create temporary table
Create table #student
( s_id int,
s_name varchar(20)
);
Select * from #student
Case statement
Case When condition1 then result1 When condition2 then result2 Else result End