3b.SQL Handson-Clauses
3b.SQL Handson-Clauses
> insert into employee (f_nm, l_nm, age, dept, salary) values ('Ravi', 'Kiran', 25,
'HR', 30000.00);
> insert into employee (f_nm, l_nm, age, dept, salary) values
('Priya', 'Darshini', 28, 'HR', 32000.00),
('Mohan', 'Bhargav', 35, 'IT', 40000.00),
('Manoj', 'Bajpai', 40, 'IT', 45000.00);
> insert into employee (f_nm, l_nm, age, location, dept, salary) values
('Akhil', 'K', 26, 'Bangalore', 'IT', 42000.00),
('Raja', 'Roy', 35, 'Bangalore', 'IT', 60000.00),
('Shilpa', 'Sharma', 40, 'Chennai', 'IT', 44000.00);
ORDER BY - Sort the Data, and arrange the data in a sequence, either in ascending
order (default) or in descending order (desc)
> select * from employee order by age, salary; ---second level sort will happen
incase of a clash.
LIMIT - to put a limit on the number of records to be fetched (filter - eliminate
what is not required)
> select * from employee order by salary limit 3; - Bottom 3 employees by Salary
> select * from employee order by salary desc limit 3; - Top 3 employees by Salary
> select id,f_nm,l_nm from employee order by id limit 1 offset 0; --- gives the
first record
> select id,f_nm,l_nm from employee order by id limit 3 offset 3; --- beginning in
the 4th place it will give 3 records.
___________________________________________________________________________________
_________________________________
> select count(f_nm) from employee where age>25 and age <35;
> select location, count(*) from employee group by location; - number of employees
in each location
> select location, dept, count(*) from employee group by location, dept; - number
of employees in each location in each department
number of employees in each location in each department and above 30 years of age
-
> select location, dept, count(*) from employee group by location, dept where
age>30; ---> This command throws error
> select location, dept, count(*) from employee where age>30 group by location,
dept;
> select location, count(*) from employee group by location having location =
'Hyderabad' ; --- is correct
this would put a computational load on the server, instead, we can do this -
> select location, count(*) from employee where location = 'Hyderabad' group by
location; --- check the run time
Where is used to filter the records before group by, and having is after group by
to work with aggregated data.