Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

SQL Practice

The document discusses various SQL commands and concepts for working with databases and tables. It covers creating and dropping databases and tables, inserting, selecting, updating, and deleting data, defining primary keys and foreign keys, joining tables, and using aggregation functions and grouping.

Uploaded by

goeludbhav12
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

SQL Practice

The document discusses various SQL commands and concepts for working with databases and tables. It covers creating and dropping databases and tables, inserting, selecting, updating, and deleting data, defining primary keys and foreign keys, joining tables, and using aggregation functions and grouping.

Uploaded by

goeludbhav12
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Session 1 – create database / tables

Create database trendytech;

Show databases;

Use trendytech;

Select database();

Create table employee ( name varchar(20) , salary int );

Show tables;

Describe employee; / desc employee

Drop table employee;

Drop database trendytech;

Create database trendytech;

Create table trendytech.employee ( );

Session 2 – CRUD - insert/ select/ update / delete

DDL – Data Definition Language - deals with table structure – Create , Alter , Drop

DML – Data Manipulation Language - deals with the data directly – Insert. Update, Delete

Create table employee ( fname varchar(20), lname varchar(20) , salary int );

INSERT INTO employee VALUES ( “Akash”, 20 );

INSERT INTO employee (fname, lname, salary ) VALUES ( “Akash”,”Gupta” 20 ); - better way to insert
values

INSERT INTO employee (fname, salary ) VALUES ( “Akash”, 20 ); - when one field is missing

INSERT INTO employee (fname, lname, salary ) VALUES ( “Akash”,”Gupta” 20 ),(“”, “”, 34 ) ; - Multiple
value inputs

Create table employee ( fname varchar(20) NOT NULL ,mname varchar(20), lname varchar(20) NOT
NULL, salary int NOT NULL); - defining what can’t be NULL

Create table employee ( fname varchar(20) NOT NULL ,mname varchar(20), lname varchar(20) NOT
NULL, salary int NOT NULL, location varchar(20) DEFAULT “bangalore”) – defining default values if
any value is not provided

Create table employee ( fname varchar(20) NOT NULL ,mname varchar(20), lname varchar(20) NOT
NULL, salary int NOT NULL, location varchar(20) NOT NULL DEFAULT “bangalore”) – can’t explicitly
pass NULL as value after this combination
Session 3 – Primary key / auto increment keys / unique key

Create table employee ( id int PRIMARY KEY, fname varchar(20) NOT NULL ,mname varchar(20),
lname varchar(20) NOT NULL, salary int NOT NULL, location varchar(20) NOT NULL DEFAULT
“bangalore”);- PRIMARY KEY – Null and repeated values are not allowed

Create table employee ( id int, fname varchar(20) NOT NULL ,mname varchar(20), lname varchar(20)
NOT NULL, salary int NOT NULL, location varchar(20) NOT NULL DEFAULT “bangalore”, PRIMARY
KEY(id)); - other way to define primary key

PRIMARY KEY (id, name) – COMPOSITE PRIMARY KEY

Create table employee ( id int AUTO_INCREMENT, fname varchar(20) NOT NULL ,mname
varchar(20), lname varchar(20) NOT NULL, salary int NOT NULL, location varchar(20) NOT NULL
DEFAULT “bangalore”, PRIMARY KEY(id)); - to autoincrement a particular value and not enter again

UNIQUE KEY – it can hold NULL value, and can have multiple NULL values- considers it different,

Purpose of unique key is to make sure the values do not duplicate.

Only one primary key eg. ID, but we can have multiple UNIQUE keys eg. Email, phone no

Create table employee ( id int UNIQUE KEY, fname varchar(20) NOT NULL ,mname varchar(20),
lname varchar(20) NOT NULL, salary int NOT NULL, location varchar(20) NOT NULL DEFAULT
“bangalore”, PRIMARY KEY(id));

Session 4 –

Select * from employee;

Select fname, lname from employee;

Select * from employee where fname=”manish”; - this stmnt will also fetch “Manish” in results( case
– insensitive)

Select * from employee where binary fname=”manish”; - this statement now became case sensitive
and will not fetch “Manish”

Select fname as name , lname as surname from employee; - Alias use ‘as’ to change column name

Update – used to change data in the table

Update employee set lname=”Sinha” where fname=”manish”; - update only specific records

Update employee set lname=”Sinha”; - now this will update all records’s lname as Sinha

Update employee set salary = salary + 5000; - increase all salaries

Delete – DML command

DELETE from employee where id= 3;

DELETE from employee; - delete all entries in the table


ALTER – used to alter the structure/ schema of the table

ALTER table employee add column jobtitle varchar(50);

ALTER table employee drop column jobtitle;

ALTER table employee modify column fname varchar(30);

ALTER table employee drop primary key;

ALTER table employee add primary key(id);

TRUNCATE – DDL command

TRUNCATE table employee; - this also removes all records in a table

Truncate internally drops the table and then recreates it that’s why it is a DDL command while Delete
command deletes one entry at a time so it is a DML command. Therefore, truncate is more efficient.

Session 5 – Foreign Key Constraint

TIMESTAMP – data type for date-time

Create table courses(course_id int NOT NULL, course_name varchar(20), course_fees int NOT NULL

PRIMARY KEY(course_id));

Create table students( id int, fname varchar(20), email varchar(20),

selected_course int NOT NULL default 1,

batchdate varchar(20), PRIMARY KEY(id), unique key (email)

FOREIGN KEY(selected_course) REFERENCES courses(course_id); -this statement checks the validity


of course id from COURSES table, if coming data is present in COURSES table then the query will be
added to the students table.

Here, Courses table – Parent ; Students table – Child

F.K constraint is used to prevent actions that would destroy link between two tables.

F.K – It is a field in one table that refers to the primary key in another table

Table with foreign key – child table, table with primary key- parent/ reference table

Session 6 – distinct/ order by / limit / like

Select DISTINCT location from students; - only shows distinct cities only once

Select * from students ORDER BY years_of_exp; ascending by default

Select * from students ORDER BY years_of_exp desc; - arrange in descending order


Select * from students ORDER BY f_name; - arrange alphabetically

Select f_name from students ORDER BY years_of_exp; - still arranges in terms of Y.O.E even if not
included in select

Select f_name, years_of_exp from students ORDER BY years_of_exp, student_fname – first it wil
order by Y.O.E and then who have same Y.O.E it will do second level sorting on basis on alphabets

LIMIT

Select * from students limit 3; will show only 3 record (no sense, need to use it with order by)

Select * from students ORDER BY years_of_exp limit 3; (will show 3 candidates with least
experience)

Select * from students ORDER BY years_of_exp DESC limit 3 ( 3 candidates with highest experience)

Select * from students order by enroll_date limit 0,3; – gives first 3 enrolled record(from first record
give 3 record same as limit 3)

Select * from students order by enroll_date limit 3,2; - from 4th record give 2 records

LIKE - % , _ are wild card character here

Select * from students where f_name LIKE ‘%ra%’; - ra can be anywhere

Select * from students where f_name LIKE ‘ra%’; – all name starting with ra

Select * from students where f_name LIKE ‘_____’; – give all names having 5 characters ( 5 _ )

Session 7 – order of execution

From (loading the table)

Select ( projecting required columns )

Distinct

Order by ( based of enroll date etc.)

Session 8 – Aggregate functions

Select count(*) from students; - total number of records

Select count( DISTINCT student_company) from students; - no. of different companies students are
coming from

Select count(*) from students where batch_date like ’%-02-%’ ; - people enrolled in any batch of Feb

GROUP BY

Select source_of_joining, count(*) as total from students group by source_of_joining; - WORKS

Select source_of_joining, count(*) as total from students group by location; - WORKS


Select location, count(*) as total from students group by source_of_joining; - this will not work,
because select should also include source_of_joining which is used in grouping

Select location, source_of_joining, count(*) from students group by location, source_of_joining; -


Grouping on two parameters – first location then source of joining and showing individual count

Select selected_course, count(*) from students group by selected_course; - count number of


enrollments for each course

MIN & MAX

Select MIN(Y.O.E) from students;

Select MAX(Y.O.E) from students;

Select MIN(Y.O.E), student_fname from students; - This won’t work, MIN is independent, it won’t
know which name to fetch, it will only get the value

Select student_fname from students order by Y.O.E limit 1 – min. experience guy

select source_of_joining, MAX(y.o.e) from students group by source_of_joining; - max y.o.e of each
source of joining seperately

select source_of_joining, SUM(y.o.e) from students group by source_of_joining; - sum of y.o.e of


each source_of_joining seperately

select source_of_joining, AVG(y.o.e) from students group by source_of_joining; - average of y.o.e of


each source_of_joining seperately

select location, AVG(y.o.e) from students group by location; - average of y.o.e of each location
seperately

Session 9 – Data Types

Decimal(3,1) eg. 12.5, 3.5

Session 11 – Joins

Student table : Student_fname, student_lname, selected_course

Course table : Course_id, course_name

Select course_name from courses where course_id= (select selected_course from students where
student_fname =”Rahul”); - Nested query to find course_name

Select student_fname, student_lname, course_name from student JOIN courses ON


students.selected_course = courses.course_id; - by default it is a INNER JOIN, only matching records
will be shown / non matching records are discarded

LEFT OUTER JOIN


All the matching records + All the non matching records in the left table which does not have the
match in right table padded with NULL’s

Create table students_latest as select * from students; - to generate a table from a table

Create table courses_latest as select * from courses;

Select student_fname, student_lname, course_name from students_latest LEFT JOIN courses_latest


ON students_latest.selected_course = courses_latest.course_id;

LEFT OUTER JOIN

All the matching records + All the non matching records in the right table which does not have the
match in left table padded with NULL’s

Select student_fname, student_lname, course_name from students_latest RIGHT JOIN


courses_latest ON students_latest.selected_course = courses_latest.course_id;

FULL OUTER JOIN

All the matching records + non matching records from left + non matching records from right

Select student_fname, student_lname, course_name from students_latest LEFT JOIN courses_latest


ON students_latest.selected_course = courses_latest.course_id

UNION

Select student_fname, student_lname, course_name from students_latest RIGHT JOIN


courses_latest ON students_latest.selected_course = courses_latest.course_id ;

CROSS JOIN

Select * from students, courses; - total result : students * courses , all first table records are
matched with all record in second table

Select * from students JOIN courses; - same result, another way

Session 12 – Where vs HAVING

Select source_of_joining, count(*) as total from students group by source_of_joining;

Select source_of_joining, count(*) as total from students group by source_of_joining where total>1;
- This will not work because, where clause is used to filter the individual record before aggregation

Select source_of_joining, count(*) as total from students group by source_of_joining having total>1;

Having is used to filter the record after grouping/aggregation is done

Select source_of_joining, count(*) as total from students group by source_of_joining having


source_of_joining=”linkedin”; - Bad approach, we should filter as early as possible

Select source_of_joining, count(*) as total from students where source_of_joining=”linkedin” group


by source_of_joining; - Efficient approach, aggregating done early

Where & Having in same query


Location from which more than 1 student has joined and students experience >10 years.

Select location, count(*) as total from students where y_o_e >10 GROUP BY location HAVING total >
1;

Where – used before group by , filtering on individual record

Having – used after group by , filtering on aggregated record

You might also like