MySQL Theory

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 50

Contents

MySQL...................................................................................................................................................2
Create Table..........................................................................................................................................2
Create columns..................................................................................................................................3
create rows........................................................................................................................................4
Select.....................................................................................................................................................6
update and delete.................................................................................................................................7
Alter usage.............................................................................................................................................9
Autocommit, Commit, Rollback.............................................................................................................9
Current_time(), current_date(), date_format(date, format)...............................................................10
Unique.................................................................................................................................................10
Not null................................................................................................................................................11
check...................................................................................................................................................12
default.................................................................................................................................................13
Primary key..........................................................................................................................................14
Auto increment...................................................................................................................................15
Foreign key..........................................................................................................................................16
on delete.............................................................................................................................................17
Joins.....................................................................................................................................................20
Functions.............................................................................................................................................26
logical operators(and, or, not).............................................................................................................26
wild cards............................................................................................................................................27
order by...............................................................................................................................................28
limit.....................................................................................................................................................28
Union...................................................................................................................................................29
Views...................................................................................................................................................32
Indexes................................................................................................................................................32
Subquery.............................................................................................................................................32
Grouped by..........................................................................................................................................33
rollup...................................................................................................................................................34
stored procedures...............................................................................................................................35
triggers................................................................................................................................................37
Case.....................................................................................................................................................40
Aliansing..............................................................................................................................................42
Partition By..........................................................................................................................................43
CTE.......................................................................................................................................................44
TempTable...........................................................................................................................................45
String Functions...................................................................................................................................46

MySQL
1. Create database name; - მონაცემთა ბაზის შექმნა.
2. Use database name; - მოხდება მხოლოდ ის რომ ჩამოიშლება მონაცემთა ბაზა.
3. Drop database „name“ ; - წაიშლება მონაცემთა ბაზა.
USE [Data Analyst Bootcamp];
4. Alter database “name” read only = 1; - კითხვის მოდზეა და მასზე ზემოქმედება
შეუძლებელია. არც წაშლა შეიძლება.
ALTER DATABASE [Data Analyst Bootcamp] SET READ_ONLY;
ALTER DATABASE [Data Analyst Bootcamp] SET READ_WRITE;

Create Table

Syntax:
CREATE TABLE [database_name.][schema_name.]table_name (
column_definition1,
column_definition2,
........,
table_constraints
);

1. ცხრილის სვეტების შექმნა.

create table employees (

employee_id int,

first_name varchar(50),

last_name varchar(50),

hourly_pay decimal(5, 2),

hire_date date
);

select * from employees;

2. ცხრილის სახელის შეცვლა.

rename table employees to workers;

EXEC sp_rename 'employees', 'workers';

drop table workers;

DROP TABLE [database_name.][schema_name.]table_name;

Create columns

1. სვეტის დამატება, რომელსაც განსაზღვრული ექნება რამდენი ასოსგან უნდა


შედგებოდეს.

alter table workers

add phone_number varchar(15);

select * from workers;

2. სვეტის სახელის შეცვლა.

alter table workers

rename column phone_number to email

EXEC sp_rename 'workers.phone_number', 'email', 'COLUMN';

select * from workers;

3. იცვლება კონკრეტული სვეტის თვისება.

alter table workers

modify column email varchar(100);

ALTER TABLE workers


ALTER COLUMN first_name VARCHAR(100);
4. იცვლება სვეტის ადგილი.

alter table workers

modify email varchar(100)

after last_name; first;

select * from workers


impossible to do that operation. It’s needed to be recreated the column and old column
data copied there!
5. წაიშლება სვეტი.

alter table workers

drop column email;

select * from workers

create rows

Syntax:

INSERT INTO [database_name].[dbo].[table_name]


(column_name1, column_name2, ... )
VALUES
(value1, value2, ... );

1. ვამატებთ სტრიქონს.

insert into workers

values (1, 'Eugene', 'krabs', 25.50, '2023-01-02');

select * from workers;

2. ვამატებთ რამდენიმე სტრიქონს.

insert into workers

values (2, "squidward", "tentacle", 15.00, "2023-01-03"),

(3, "spongebob", "squarepants", 12.00, "2023-01-04"),

(4, "patrick", "star", 12.50, "2023-01-05"),

(5, "sandy", "cheeks", 17.50, "2023-01-06");

select * from workers

3. ვამატებთ კონკრეტულ მახასიათებლებს მხოლოდ.

insert into workers (employee_id, first_name, last_name)

values (6, "shelden", "plankton");

select * from workers

4. We can get one table values into another one

-- Create the Student table


CREATE TABLE Student (
StudentID INT PRIMARY KEY,

Name VARCHAR(100),

Gender CHAR(1),

Marks DECIMAL(5, 2)

);

-- Create the Student_info table


CREATE TABLE Student_info (

StudentID INT PRIMARY KEY,

Name VARCHAR(100),

Gender CHAR(1),

Marks DECIMAL(5, 2)

);

-- Insert some sample data into the Student table


INSERT INTO Student (StudentID, Name, Gender, Marks)

VALUES

(1, 'John', 'M', 85.5),

(2, 'Alice', 'F', 90.2),

(3, 'Bob', 'M', 78.9);

-- Execute the INSERT INTO SELECT statement to copy data from Student to Student_info
INSERT INTO Student_info (StudentID, Name, Gender, Marks)

SELECT StudentID, Name, Gender, Marks

FROM Student;

Select

Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition
GROUP BY column_name
HAVING condition
ORDER BY column_name ASC|DESC;

Functions
1. Min

SELECT MIN ( DISTINCT aggregate_expression)


FROM table_name(s)
[WHERE conditions];
2. Max

SELECT MAX ( DISTINCT aggregate_expression)


FROM table_name(s)
[WHERE conditions];

3. Sum

SELECT SUM( DISTINCT aggregate_expression)


FROM table_name(s)
[WHERE conditions];

4. Count

SELECT AVG(ALL | DISTINCT expression)


FROM table_name(s)
[WHERE conditions];

5. Avg

SELECT COUNT(expression)
FROM table_name(s)
[WHERE conditions];

CREATE TABLE sales (


product_id INT,
revenue DECIMAL(10, 2)
);

INSERT INTO sales (product_id, revenue) VALUES (1, 1200);


INSERT INTO sales (product_id, revenue) VALUES (2, 1500);
INSERT INTO sales (product_id, revenue) VALUES (3, 1000);
INSERT INTO sales (product_id, revenue) VALUES (4, 1200);
INSERT INTO sales (product_id, revenue) VALUES (1, 1300);
INSERT INTO sales (product_id, revenue) VALUES (2, 1300);
INSERT INTO sales (product_id, revenue) VALUES (3, 1100);
INSERT INTO sales (product_id, revenue) VALUES (4, 1400);

SELECT
AVG(ALL revenue) AS average_revenue_all,
AVG(DISTINCT revenue) AS average_revenue_distinct
FROM
sales
WHERE
revenue > 1000;

comparison symbols

Inde Comparison Description


x Operator

1) = It specifies equal symbol.

2) <> It specifies not equal symbol.

3) != It specifies not equal symbol.

4) > It specifies greater than symbol.

5) >= It specifies greater than or equal symbol.

6) < It specifies less than symbol.

7) <= It specifies less than or equal symbol.

8) !> It specifies not greater than symbol.

9) !< It specifies not less than symbol.

10) IN ( ) It matches a value in a list.

11) NOT It is used to negate a condition.

12) BETWEEN It is used to specify within a range (inclusive)


value.

13) IS NULL It specifies null value.

14) IS NOT NULL It specifies non-null value.

15) LIKE It specifies pattern matching with % and _

16) EXISTS It specifies that the condition is met if subquery


returns at least one row.

Server operators

1. Intersect:
-- Creating sample tables
CREATE TABLE employees (
employee_id INT,
employee_name VARCHAR(50)
);

CREATE TABLE managers (


manager_id INT,
manager_name VARCHAR(50)
);

-- Populating sample data into tables


INSERT INTO employees (employee_id, employee_name) VALUES
(1, 'John'),
(2, 'Alice'),
(3, 'Bob'),
(4, 'Emma');

INSERT INTO managers (manager_id, manager_name) VALUES


(1, 'John'),
(3, 'Bob'),
(5, 'Eva');

-- Query using INTERSECT


SELECT employee_id, employee_name
FROM employees

INTERSECT

SELECT manager_id, manager_name


FROM managers;
2. In:
SELECT *
FROM [javatpoint].[dbo].[Employees]
WHERE name IN ('Mahesh', 'Lily', 'Rahul');
3. Not:
SELECT *
FROM [javatpoint].[dbo].[Employees]
WHERE name NOT IN ('Mahesh', 'Mohan', 'Chitra');
4. Between:
SELECT *
FROM [javatpoint].[dbo].[Employees]
WHERE id BETWEEN 7 AND 13;
5. Is Null:
SELECT *
FROM [javatpoint].[dbo].[Employees]
WHERE salary IS NULL;
6. Is Not Null:
SELECT *
FROM [javatpoint].[dbo].[Employees]
WHERE salary IS NOT NULL;
7. Like:

Wildcard Explanation

% It is used to match any string of any length (including zero length).

_ It is used to match on a single character.

[] It is used to match on any character in the [ ] brackets (for example, [abc]


would match on a, b, or c characters)

[^] It is used to match on any character not in the [^] brackets (for example,
[^abc] would match on any character that is not a, b, or c characters)

%:
select * from employees

where first_name like "s%";

select * from employees

where first_name like "sp%";

select * from employees

where first_name like "%b";

SELECT *
FROM [javatpoint].[dbo].[Student]
WHERE name NOT LIKE 'A%';

_ABC_
select * from employees

where job like "ca_hie_";

select * from employees

where job like "_a%";

[ABC]
SELECT *
FROM [javatpoint].[dbo].[Student]
WHERE name LIKE 'Aj[ie]et%';

8. EXISTS:
-- Creating sample tables
CREATE TABLE customers (
customer_id INT,
customer_name VARCHAR(50)
);

CREATE TABLE orders (


order_id INT,
customer_id INT,
order_date DATE
);

-- Populating sample data into tables


INSERT INTO customers (customer_id, customer_name) VALUES
(1, 'John'),
(2, 'Alice'),
(3, 'Bob'),
(4, 'Emma');

INSERT INTO orders (order_id, customer_id, order_date) VALUES


(101, 1, '2024-03-20'),
(102, 2, '2024-03-21'),
(103, 3, '2024-03-22'),
(104, 1, '2024-03-23'),
(105, 3, '2024-03-24');

SELECT customer_id, customer_name


FROM customers AS c
WHERE EXISTS (
SELECT *
FROM orders AS o
WHERE o.customer_id = c.customer_id
);

update and delete


Update Syntax:

UPDATE [database_name].[ schema_name].table_name


SET column1 = new_value1,
column2 = new_value2, ...
[WHERE Clause]

1. როცა გვინდა ცხრილში ცვლილებების შეტანა.

UPDATE workers

SET hourly_pay = 10.25, hire_date = "2023-01-07"

WHERE employee_id = 6

limit 1;

SELECT * FROM workers;

UPDATE TOP(1) workers


SET hourly_pay = 10.25, hire_date = '2023-01-07'
WHERE employee_id = 6;

SELECT * FROM workers;

UPDATE workers

SET hourly_pay = 10.25, hire_date = null

WHERE employee_id = 6

limit 1;

SELECT * FROM workers;

UPDATE top (1) workers


SET hourly_pay = 10.25, hire_date = null
WHERE employee_id = 6
SELECT * FROM workers;

UPDATE workers

SET hourly_pay = 10.25, hire_date = NULL

WHERE employee_id = 6;

SELECT * FROM workers;

We can do this without actual script an with SQL. Clicking right button of mouse and search script
table as and then we find what we need and get script. Only one thing needed is to replace our new
data and execute.

DELETE FROM [javatpoint].[dbo].[STUDENT]


WHERE ID =3;

delete from workers

where employee_id = 6;

SELECT * FROM workers;

DELETE TOP (top_value) [ PERCENT ]


FROM [database_name].[dbo].[table_name]
[WHERE conditions];

TOP (top_value): It is used to delete the top number of rows in the result
set based on top_value. For example, TOP(10) would delete the top 10
rows matching the delete criteria.

PERCENT: It is optional. It is used to delete the percentage of of top rows.


For example, TOP(10) PERCENT would delete the top 10% of the records
matching the delete criteria.

Alter usage

 ALTER TABLE table_name ADD column_name data_type column_constraints;


 ALTER TABLE table_name
ADD column_name1 column_definition,
ADD column_name2 column_definition;

 ALTER TABLE table_name DROP COLUMN column_name;

 ALTER TABLE table_name


DROP COLUMN column_name1, DROP COLUMN column_name2...

 ALTER TABLE table_name ALTER COLUMN column_name new_data_type(size);

 ALTER TABLE table_name


ADD CONSTRAINT [constraint_name] PRIMARY KEY ([column_name])

 ALTER TABLE Student ADD CONSTRAINT PrimaryKey PRIMARY KEY (Id)

 ALTER TABLE table_name DROP CONSTRAINT [constraint_name]

 ALTER TABLE Student ALTER COLUMN Age VARCHAR (10) NOT NULL;

Autocommit, Commit, Rollback


1. Autocommit = off თუ ამას გამოვრთავთ დაუყოვნებლივ აღარ შეინახება.
ყოველ შესვლზე თავიდან უნდა დავაყენოთ.
BEGIN TRANSACTION;
2. Commit; როცა ამას ავკრებთ შეინახება.
3. Rollback; უკან დააბრუნებს ან commit- ამდე როცა გამოვრთეთ Autocommit.

Current_time(), current_date(),

date_format(date, format)
CREATE TABLE test (

current_date_column DATE,

current_time_column TIME,

current_datetime_column DATETIME

);

insert into test

values(current_date(), current_time(),now());

select * from test;

INSERT INTO test


VALUES (CAST(GETDATE() AS DATE), CAST(GETDATE() AS TIME),
GETDATE());

SELECT * FROM test;

SELECT DATE_FORMAT(order_date, 'll+%e, %Y') AS formatted_date

FROM orders;

SELECT FORMAT(current_date_column, 'll+dd, yyyy') AS


formatted_date
FROM test;

Unique
1. პირველი გზა, თუ როგორ მივანიჭოთ უნიკალური ხარისხი შექმნისას.

create table products(

product_id int,

product_name varchar(25) unique,

price decimal(4, 2)

);

1. მეორე გზა, თუ როგორ მივანიჭოთ უნიკალური ხარისხი შექმნის შემდეგ.

alter table products

add constraint

unique(price);

ALTER TABLE products


ADD CONSTRAINT UQ_Price UNIQUE (price);
საბოლოოდ უბრალოდ აღარ შეიძლება უნიკალურ სვეტში გამეორება მნიშვნელობის .

როცა გვინდა მოვაშოროთ unique:

alter table employees

add constraint this_one unique(active_status);

alter table employees

drop index this_one;

ALTER TABLE dbo.products


DROP CONSTRAINT this_one;
Not null
გზა 1:

CREATE TABLE product (

product_id INT,

product_name VARCHAR(25),

price DECIMAL(4,2) NOT NULL

);

გზა 2:

alter table products

modify price decimal(4,2) not null;

ALTER TABLE product


ALTER COLUMN product_id int NOT NULL;
როცა გვინდა მოვხსნათ not null:

alter table time

modify my_date date null;

ALTER TABLE product


ALTER COLUMN product_id INT NULL;

check
CREATE TABLE employees (

employee_id INT,

first_name VARCHAR(50),

last_name VARCHAR(50),

hourly_pay DECIMAL(5, 2) CHECK(hourly_pay >= 10.00),

hire_date DATE

);

CREATE TABLE employeesssssss (


employee_id INT,

first_name VARCHAR(50),

last_name VARCHAR(50),

hourly_pay DECIMAL(5, 2),

hire_date DATE,

check (hourly_pay >= 10.00)

);

CREATE TABLE nika (

employee_id INT,

first_name VARCHAR(50),

last_name VARCHAR(50),

hourly_pay DECIMAL(5, 2),

hire_date DATE,

constraint chk_hourly_pay check (hourly_pay >= 10.00)

);

alter table employees

add constraint chk_hourly_pay check (hourly_pay >= 10.00);

alter table employees

drop check chk_hourly_pay;

alter table employees


drop constraint chk_hourly_pay1;

default
1. Default - ად დადების გზა.

create table products (

product_id int,

product_name varchar(25),
price decimal(4, 2) default 2);

2. Default - ად დადების გზა.

alter table products

alter price set default 2;

ALTER TABLE products


ADD CONSTRAINT DF_Price DEFAULT 2 FOR price;

insert into products (product_id, product_name)

values(1, "DF"), (2, "eg"), (3, "4"), (5, "6");

select *from products;

insert into products (product_id, product_name)


values(6, 'DF'), (7, 'eg'), (8, '4'), (9, '6');
select *from products;
როცა default მნიშვნელობის წაშლა გვინდა.

ALTER TABLE table_name

ALTER COLUMN column_name DROP DEFAULT;

ALTER TABLE products


drop constraint DF_Price;

Primary key
ძირითადი გასაღების სვეტები არ შეიძლება შეიცავდეს NULL მნიშვნელობებს .
თითოეულ მწკრივს უნდა ჰქონდეს უნიკალური, არა null მნიშვნელობა პირველადი
გასაღების სვეტებში.

create table transactions(

transaction_id int primary key,

amount decimal(5, 2)

);

Select * from transaction;

alter table transactions

add constraint
primary key(transaction_id);

select * from transactions;

ALTER TABLE transactions


ADD CONSTRAINT primary_key PRIMARY KEY (transaction_id);

ALTER TABLE transactions


ADD PRIMARY KEY (transaction_id);

CREATE TABLE your_table_name (

column1 data_type,

column2 data_type,

PRIMARY KEY (column1, column2)

);

CREATE TABLE transactions (


name varchar(50),
age int,
CONSTRAINT nick PRIMARY KEY (name, age)
);

ALTER TABLE your_table_name

DROP PRIMARY KEY;

ALTER TABLE transactions


DROP constraint key_name;

Auto increment
როცა დაემატება ახალი სტრიქონი, ერთით გაიზრდება იმ სვეტში სადაცდადებულია ეს
მოთხოვნა.

create table transactions (

transactions_id int primary key auto_increment,

amount decimal(5, 2)

);
CREATE TABLE transactions (
transactions_id int IDENTITY(1,1) PRIMARY KEY,
amount decimal(5, 2)
);

ALTER TABLE transactions

AUTO_INCREMENT = 100;

Auto_increment = 100; ნიშნავს რომ 100 იქნება პირველი წევრი, და აქედან გაიზრდება
ერთით.

DBCC CHECKIDENT ('transactions', NORESEED);

DBCC CHECKIDENT ('transactions', RESEED, 99);

Foreign key
შევქმენით ერთი ცხრილი და შევიტანეთ მონაცემები.

create table customers(

customer_id int primary key auto_increment,

first_name varchar(50),

last_name varchar(50)

);

insert into customers (first_name, last_name)

values ("fred","fish"), ("larry","lobster"), ("bubble","bass");

select * from customers;

შევქმენით მეორე ცხრილი და ერთ ერთი წვეტის კავშირისთვის მეორე ცხრილთან


დავამატეთ foreign key.

create table transactions (

transaction_id int primary key auto_increment,

amount decimal(5, 2),

customer_id int,

foreign key(customer_id) references customers(customer_id)


);

ტრანზაქციების ცხრილში მომხმარებლის id კავშირშია მომხმარებლების ცხრილთან.


მისი მეშვეობით შეგვიძლია ვიპოვოთ სახელი და გვარი.

Foreign key-ს მოშორება.

alter table transactions

drop foreign key transactions_ibfk_1;

თუ გვინდა რომ ჩვენი სახელი დავარქვათ.

alter table transactions

add constraint fk_customer_id

foreign key(customer_id) references customers(customer_id);

alter table transactions

auto_increment = 1000;

insert into transactions (amount, customer_id)

values (3.99, 3), (2.89, 2),(3.38, 3), (4.99, 1);

delete from customers where customer_id = 3;

on delete

ON DELETE CASCADE:
When a foreign key relationship is defined with ON DELETE
CASCADE, it means that if a record in the parent table is deleted,
all corresponding records in the child table will also be deleted
automatically. In other words, the deletion of a parent record
cascades down to the child records, ensuring referential
integrity.
Here's an example:
Suppose you have two tables, authors and books, where books has
a foreign key referencing the authors table:
If you have a record in the authors table and corresponding
records in the books table, and you delete the author record, all
related book records for that author will be automatically
deleted as well.

CREATE TABLE authors (


author_id INT PRIMARY KEY,
author_name VARCHAR(50)
);

CREATE TABLE books (


book_id INT PRIMARY KEY,
book_title VARCHAR(100),
author_id INT,
FOREIGN KEY (author_id) REFERENCES authors(author_id) ON
DELETE CASCADE
);

ON DELETE SET NULL:


When a foreign key relationship is defined with ON DELETE SET
NULL, it means that if a record in the parent table is deleted, the
corresponding foreign key values in the child table will be set to
NULL, effectively breaking the link between the child and parent
records. If you delete a student record in the students table, the
student_id values in the enrollments table for that student will be set to
NULL, indicating that the student is no longer enrolled in any courses.
Here's an example:

CREATE TABLE students (


student_id INT PRIMARY KEY,
student_name VARCHAR(50)
);

CREATE TABLE enrollments (


enrollment_id INT PRIMARY KEY,
student_id INT,
course_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
ON DELETE SET NULL,
FOREIGN KEY (course_id) REFERENCES courses(course_id)
);

როცა შექმნილია ცხრილი და გვინდა შემდეგ დავამატოთ.

ALTER TABLE enrollments


DROP FOREIGN KEY fk_student_id,
ADD CONSTRAINT fk_student_id
FOREIGN KEY (student_id)
REFERENCES students(student_id)
ON DELETE SET NULL; -- Set the ON DELETE SET NULL option
Joins
Tables:
REATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50),
Position VARCHAR(50)
);

INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Position)


VALUES
(1, 'John', 'Doe', 'HR', 'Manager'),
(2, 'Jane', 'Smith', 'Marketing', 'Analyst'),
(3, 'Alice', 'Johnson', 'Finance', 'Accountant'),
(4, 'Bob', 'Williams', 'IT', 'Developer'),
(5, 'Emily', 'Brown', 'Operations', 'Supervisor'),
(6, 'Michael', 'Johnson', 'Sales', 'Sales Representative'),
(7, 'Samantha', 'Clark', 'Customer Service', 'Representative'),
(8, 'David', 'Martinez', 'Research & Development', 'Research Scientist'),
(9, 'Jennifer', 'Lee', 'Human Resources', 'HR Assistant'),
(10, 'Andrew', 'Garcia', 'Finance', 'Financial Analyst');

CREATE TABLE Salaries (


EmployeeID INT PRIMARY KEY,
Salary DECIMAL(10, 2)
);

INSERT INTO Salaries (EmployeeID, Salary)


VALUES
(1, 60000.00),
(2, 50000.00),
(3, 55000.00),
(4, 65000.00),
(5, 58000.00),
(6, 62000.00),
(7, 48000.00),
(8, 70000.00),
(9, 45000.00),
(10, 58000.00),
(11, 53000.00),
(12, 64000.00),
(13, 51000.00),
(14, 59000.00),
(15, 56000.00);

select * from Employees


select * from Salaries
1. Inner join:

Table A Table B

SELECT Employees.EmployeeID, Employees.FirstName, Employees.LastName,


Employees.Department, Employees.Position, Salaries.Salary
FROM Employees
INNER JOIN Salaries ON Employees.EmployeeID = Salaries.EmployeeID;

 In inner join case we get what is mutual in terms of id or what is


matched.
2. Left outer join:

Table A Table B

SELECT *
FROM Salaries
left JOIN Employees ON Salaries.EmployeeID = Employees.EmployeeID;
 Salaries are writtern because of firstly it is given and then employees are
accomodated.

3. Right outer join:

Table A Table B

SELECT *
FROM Salaries
right outer JOIN Employees ON Salaries.EmployeeID =
Employees.EmployeeID;
 Here first employees are written because this is at the right side and the
salaries are accommodated.
4. Full outer join:

Table A Table B

SELECT
Employees.EmployeeID,
Employees.FirstName,
Employees.LastName,
Employees.Department,
Employees.Position,
Salaries.Salary
FROM
Employees
FULL OUTER JOIN
Salaries ON Employees.EmployeeID = Salaries.EmployeeID;

 Here all is written, does not matter which one is taken first.
5. Cross join:

SELECT
FROM
Employees
cross JOIN
Salaries;

 It has 150 value and checks all possible matches.

6. Self join:

CREATE TABLE employee (

employee_id INT PRIMARY KEY,

name VARCHAR(255),

supervisor_id INT

);

INSERT INTO employee (employee_id, name, supervisor_id)

VALUES

(1, 'Alice', NULL), -- Alice is the top-level manager

(2, 'Bob', 1), -- Bob reports to Alice

(3, 'Charlie', 1), -- Charlie also reports to Alice

(4, 'David', 2); -- David reports to Bob

SELECT *

FROM employee AS e1

LEFT JOIN employee AS e2

ON e1.supervisor_id = e2.employee_id;

select * from employee;

სასარგებლოა როცა გვინდა ერთ ცხრილში მოცემული მონაცემები დავალაგოთ


იერარქიულად.

 ალისი არავიზე არაა დაქვემდებარებული


 ბობი ალისზეა
 ჩარლი ალისზეა
 დავიდი ბობზე

CREATE TABLE Categories (


CategoryID INT PRIMARY KEY,
CategoryName VARCHAR(50),
ParentCategoryID INT
);

INSERT INTO Categories (CategoryID, CategoryName, ParentCategoryID)


VALUES
(1, 'Electronics', NULL), -- Top-level category
(2, 'Computers', 1), -- Sub-category under Electronics
(3, 'Laptops', 2), -- Sub-category under Computers
(4, 'Smartphones', 1), -- Sub-category under Electronics
(5, 'Clothing', NULL), -- Another top-level category
(6, 'Men''s Clothing', 5), -- Sub-category under Clothing
(7, 'Women''s Clothing', 5); -- Sub-category under Clothing

SELECT c.CategoryID, c.CategoryName, c.ParentCategoryID,


p.CategoryName AS ParentCategoryName
FROM Categories c
LEFT JOIN Categories p ON c.ParentCategoryID = p.CategoryID;

Case study:
SELECT Employees.FirstName, AVG(Salaries.Salary) AS Average_salary
FROM [Data Analyst Bootcamp].[dbo].Employees
LEFT JOIN [Data Analyst Bootcamp].[dbo].[Salaries]
ON Employees.EmployeeID = Salaries.EmployeeID
WHERE Employees.FirstName != 'Bob'
GROUP BY Employees.FirstName
ORDER BY Average_salary DESC;
 Here David is 2 in company and because they are
grouped there is one David and there average.

Functions
რამდენი სტრიქონია.

select count(amount)

from transactions;

შეგვიძლია where-ით უფრო დავაკონკრეტოთ.

select count(amount) as "today"

from transactions where customer_id > 2;

select max(amount) as "max"

from transactions where customer_id > 2;

select avg(amount) as "average"

from transactions where customer_id > 2;

select sum(amount) as "average"

from transactions where customer_id > 2;

select concat(first_name," ", last_name) as full_name

from customers;
logical operators(and, or, not)
select * from employees

where hire_date < "2023-01-5" and job = "cook";

select * from employees

where hire_date < "2023-01-5" or job = "cook";

select * from employees

where not hire_date < "2023-01-5" and not job = "asst. manager";

select * from employees

where hire_date between "2023-01-04" and "2023-01-07";

select * from employees

where job in ("cook", "cashier", "janitor");

order by
select * from employees

order by last_name desc/asc;

select * from transactions

order by customer_id asc, amount desc;


CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Salary DECIMAL(10, 2)
);

INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary) VALUES (1,


'John', 'Doe', 50000.00);
INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary) VALUES (2,
'Alice', 'Smith', 60000.00);
INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary) VALUES (3,
'Bob', 'Jones', 55000.00);
INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary) VALUES (4,
'Emily', 'Johnson', 62000.00);
INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary) VALUES (5,
'Michael', 'Williams', 58000.00);
INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary) VALUES (6,
'Sophia', 'Brown', 63000.00);
INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary) VALUES (7,
'Matthew', 'Miller', 57000.00);
INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary) VALUES (8,
'Emma', 'Davis', 59000.00);

SELECT EmployeeID, FirstName, LastName, Salary


FROM Employees
ORDER BY Salary DESC;

select * from Employees

limit
select * from customers

limit 6;

select * from customers

order by last_name desc limit 3;

select * from customers

limit 2, 1;

Union

Syntax:

SELECT expression1, expression2, ... expression_n


FROM tables
[WHERE conditions]
UNION
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions];

 UNION combines the results of multiple SELECT queries into a single result set, removing
duplicates.
 UNION ALL also combines the results of multiple SELECT queries into a single result set, but
it retains all rows, including duplicates.

Example 1:
-- Create CourseA table
CREATE TABLE CourseA (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
CourseName VARCHAR(50)
);

-- Insert sample data into CourseA table


INSERT INTO CourseA (StudentID, FirstName, LastName, CourseName)
VALUES
(1, 'John', 'Doe', 'Math'),
(2, 'Jane', 'Smith', 'Science'),
(3, 'Alice', 'Johnson', 'English');

-- Create CourseB table


CREATE TABLE CourseB (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
CourseName VARCHAR(50)
);

-- Insert sample data into CourseB table


INSERT INTO CourseB (StudentID, FirstName, LastName, CourseName)
VALUES
(4, 'Bob', 'Williams', 'History'),
(5, 'Emily', 'Brown', 'Geography'),
(6, 'Michael', 'Johnson', 'Computer Science');

-- Retrieve data using UNION


SELECT StudentID, FirstName, LastName, CourseName
FROM CourseA
UNION
SELECT StudentID, FirstName, LastName, CourseName
FROM CourseB;
Example 2:
-- Create Students table
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Grade VARCHAR(10)
);

-- Insert sample data into Students table


INSERT INTO Students (StudentID, FirstName, LastName, Grade)
VALUES
(1, 'John', 'Doe', 'A'),
(2, 'Jane', 'Smith', 'B'),
(3, 'Alice', 'Johnson', 'A');

-- Create Teachers table


CREATE TABLE Teachers (
TeacherID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Subject VARCHAR(50)
);

-- Insert sample data into Teachers table


INSERT INTO Teachers (TeacherID, FirstName, LastName, Subject)
VALUES
(1, 'Mr.', 'Brown', 'Math'),
(2, 'Mrs.', 'Davis', 'English');

-- Retrieve data using UNION


SELECT StudentID, FirstName, LastName, Grade
FROM Students
UNION
SELECT TeacherID, FirstName, LastName, Subject AS Grade
FROM Teachers;

Example 3:
-- Create TableA
CREATE TABLE TableA (
ID INT,
Name VARCHAR(50)
);

-- Insert sample data into TableA


INSERT INTO TableA (ID, Name) VALUES
(1, 'John'),
(2, 'Jane'),
(3, 'Alice');

-- Create TableB
CREATE TABLE TableB (
ID INT,
Name VARCHAR(50)
);

-- Insert sample data into TableB


INSERT INTO TableB (ID, Name) VALUES
(2, 'Jane'),
(3, 'Alice'),
(4, 'Bob');

-- UNION
SELECT * FROM TableA
UNION
SELECT * FROM TableB;

-- UNION ALL
SELECT * FROM TableA
UNION ALL
SELECT * FROM TableB;

 Main thing with union is that column numbers must be same and type
must be also same(name is not needed to be the same).

Views
create view employee_attandance as

select first_name, last_name from employees;

view კატეგორიაში დაემატება ის სვეტები რომელიც მივუთითეთ, ეს არის ხედვა და


შეგვიძლია მანიპულაცია. მიდი სარგებელი არის ის რომ არ გვიწევს ახალი ცხრილის
შექმნა.

Indexes
მონაცემის ძებნის პროცესი მიმდინარეობს ჯერ იწყებს პირველი სტრიქონიდან და
ჩადის ბოლოში. ინდექსით კი მხოლოდ ერთ სვეტს ამოწმებს. ეს კარგია როცა დიდი
მონაცემი გვაქვს.

CREATE INDEX idx_name ON large_dataset (name);

-- Query without an index


SELECT * FROM large_dataset WHERE name = 'Name50000';

-- Query with an index

SELECT * FROM large_dataset USE INDEX(idx_name) WHERE name = 'Name50000';

Subquery
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50)
);

INSERT INTO Employees (EmployeeID, FirstName, LastName, Department)


VALUES
(1, 'John', 'Doe', 'IT'),
(2, 'Jane', 'Smith', 'HR'),
(3, 'Michael', 'Johnson', 'Finance'),
(4, 'Emily', 'Williams', 'Marketing'),
(5, 'William', 'Brown', 'IT'),
(6, 'Emma', 'Jones', 'Finance'),
(7, 'Olivia', 'Garcia', 'Marketing'),
(8, 'James', 'Martinez', 'HR'),
(9, 'Sophia', 'Taylor', 'Data Science'),
(10, 'Alexander', 'Clark', 'IT');

Example 1:
SELECT FirstName, LastName, Department
FROM Employees
WHERE Department IN (
SELECT Department
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 2
);

Grouped by
ვთქვათ გვაქვს ეს ცხრილი და გვაინტერესებს რა
იყო ჩვენი შემოსავალი თითოეულ თვეს.
მოცემული გვაქვს იანვრის, თებერვლის და
მარტის მონაცემები. იმისთვის რომ ეს
დავთვალოთ უნდა გამოვიყენოთ:

select sum(amount), order_date

from transactions
group by order_date;

select * from transactions;

select sum(amount), customer_id

from transactions

group by customer_id;

select sum(amount), customer_id

from transactions

group by customer_id

having sum(amount) > 3;

CREATE TABLE Sales (


Product VARCHAR(50),
Category VARCHAR(50),
Amount DECIMAL(10, 2)
);

INSERT INTO Sales (Product, Category, Amount) VALUES ('Product1', 'Category1',


100.00);
INSERT INTO Sales (Product, Category, Amount) VALUES ('Product2', 'Category1',
150.00);
INSERT INTO Sales (Product, Category, Amount) VALUES ('Product3', 'Category2',
200.00);
INSERT INTO Sales (Product, Category, Amount) VALUES ('Product4', 'Category2',
250.00);
INSERT INTO Sales (Product, Category, Amount) VALUES ('Product5', 'Category3',
300.00);
INSERT INTO Sales (Product, Category, Amount) VALUES ('Product5', 'Category3',
800.00);
SELECT Category, SUM(Amount) AS TotalSales
FROM Sales
GROUP BY Category
HAVING SUM(Amount) > 500

rollup
select sum(amount), order_date

from transactions

group by order_date with rollup;


select count(transaction_id) as "# of orders", customer_id

from transactions

group by customer_id with rollup;

stored procedures

Example 1:
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50)
);
INSERT INTO Employees (EmployeeID, FirstName, LastName,
Department)
VALUES
(1, 'John', 'Doe', 'IT'),
(2, 'Jane', 'Smith', 'HR'),
(3, 'Michael', 'Johnson', 'Finance'),
(4, 'Emily', 'Williams', 'Marketing'),
(5, 'William', 'Brown', 'IT'),
(6, 'Emma', 'Jones', 'Finance'),
(7, 'Olivia', 'Garcia', 'Marketing'),
(8, 'James', 'Martinez', 'HR');

CREATE PROCEDURE GetEmployeeByID


@EmployeeID INT
AS
BEGIN
SELECT FirstName, LastName, Department
FROM Employees
WHERE EmployeeID = @EmployeeID;
END;

EXEC GetEmployeeByID @EmployeeID = 7

Here we have something like function, and argument is @EmployeeID.

Example 2:
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY identity(100,1),
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50)
);
INSERT INTO Employees (FirstName, LastName, Department)
VALUES
('John', 'Doe', 'IT'),
('Jane', 'Smith', 'HR'),
('Michael', 'Johnson', 'Finance'),
('Emily', 'Williams', 'Marketing'),
('William', 'Brown', 'IT'),
('Emma', 'Jones', 'Finance'),
('Olivia', 'Garcia', 'Marketing'),
('James', 'Martinez', 'HR');

CREATE PROCEDURE InsertEmployee


@FirstName VARCHAR(50),
@LastName VARCHAR(50),
@Department VARCHAR(50)
AS
BEGIN
-- Insert new employee into the Employees table
INSERT INTO Employees (FirstName, LastName, Department)
VALUES (@FirstName, @LastName, @Department);
END;

EXEC InsertEmployee
@FirstName = 'nick',
@LastName = 'kordzakhia',
@Department = 'data science';

select * from Employees

Example 3:
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50)
);

CREATE PROCEDURE InsertEmployee


@FirstName VARCHAR(50),
@LastName VARCHAR(50),
@Department VARCHAR(50)
AS
BEGIN
DECLARE @EmployeeID INT;

-- Get the maximum existing EmployeeID


DECLARE @MaxEmployeeID INT;
SELECT @MaxEmployeeID = ISNULL(MAX(EmployeeID), 999) FROM
Employees; -- Setting initial value to 999

-- Increment the EmployeeID by 1


SET @EmployeeID = @MaxEmployeeID + 1;

-- Insert new employee into the Employees table


INSERT INTO Employees (EmployeeID, FirstName, LastName,
Department)
VALUES (@EmployeeID, @FirstName, @LastName, @Department);
END;

EXEC InsertEmployee
@FirstName = 'Nick',
@LastName = 'Kordzakhia',
@Department = 'Data Science';

select * from Employees;

triggers
CREATE TABLE employees (

employee_id INT AUTO_INCREMENT PRIMARY KEY,

first_name VARCHAR(50),

last_name VARCHAR(50),

annual_salary DECIMAL(10, 2)

);

INSERT INTO employees (first_name, last_name, annual_salary)


VALUES

('John', 'Doe', 60000.00),

('Jane', 'Smith', 70000.50),

('Michael', 'Johnson', 55000.75),

('Emily', 'Brown', 80000.25),

('David', 'Wilson', 75000.80),

('Sarah', 'Davis', 90000.00),

('William', 'Jones', 62000.50),

('Olivia', 'Martinez', 72000.75),

('James', 'Garcia', 68000.30),

('Sophia', 'Lopez', 85000.40);

alter table employees

add column daily_pay int;

update employees

set daily_pay = annual_salary / 365;

ამის შემდეგ მე მინდა რომ როცა შეიცვლება ერთი სვეტის ერთი უჯრა ავტომატურად
შეიცვალოს შედეგი. ანუ თუ შევცვლი annual_salary-ს უნდა შეიცვალოს daily_pay.

create trigger before_hourly_pay_update

before update on employees

for each row

set new.daily_pay = (new.annual_salary / 365)

update employees

set annual_salary = 200000

where employee_id = 8;

select * from employees;

update employees

set annual_salary = annual_salary * 2;


select * from employees;

insert into employees

values (11, "Nick", "Kordzakhia", 300000, null);

select* from employees;

create trigger before_hourly_pay_insert

before insert on employees

for each row

set new.daily_pay = (new.annual_salary / 365);

insert into employees

values (12, "Nickoloz", "Kordzakhia", 500000, null);

select* from employees;

update expanses

set expense_total = (select sum(daily_pay) from employees)

where expense_name = "salaries";

create trigger after_salary_delete

after delete on employees

for each row

update expanses

set expense_total = expense_total - old.daily_pay

where expense_name= "salaries";

create trigger after_salary_insert

after insert on employees

for each row

update expenses

set expense_total = expense_total + new.daily_pay

where expense_name = "salaries";


create trigger after_salary_update

after update on employees

for each row

update expanses

set expense_total = expense_total + (new.daily_pay - old.daily_pay)

where expense_name = "salaries";

Case
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50),
Salary DECIMAL(10, 2)
);

INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Salary)


VALUES
(1, 'John', 'Doe', 'HR', 50000.00),
(2, 'Jane', 'Smith', 'Marketing', 55000.00),
(3, 'Alice', 'Johnson', 'Finance', 60000.00),
(4, 'Bob', 'Williams', 'IT', 65000.00),
(5, 'Emily', 'Brown', 'Operations', 60000.00),
(6, 'Michael', 'Johnson', 'Sales', 58000.00),
(7, 'Samantha', 'Clark', 'Customer Service', 52000.00),
(8, 'David', 'Martinez', 'Research', 70000.00),
(9, 'Jennifer', 'Lee', 'HR', 48000.00),
(10, 'Andrew', 'Garcia', 'Finance', 55000.00),
(11, 'Jessica', 'Taylor', 'IT', 62000.00),
(12, 'Steven', 'Anderson', 'Sales', 54000.00),
(13, 'Melissa', 'Thomas', 'Operations', 59000.00),
(14, 'Daniel', 'Hernandez', 'Finance', 51000.00),
(15, 'Sophia', 'Lopez', 'Marketing', 63000.00);

SELECT *,
CASE
WHEN Salary >= 60000.00 THEN 'High Salary'
WHEN Salary >= 55000.00 THEN 'Medium Salary'
ELSE 'Low Salary'
END AS SalaryCategory,
CASE
WHEN Department = 'HR' THEN 'Human Resources'
WHEN Department = 'Marketing' THEN 'Marketing Department'
WHEN Department = 'Finance' THEN 'Financial Department'
WHEN Department = 'IT' THEN 'Information Technology'
ELSE 'Other Department'
END AS DepartmentName,
CASE
WHEN FirstName = 'John' THEN 'Senior Employee'
WHEN FirstName = 'Jane' THEN 'Experienced Employee'
ELSE 'New Employee'
END AS EmployeeType
FROM Employees;

SELECT
*,
Salary * 0.1 AS Bonus, -- Assuming bonus is 10% of the salary
CASE
WHEN Salary >= 60000.00 THEN Salary * 0.3 -- 30% tax for high earners
WHEN Salary >= 55000.00 THEN Salary * 0.25 -- 25% tax for medium
earners
ELSE Salary * 0.2 -- 20% tax for low earners
END AS TaxDeduction,
Salary + (Salary * 0.1) -
CASE
WHEN Salary >= 60000.00 THEN Salary * 0.3
WHEN Salary >= 55000.00 THEN Salary * 0.25
ELSE Salary * 0.2
END AS NetSalary
FROM Employees;
Aliansing
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
Gender NVARCHAR(10),
DateOfBirth DATE,
Address NVARCHAR(100),
PhoneNumber NVARCHAR(15),
Email NVARCHAR(100),
JobTitle NVARCHAR(50)
);
CREATE TABLE Salaries (
SalaryID INT PRIMARY KEY,
EmployeeID INT FOREIGN KEY REFERENCES Employees(EmployeeID),
Salary DECIMAL(10, 2),
EffectiveDate DATE
);
-- Inserting data into Employees table
INSERT INTO Employees (EmployeeID, FirstName, LastName, Gender,
DateOfBirth, Address, PhoneNumber, Email, JobTitle)
VALUES
(1, 'John', 'Doe', 'Male', '1990-05-15', '123 Main St, Anytown, USA', '123-
456-7890', '[email protected]', 'Manager'),
(2, 'Jane', 'Smith', 'Female', '1995-08-25', '456 Elm St, Anytown, USA',
'987-654-3210', '[email protected]', 'Software Engineer'),
(3, 'Michael', 'Johnson', 'Male', '1987-12-10', '789 Oak St, Anytown, USA',
'555-123-4567', '[email protected]', 'HR Specialist'),
(4, 'Emily', 'Brown', 'Female', '1992-03-20', '101 Pine St, Anytown, USA',
'111-222-3333', '[email protected]', 'Accountant'),
(5, 'David', 'Wilson', 'Male', '1985-06-30', '202 Cedar St, Anytown, USA',
'444-555-6666', '[email protected]', 'Marketing Specialist'),
(6, 'Jessica', 'Taylor', 'Female', '1993-09-05', '303 Maple St, Anytown,
USA', '777-888-9999', '[email protected]', 'Sales Manager'),
(7, 'Christopher', 'Anderson', 'Male', '1989-11-12', '404 Birch St,
Anytown, USA', '666-777-8888', '[email protected]', 'Data
Analyst'),
(8, 'Amanda', 'Martinez', 'Female', '1991-04-18', '505 Walnut St, Anytown,
USA', '222-333-4444', '[email protected]', 'Customer Service
Representative'),
(9, 'Matthew', 'Hernandez', 'Male', '1986-07-25', '606 Pineapple St,
Anytown, USA', '999-111-2222', '[email protected]', 'Project
Manager'),
(10, 'Samantha', 'Garcia', 'Female', '1994-10-08', '707 Peach St, Anytown,
USA', '888-999-0000', '[email protected]', 'Quality Assurance
Tester');

-- Inserting data into Salaries table


INSERT INTO Salaries (SalaryID, EmployeeID, Salary, EffectiveDate)
VALUES
(1, 1, 75000.00, '2024-01-01'),
(2, 2, 60000.00, '2024-01-01'),
(3, 3, 45000.00, '2024-01-01'),
(4, 4, 55000.00, '2024-01-01'),
(5, 5, 50000.00, '2024-01-01'),
(6, 6, 80000.00, '2024-01-01'),
(7, 7, 70000.00, '2024-01-01'),
(8, 8, 40000.00, '2024-01-01'),
(9, 9, 90000.00, '2024-01-01'),
(10, 10, 45000.00, '2024-01-01');
select FirstName as FName
from [Data Analyst Bootcamp].[dbo].[Employees]

select FirstName + ' ' + LastName as FullName


from [Data Analyst Bootcamp].[dbo].[Employees]

select demo.FirstName + ' ' + demo.LastName as FullName,


sal.Salary
from [Data Analyst Bootcamp].[dbo].[Employees] as demo
join [Data Analyst Bootcamp].[dbo].[Salaries] as sal
on demo.EmployeeID = sal.SalaryId

CREATE TABLE EmployeeHobbies (


EmployeeID INT PRIMARY KEY,
Hobby NVARCHAR(100)
);
-- Inserting data into EmployeeHobbies table
INSERT INTO EmployeeHobbies (EmployeeID, Hobby)
VALUES
(1, 'Playing Chess'),
(2, 'Playing Guitar'),
(3, 'Photography'),
(4, 'Cooking'),
(5, 'Running'),
(6, 'Traveling'),
(7, 'Gardening'),
(8, 'Singing'),
(9, 'Playing Soccer'),
(10, 'Drawing');

select a.FirstName + ' ' + a.LastName as FullName, b.Salary, c.Hobby


from [Data Analyst Bootcamp].[dbo].[Employees] as a
join [Data Analyst Bootcamp].[dbo].[Salaries] as b
on a.EmployeeID = b.SalaryId
join [Data Analyst Bootcamp].[dbo].[EmployeeHobbies] as c
on a.EmployeeID = c.EmployeeID

Partition By
select a.Gender,
Count(Gender)
from Employees as a
join Salaries as b
on a.EmployeeID =
b.EmployeeID
group by Gender

select a.Gender, Count(Gender) over (partition by


gender) as Partition
from Employees as a
join Salaries as b
on a.EmployeeID = b.EmployeeID
 If we had only count there will be error because it is impossible to calculate.
 If we have group by it counts how many unit is in single group.
 If we have partition by it is counted how many unit is in table similar to particular.

CTE
with CTE as
(SELECT
*,
CASE
WHEN Exit_Date IS NOT NULL THEN DATEDIFF(YEAR, Hire_Date, Exit_Date)
ELSE DATEDIFF(YEAR, Hire_Date, GETDATE())
END AS SPAN
--CASE
-- WHEN SPAN BETWEEN 0 AND (MAX(SPAN) - MIN(SPAN)) / 3 THEN 'NEW'
-- WHEN SPAN Between (MAX(SPAN) - MIN(SPAN))/3 and (MAX(SPAN) -
MIN(SPAN))/3*2 then 'EXPERIENCED'
-- WHEN SPAN between (MAX(SPAN) - MIN(SPAN))/3*2 and max(SPAN) THEN
'VETERAN'
-- end as status
FROM
[Case Study].[dbo].[Employee Sample Data])

select *,
CASE
WHEN SPAN BETWEEN 0 AND (select(MAX(SPAN) - MIN(SPAN))from CTE) /
3 THEN 'NEW'
WHEN SPAN Between (select(MAX(SPAN) - MIN(SPAN))from CTE)/3 and
(select(MAX(SPAN) - MIN(SPAN))from CTE)/3*2 then 'EXPERIENCED'
WHEN SPAN between (select(MAX(SPAN) - MIN(SPAN))from CTE)/3*2 and
(SELECT max(SPAN) from CTE) THEN 'VETERAN'
end as status
from CTE

 Here what we are selecting is imaginary and when we create imaginary columns we can not
use them. What is in comment is usage of imaginary column “SPAN”, so it is mistake.
 With statement gives us opportunity to use imaginary columns and what is created under
“with” is not saved in disk but is method of using imaginary columns.

TempTable
drop table if exists ##Emp_Sal
create table ##Emp_Sal (
Full_Name varchar(50),
Annual_Salary varchar(50)
)
insert into ##Emp_Sal
select Full_Name, Annual_Salary from [Employee Sample Data]

select * from ##Emp_Sal

select * from ##Emp_Sal

 Global temp table is with ## and local with #.


 Global temp table’s usage is possible in every query page. Local is
accessible only one page where it is created.
 When access with database is stopped, all temp tables are dropped.
 Temp table is saved in Tempdb database.
 Thus we can create table and use as we need which we need small
session period.
 If we delete query page where this temp table is created it is dropped
automatically.
CREATE TABLE #Temp_Table (
Full_Name VARCHAR(50),
Span INT
);

INSERT INTO #Temp_Table


SELECT
Full_Name,
CASE
WHEN Exit_Date IS NOT NULL THEN
DATEDIFF(YEAR, Hire_Date, Exit_Date)
ELSE DATEDIFF(YEAR, Hire_Date, GETDATE())
END AS Span
FROM
[Case Study].[dbo].[Employee Sample Data];

select * from #Temp_Table


select *,
case
when Span <= 5 then 'Low experience'
when Span > 5 and Span < 20 then
'Experienced'
eLSE 'EXPERT'
END as 'status'
from #Temp_Table
String Functions

LEN(string): Returns the number of characters in a


string.
Example:
SELECT LEN('Hello'); -- Returns 5

LEFT(string, length): Returns the leftmost characters


from a string up to the specified length.
Example:
SELECT LEFT('Hello World', 5); -- Returns 'Hello'

RIGHT(string, length): Returns the rightmost characters


from a string up to the specified length.
Example:
SELECT RIGHT('Hello World', 5); -- Returns 'World'

SUBSTRING(string, start, length): Returns a substring


from a string starting at the specified start position
and optionally for a specified length.
Example:
SELECT SUBSTRING('Hello World', 7, 5); -- Returns 'World'

UPPER(string): Converts a string to uppercase.


Example:
SELECT UPPER('hello'); -- Returns 'HELLO'

LOWER(string): Converts a string to lowercase.


Example:
SELECT LOWER('Hello'); -- Returns 'hello'

REPLACE(string, old, new): Replaces all occurrences of a


substring within a string with another substring.
Example:
SELECT REPLACE('Hello World', 'World', 'Universe'); --
Returns 'Hello Universe'

LTRIM(string): Removes leading spaces from a string.


Example:
SELECT LTRIM(' Hello'); -- Returns 'Hello'
RTRIM(string): Removes trailing spaces from a string.
Example:
SELECT RTRIM('Hello '); -- Returns 'Hello'

TRIM(string): Removes leading and trailing spaces from a


string.
Example:
SELECT TRIM(' Hello '); -- Returns 'Hello'

CHARINDEX(substring, string[, start]): Returns the


starting position of the first occurrence of a substring
within a string, optionally starting the search from a
specified position.
Example:
SELECT CHARINDEX('l', 'Hello'); -- Returns 3

REVERSE(string): Reverses the characters in a string.


Example:
SELECT REVERSE('Hello'); -- Returns 'olleH'

STUFF(string, start, length, replacement): Deletes a


specified length of characters from a string at a
specified starting position and then inserts another
string into the original string at the same position.
Example:
SELECT STUFF('Hello World', 7, 5, 'Universe'); -- Returns
'Hello Universe'

CONCAT(string1, string2, ...): Concatenates two or more


strings together.
Example:
SELECT CONCAT('Hello', ' ', 'World'); -- Returns 'Hello
World'

FORMAT(string, format): Formats the value of string using


the specified format.
Example:
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd'); -- Returns '2022-
01-01'

REPLICATE(string, count): Repeats a string a specified


number of times.
Example:
SELECT REPLICATE('Hello', 3); -- Returns
'HelloHelloHello'

You might also like