CRUD

 CRUD

Create:

Used to create database, table and to insert information in it.

syntax:
create database <database_name>;
create table <table_name> (
columns_name datatype constrains );

insert into table_name (columns) values (value1);


In insert into query you don't need to specify the columns.
syntax:
insert into film values(default, 'The Dark Knight', 'Batman fights the Joker', 2008, 1, NULL, 3,4.99,152, 19.99, 'PG-13', 'Trailer', default);

But issue is that you need to remember the order and datatype of all columns and you cannot skip any column and can change their order as to understand the values table need to map the value with respective columns and hence it will consider the definition and will put information in same order hence always giving column names and then value is preferred.

Drawbacks of using insert into command without column names in syntax:

  • Not good practice and make query prone to errors as columns are not specified and you need to remember order of columns to insert values into it.
  • As you can understand it made writing query tedious.
  • You need to specify values for all the columns and if count of columns are huge and most of them acquire default values or get autofill then it will cause an issue and inconvenience to write so many information in a query which is not maditory.

Read:

  • select - print
  • You may print constant data or data from table
  • Most used query

syntax Select:

to print constant value.

select constant_value;

To print whole table data:

select * from table_name;

* --> means record in a table.

To print specific columns from a table:

select col1, col2 from table_name;

Pseudo code: for select * from table_name;

table_name : [[],[],[],[]]
ans = [] - > Intermediate table for information extraction and to work with it without disturbing original table.
for row in table_name:
    ans.add(row)

for row in ans:
    print(row);

-- print student_id and full name of a student from student table.

select s_id, concat(first_name, last_name) as full_name 
from school.students;

select 'name' as info from students; -> It will print the constant named name with respect to records present in a table named students. It is used when you need to generate data for all the records for reference as dummy data for testing. It will help you to check the records and load and time complexity to execute a command for stress testing.


Distinct keyword:

It helps to get unique values from the table. Combination of columns will define it's behaviour as it's work is to find the distinct records and to display it.

select distinct * from students; -> it will check entire record and then will display distinct entries.
select distinct first_name from students; -> it will check only unique column information and will display it.

Rules to use it:

  • It should be first keyword after select keyword in a query.
  • It  can be applied on record or on a column or pair of columns or any number of columns as subset.
  • Filters out duplicates.
some more examples:

-- display all the years when movie released and entry is present in sakila database under film table.
select distinct release_year from sakila.film; 

select * from sakila.film;

--  from films table get distinct pairs of release years and ratings.
use sakila;
select distinct release_year, rating from film;

Pseudo code:
film: [[],[],[],[]]
ans= []
for row in film:
    ans.add(row)

filtered_ans = []
for row in ans:
    filtered_ans.add(row[release_year], row[rating])

unique_ans = set(filtered_ans)
print(unique_ans)

Operations on select queries:

-- Get title and length of each movie in hours?
select title, length/60
from film;

-- Get length of movies in approx whole number?
select round(length/60) as duration
from film;

-- Get length of movies in approx two decimal number?
select round(length/60, 2) as duration
from film;


-- Given length and rental duration of movies, get the number of times we can watch it?

select 
title, 
length, 
rental_duration, 
round(rental_duration/(length/60)) as possible_time_watched_movie 
from film;

-- round keyword will round the number to nearest whole number.
select round(8.8);

Inserting data from another table:

use school;

create table students_detail 
(
s_id int primary key auto_increment,
first_name varchar(100) not null,
last_name varchar(100) not null,
psp int not null,
marks int not null
);

insert into students_detail 
(first_name, last_name, psp, marks)
values
('Puneet ', 'Kumar Singh', 99, 100),
('Anu ' , 'Singh', 100, 100),
('Devansh ', 'Singh', 100, 100),
('Rupesh ', 'Khanna', 34, 12);


select * from students_detail;

create table student_info(
student_id int primary key auto_increment,
first_name varchar(100) not null,
last_name varchar(100) not null);

insert into student_info (first_name, last_name)
select first_name, last_name 
from students_detail;

select * from student_info;

Where clause (similar to if condition in coding):

It help to filter out the data and display result matching to filter data criteria and help to sample the data and even help to understand the data and help to perform many operations on selective data rather than doing on entire table unintentionally.

-- display all records from film table where rating if pg-13

select * from film where rating = 'pg-13'; 

select count(*) from film where rating = 'pg-13';

Pseudo code:
table_name =  [[],[],[],[],[]]
ans = []
for row in table_name:
    if row.matches(condition in where clause)
        ans.add(row)

for row in ans:
    print(row)

keywords to have multiple conditions to filter the data from a table:

AND, OR and not (NOT, <>, !=) keywords

-- Get all the movies which were released in 2006 and have rating as PG-13:
select title, release_year, rating 
from film
where release_year = 2006 and rating = 'PG-13';

-- Get all the movies which are relased in 2006 or having rating as PG-13:
select title, release_year, rating 
from film
where release_year = 2006 or rating = 'PG-13';

-- Get all the movies which are relased in 2006 and not having rating as PG-13:
select title, release_year, rating 
from film
where release_year = 2006 and  rating != 'PG-13';

select title, release_year, rating 
from film
where release_year = 2006 and  rating <> 'PG-13';

select title, release_year, rating 
from film
where release_year = 2006 and not rating = 'PG-13';

Order by clause:

It help to sort the data and display it in right order as per our requirement.

Now if you have sorted out the data with respect to any column and then that column has some conflicts or have same precesion or have same value then primary key will be used to sort the data and according to primary key data record will be sorted as per your requirement. So if you want to sort in decending order then primary key with smaller value will come first then other one will come if desired column is having a tie on a value for ordering the result. As you are not using primary key for ordering hence always smaller value of primary key will take position but if primary key is also present in list of order by clause then the order nature specified for the primary key will decide the value.

Note: Primary key is always a tie-breaker. You can have one of more columns for defining the desired ordering of data for sorting.


-- order the film name with respect to rental duration in desc and with rating in desc as well.
select film_id, title, rental_duration, rating 
from film
order by rental_duration desc, rating desc;

In operator:

If you want to check if list of data is present in a table then you can use in operator as it will help to use or condition with multiple values for information and hence to reduce or condition you can use in operator to help you in writing a clean a query.

syntax:

select * from 
table where value in (list of values);

-- show all movies which are from rating PG-13 and NC-17

select title, rating
from film 
where rating in ('PG-13', 'NC-17');

Note: It give advantage to have multiple values for searching the result and is very handy when you will use nested queries or sub-queries to derive desired result. As most of the time you are not sure how many information from a column will come for matching the result and hence in will save you as equal to will give error as it is restricted to have only single value for result.

Between Operator:

It helps to get values in a specific range of values. Most of the time used for timeline and to find the values which is in between some range. here starting value and ending value is also included in search for information so basically the search is a close bracket search including starting and ending value in range.

Syntax:
select * from film where release_year between 2006 and 2016;
Both 2006 and 2016 are included in range for searching the information.


Like Operator:

It will help to match the pattern in place of exact word, mostly used when you are not sure of exact word and have some idea of the work starting or ending and then you can match it for information.

  • Whenever there is a column storing string, theres comes a requirement to do some kind of pattern matching.
  • As most the time information is stored in table with respect to pattern or allowed naming convention. In this case like operator help us to fetch information and help to decide strategies to filter out right information as per requirement.

Like operator work with two wildcard operators:

  • '_' : Can have exactly one occurrence of a single character.
  • '%' :  Can have any number of character or it can stay empty as well.

How to use these wildcards:

  • %beg% - means we can have string before beg and after beg as well of any value and range or of any length.
  • %beg - any string ending with beg.
  • beg% - any string starting with beg.

Pattern matching practice and understanding with examples:
String - C a t
Pattern -
  • _ _ t - Yes it can match with the word.
  • % t - yes it can match as any string can come which will end with t and cat word follow this rule.
  • % - yes it can match as well as it means any word in this work will match it is like allowed for all.
  • %Cat% - Yes it will match as % can be replaced with null. It will make work unristricted, example: catterpiller havign cat in it, concat as having cat in it. 
  • _Cat_ - It will not match the pattern as it need to have some value and _ cannot be null so it will not match

Get data of all the morning batches:

select * 
from batches
where batch_name like '%morn%';
If you want it to be case sensitive then need to use binary keyword before the column name in where clause.

select *
from batches 
where binary batch_name like '%Morn%';

-- select all the movies which have love word in it.

-- to make case sensitive selection of value. Binary keyword use.
select *
from sakila.film
where binary title like '%love';


select *
from sakila.film
where title like '%love';

Null operator:

Any column is need to be marked as empty it means it need to store null value it is datatype independent.
Now null is special case you cannot consider any empty string as null as empty string datatype is string and null is not having datatype it means does not exist.

Example to understand null value.
select * from student where status = NULL;
It will not work.

Reason:
select 1=1; -> It will return true means 1
select 2 = 21; -> It will return false means 0
select null = null; -> It will return false as null is not equal to null. So null is not equal to anything. 
select null != null; will also return false. So it cannot be compared with anything.

In layman language we can say that empty glass != empty brain it means empty is common property but to two different things. So in short null is a feeling or behaviour hence they can't be compared.

so to compare the null we need to use is null and is not null keywords. As these keywords will use mechanism to identify the value is defined or not.

example:
select * from student where status is null;
select * from student where status is not null;


-- select all students who don't have any batches yet.
select * from students where batch_id is null;

-- select all students who has assigned batch_id
select * from students where batch_id is not null;


Limit clause:

It will help to limit the rows a table can return as output.
It is used when we have a table with huge amount of data but to decide the nature of data we just need to observe some data as sample data then to limit the data to sample size we need to use limit clause.

-- to check only two records of output data.
select * from students limit 2;

select * from film limit 6 offset 24;

Here offset means start your count of limit after row number 24. So now result will from row number 25 to 30.

-- limit last 10 rows of data from table film.
use sakila;
select * from (select * from film
order by film_id desc) as a limit 10;

It will also work.

select * from film
order by film_id desc
limit 10;


Update operation:

It will help you to correct the value present in a column if you have entered wrong information by mistake.

syntax:

update table <table_name> set col_name = value where conditions;

example:
update table students set first_name = 'Rohit'
where id = 3;

As it will help you to update only the desired row of a table.

example:
use school;
select * from students;

update students set first_name = 'Rohit'
where s_id = 6;

set sql_safe_update = 0 -> It will help to allow updating the data in a table without any safety and will allow to update values without using where clause. It is not recommended.

Delete VS Truncate VS Drop Operations:

Delete:
 Removes specified rows one-by-one from table and can delete all rows as well if no where condition is provided to identify the specific rows for deletion.

Must be used wisely.

Syntax:
delete from table_name where conditions;
It will iterate the data and once identify the right data then it will delete it.

In short it means iterate the records and then remove identified records. So iterate and delete operation is performed by default.

Time complexity - T.C = O(n)
You can undo the deletion task as it is roll-backable.

Truncate:
Removes the complete table and then recreates it.It is used when you want to empty the table.
Basically truncate command dereference the memory of table. It will create another table with same column name and nature but this new table is not going to have any data and once it get created then old table will be referred to this new table in memory and as a result you will loose the data and old memory location of table which hold this data.


Query: Truncate table_name;



example:
student -> 001 (memory location)
after truncate student -> 007 (location) as a result data stored over location 001 is now lost.

As it shifts the memory location hence you cannot rollback it.It means data cannot be recovered.


Drop:

It is used to remove table and it's structure as well.

Query: drop table table_name;

You cannot role it back. Here you are dereferencing the table memory location and even removing the metadata of the table which help you to know about the table and select it.

Some keypoints to remember:
If you use delete command to remove the record then insert new record then counter of id will start after the deleted record id number. example you have deleted the last record numbered 6 then entered new record then id will be 7 and will not be 6. But if use truncate command then id will be reset as new table is created over new location. So id will be reset to 0.

drop students_copy; -> it will not work as you have not specified what you are trying to drop a table or something else.

In SQL world as well garbage collector concept exist which will free the memory after sometime once an memory is dereferenced.



Delete command property:
  • Slower than Truncate
  • Doesn't reset the key
  • It can be rolled back.
  • Schema is preserved.
Truncate command property:
  • Faster than delete
  • resets the key
  • it cannot be rolled back because the complete table is deleted as an intermediate step.
  • Schema is preserved.

Drop command property:
  • Cannot be rolled back
  • don't preserve the schema






Comments

Popular posts from this blog

Aggregate Queries and Views

Schema Design

Transactions in SQL