KEMBAR78
SQL Query All SQL Constraints Table Constraint Name SQL Keyword Description Not Null | PDF | Database Index | Relational Database
0% found this document useful (0 votes)
9 views33 pages

SQL Query All SQL Constraints Table Constraint Name SQL Keyword Description Not Null

The document provides a comprehensive overview of SQL constraints, including definitions and examples of various constraints like NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT, and INDEX. It also includes SQL queries for creating databases and tables, inserting data, and performing operations such as joins, aggregations, and using different SQL operators. Additionally, it covers advanced topics like cascading updates and deletes, altering tables, and the differences between DELETE and TRUNCATE commands.

Uploaded by

Raushan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views33 pages

SQL Query All SQL Constraints Table Constraint Name SQL Keyword Description Not Null

The document provides a comprehensive overview of SQL constraints, including definitions and examples of various constraints like NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT, and INDEX. It also includes SQL queries for creating databases and tables, inserting data, and performing operations such as joins, aggregations, and using different SQL operators. Additionally, it covers advanced topics like cascading updates and deletes, altering tables, and the differences between DELETE and TRUNCATE commands.

Uploaded by

Raushan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

SQL Query

All SQL Constraints Table

Constraint Name SQL Keyword Description

Ensures the column cannot


NOT NULL NOT NULL
store NULL values.

Ensures all values in a column


UNIQUE UNIQUE (or a combination of columns)
are distinct.

Uniquely identifies each row.


PRIMARY KEY PRIMARY KEY Combines NOT NULL and
UNIQUE. Only one per table.

Enforces a link between


FOREIGN KEY FOREIGN KEY columns in two tables (parent-
child relationship).

Validates data against a


CHECK CHECK
specific condition.

Sets a default value if no value


DEFAULT DEFAULT
is provided during insertion.

Improves data retrieval speed.


INDEX CREATE INDEX Not a constraint, but related to
performance.

AUTO_INCREMENT
Automatically increments the
AUTO INCREMENT (MySQL) / SERIAL
value for each new row.
(PostgreSQL)

UNIQUE Constraint on Ensures the combination of


UNIQUE(col1, col2)
Multiple Columns multiple columns is unique.

Uses multiple columns as a


Composite Primary Key PRIMARY KEY(col1, col2)
single unique identifier.

Limits the column value to a


ENUM ENUM('val1', 'val2',...) specified list of allowed values
(MySQL-specific).

Allows multiple values from a


SET SET('a','b',...)
list (MySQL-specific).
Constraint Name SQL Keyword Description

Automatically deletes child


rows when parent row is
ON DELETE CASCADE ON DELETE CASCADE
deleted (used with FOREIGN
KEY).

Automatically updates child


rows when parent key is
ON UPDATE CASCADE ON UPDATE CASCADE
updated (used with FOREIGN
KEY).

NOT DEFERRABLE / Controls when constraint


DEFERRABLE (PostgreSQL) checking occurs (immediate or
INITIALLY DEFERRED end of transaction).

Ensures that data inserted


WITH CHECK OPTION
WITH CHECK OPTION through a view satisfies the
(Views)
view’s WHERE clause.

Sample Table Using Most Constraints


CREATE TABLE employees (
emp_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE,
age INT CHECK (age >= 18),
gender ENUM('Male', 'Female', 'Other') DEFAULT 'Other',
dept_id INT,
hire_date DATE DEFAULT CURRENT_DATE,
FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
Queries
-- creating database
create database DatabsePractice;
-- deleting data base
drop database DatabsePractice;
-- using database
use DatabsePractice;
-- creating tables

CREATE TABLE user (


user_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(40) NOT NULL,
email VARCHAR(50) UNIQUE,
password VARCHAR(80) NOT NULL,
age INT DEFAULT 20 CHECK(age >= 18),
gender ENUM('male', 'female', 'others') DEFAULT 'others',
CreatedDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UpdatedDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
);

-- inserting values into tables


INSERT INTO user (name,email,password,age,gender)
VALUES('Raushan','raushankumar23082004@gmail.com','raus@1234',21,'male');
-- showing table
SELECT * FROM USER;

-- practice question
CREATE DATABASE XYZ;
USE XYZ;
CREATE TABLE Employee(
id INT primary key,
name varchar(40),
salary INT
);
-- drop table
drop table Employee;
INSERT INTO Employee(id,name,salary)
values
(1,'adam',2500),
(2,'bob',30000),
(3,'casey',30000);

CREATE TABLE Workers(


id INT,
name varchar(40),
salary INT,
foreign key (id) references Employee(id)
);

INSERT INTO Workers(id,name,salary)


values
(1,'ram',2500),
(2,'sita',30000),
(3,'gita',36000);

drop table Workers;

SELECT * FROM Employee;


SELECT * FROM Workers;
-- joins to access info of another table useing one table when
-- applied primary and foreign key concept
SELECT
Employee.id,
Employee.name AS employee_name,
Employee.salary AS employee_salary,
Workers.name AS worker_name,
Workers.salary AS worker_salary
FROM
Employee
JOIN
Workers
ON
Employee.id = Workers.id;
-- Create the database
CREATE DATABASE college;

-- Use the college database


USE college;

-- Create the student table


CREATE TABLE student (
rollno INT PRIMARY KEY,
name VARCHAR(50),
marks INT NOT NULL,
grade VARCHAR(1),
city VARCHAR(20)
);
INSERT INTO student (rollno, name, marks, grade, city)
VALUES
(101, 'Anil', 78, 'C', 'Pune'),
(102, 'Bhumika', 93, 'A', 'Mumbai'),
(103, 'Chetan', 85, 'B', 'Mumbai'),
(104, 'Dhruv', 96, 'A', 'Delhi'),
(105, 'Farah', 82, 'B', 'Delhi'),
(106, 'Avi', 12, 'D', 'Delhi');
-- select name,marks from student;
-- select city from student;// to see city of students
-- but if u want to see unique city then use distinct key word
select distinct city from student;

-- non lets learn where clause


select * from student where marks >80;
select * from student where city="Delhi";
select * from student where marks >80 && city="Mumbai";
-- here in where clauses we learn operators

1. Operators in SQL WHERE Clause – Summary Table

Category Operator Meaning / Use

Arithmetic + Addition

- Subtraction

* Multiplication

/ Division

% Modulus (remainder)

Comparison = Equal to

!= or <> Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

Logical AND True if both conditions are true

OR True if at least one condition is true

NOT Reverses the condition


Category Operator Meaning / Use

Bitwise & Bitwise AND

` `

^ Bitwise XOR

~ Bitwise NOT (MySQL does support it, others may vary)

<< Left shift

>> Right shift

2. Example Table: student


Assume this table exists:
CREATE TABLE student (
rollno INT PRIMARY KEY,
name VARCHAR(50),
marks INT NOT NULL,
grade VARCHAR(1),
city VARCHAR(20)
);

3. SQL Queries Using Each Type of Operator

A. Arithmetic Operators
-- Find students whose marks + 10 is greater than 90
SELECT * FROM student
WHERE marks + 10 > 90;
-- Find students whose marks * 2 is less than 160
SELECT * FROM student
WHERE marks * 2 < 160;

B. Comparison Operators
-- Students who scored exactly 85
SELECT * FROM student
WHERE marks = 85;
-- Students who scored more than 90
SELECT * FROM student
WHERE marks > 90;
-- Students who scored less than or equal to 80
SELECT * FROM student
WHERE marks <= 80;
-- Students who did not score 93
SELECT * FROM student
WHERE marks != 93;

C. Logical Operators
-- Students who are from Delhi AND scored more than 80
SELECT * FROM student
WHERE city = 'Delhi' AND marks > 80;
-- Students from Delhi OR Mumbai
SELECT * FROM student
WHERE city = 'Delhi' OR city = 'Mumbai';

-- Students NOT from Delhi


SELECT * FROM student
WHERE NOT city = 'Delhi';

D. Bitwise Operators
Bitwise operators usually work on integers.
-- Students whose rollno has 2nd bit set (bitwise AND with 2)
SELECT * FROM student
WHERE rollno & 2;

-- Students where rollno | 1 = 101 (bitwise OR)


SELECT * FROM student
WHERE (rollno | 1) = 101;
-- Students whose rollno XOR 1 = 102
SELECT * FROM student
WHERE (rollno ^ 1) = 102;

Note: Bitwise operators are less commonly used in everyday SQL queries. They are used
more in low-level data filtering or flags.
-- Between operator
select * from student where marks between 59 and 90;
-- IN operator
select * from student where city in ('Delhi','Mumbai');
-- NOT IN operator
-- Students NOT from Delhi
SELECT * FROM student
WHERE city NOT IN ('Delhi','Mumbai');

-- limit clause =>set an upper limit on a number of tuple


select * from student limit 4;
select rollno,name from student limit 4;

-- Order by clause
select * from student order by city ASC;
select * from student order by marks DESC;
-- Aggregate functions
summary value. They are commonly used with the GROUP BY clause to group rows based
on one or more columns.

Common Aggregate Functions in SQL:

Function Description

COUNT() Returns the number of rows

SUM() Returns the total sum of a numeric column

AVG() Returns the average value of a numeric column

MIN() Returns the smallest value


Function Description

MAX() Returns the largest value

Syntax Example
SELECT COUNT(*) FROM employees;
SELECT AVG(salary) FROM employees;
SELECT MAX(salary) FROM employees;
SELECT MIN(salary) FROM employees;
SELECT SUM(salary) FROM employees;

With GROUP BY Example


SELECT department, AVG(salary)
FROM employees
GROUP BY department;
This groups employees by their department and returns the average salary per department.
The GROUP BY: clause in SQL is used to group rows that have the same values in specified
columns into summary rows, like totals or averages. It's commonly used with aggregate
functions such as COUNT(), SUM(), AVG(), MAX(), and MIN().
Example:
Table: sales

id product quantity price

1 Apple 10 5

2 Banana 20 2

3 Apple 15 5

4 Banana 10 2

5 Mango 8 3

Query:
SELECT product, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product;
Result:
product total_quantity

Apple 25

Banana 30

Mango 8

-- Group by clause
use college;
select * from student;
select name,sum(marks) as Total_Marks
from student
group by name;
-- total no fo students from a city
select city,count(name) as Total_Count
from student
group by city;
-- student name greater than marks 80 from a city
select city,marks,name,
count(name) as Total_Count
from student
where marks>=80
group by city,marks,name;
-- question Write the Query to find avg marks in each city in ascending order.
select city,
avg(marks) as Average_Marks
from student
group by city
order by Average_Marks ASC

-- creating one more table called customer for question practice


create database customer;
use customer;
DROP TABLE IF EXISTS customer;
create table customers (
customer_id int primary key,
customer_name varchar(60),
mode varchar(60),
city varchar(60)
);

INSERT INTO customers (customer_id,customer_name,mode,city)


values
(101, 'Olivia Barrett', 'Netbanking', 'Portland'),
(102, 'Ethan Sinclair', 'Credit Card', 'Miami'),
(103, 'Maya Hernandez', 'Credit Card', 'Seattle'),
(104, 'Liam Donovan', 'Netbanking', 'Denver'),
(105, 'Sophia Nguyen', 'Credit Card', 'New Orleans'),
(106, 'Caleb Foster', 'Debit Card', 'Minneapolis'),
(107, 'Ava Patel', 'Debit Card', 'Phoenix'),
(108, 'Lucas Carter', 'Netbanking', 'Boston'),
(109, 'Isabella Martinez', 'Netbanking', 'Nashville'),
(110, 'Jackson Brooks', 'Credit Card', 'Boston');
select * from customers;

-- For the given table, find the total payment according to each payment method.
select mode, count(mode) as paymentMethodUsed
from customers
group by mode
order by paymentMethodUsed asc;
-- student table se grade ko group kro ki kirne students ko konsa grade mila
use college;
select grade,count(name) as no_of_stu
from student
group by grade
order by no_of_stu;
-- having clause
-- having clause is similar to where clause, where where clause is userd on row
-- whereas having clause is work on groups if we have to apply condition on groups then w'll
use having
use college;
select city,count(name)
from student
group by city
having max(marks>90);
-- you can see there we have applied having clause on groups
-- here is the general order of clause
-- SELECT choose what columns/expressions to return
-- FROM — identify the table(s) and join them if needed
-- WHERE — filter rows before grouping
-- GROUP BY — group filtered rows
-- HAVING — filter groups (like WHERE but for groups)
-- ORDER BY — sort the result
-- LIMIT — restrict number of final rows

-- now update table


SET SQL_SAFE_UPDATES = 0;
UPDATE student
SET grade = 'O'
WHERE grade = 'A';
select * from student;
#deleting a row
INSERT INTO student (rollno, name, marks, grade, city)
VALUES
(111, 'vinod', 12, 'F', 'UP');
delete from student where marks=12;
#more aboout foreignkey
# creating a department table and a crossponding teacher table that defines
# which techer is asociated with which department
use college;
create table if not exists dept (
dept_id int PRIMARY key,
dept_name VARCHAR(50)
);
insert into dept(dept_id,dept_name)
values
(101,'IT'),
(102,'CSE'),
(103,'ECE'),
(104,'CE');
select * from dept;
create table if not exists teacher(
id int primary key,
name VARCHAR(50),
dept_id int,
FOREIGN KEY (dept_id) references dept(dept_id)
);
insert into teacher (id,name,dept_id)
values
(111,'Raushan','101'),
(112,'vikash','102'),
(113,'sushil','101'),
(114,'vaibhav','102');
select * from teacher;
# note dept table ka dept_id column jo ek primary key hai of dept table and
# in teacher table this dept_id column is associated as foreignkey then the
# dept table is called parent table and teache table is called children table

# now learn about cascading for foreignkey what is it


# dekho jaise tumne dept table ka dept_id ko as foreignkey banaye ho teacher table me
# to kal ko agar koi deptment delete ho jaye ya update ho jaye jaise maan lo ki kal ko
# CSE deptment ka id change ho jati hai to teacher table me bhi dept_id change honi chahiye
# ya cse dept hi delete ho jaye to asociated row delete honi
# chahiye isske liye cascading use kiya jata hai foreign key ke sath

# on delete cascade;
# on update cascade;
drop table if exists teacher;
create table if not exists teacher(
id int primary key,
name VARCHAR(50),
dept_id int,
FOREIGN KEY (dept_id) references dept(dept_id)
on delete cascade
on update cascade
);
select * from dept;
select * from teacher;

update dept
set dept_id=105
where dept_id=102;
insert into teacher (id,name,dept_id)
values
(115,'sukla','103');
delete from dept
where dept_id=103;

#now ALTER
#alter is used to add,remove,update,rename column also rename the table name ;
#add a column
alter table student
add column age int not null default 20;
select * from student;
#drop a column
alter table student
drop column age;
#rename table
use college;
alter table student
rename to students;

select * from students;

alter table students


rename to student;

#rename colums name


ALTER TABLE student
RENAME COLUMN salary_ TO age_stu;
#rename a column name or datatypes or constraints
alter table student
change salary salary_ int default 40000;

ALTER TABLE student


CHANGE age grade VARCHAR(40) DEFAULT 'A';

#modify a column datatypes or constraints


alter table student
modify column age_stu varchar(4);
select * from student;
#now truncate it is used to delete all rows from a table in which all rows are deleted but table
still exists
where as drop deletes entire table we can also delete entire row using delete command delete
from student ;
then what is diff b/w delete and truncate here is the diff

DELETE FROM student;


 Ye har row ko ek-ek karke delete karta hai.
 Har row ke deletion ka log banata hai (transaction log).
 Triggers fire hote hain agar defined hain.
 Slow hota hai jab table me bahut saare records ho.
 ROLLBACK possible hota hai agar transaction ke andar ho.

TRUNCATE TABLE student;


 Ye poore table ke data pages ko deallocate kar deta hai.
 Ye row-by-row delete nahi karta — fast hota hai.
 No WHERE clause allowed.
 Triggers fire nahi hote.
 Identity column reset ho jata hai (if exists).
 Less transaction log used ⇒ zyada efficient on large tables.
 Mostly cannot ROLLBACK unless inside a transaction without COMMIT.
truncate table student;
# Joins: joins are used to combine rows from two or more tables based on related
column b/w them.

# Joins joins are userd to combine rows from two or more tables based on related column
b/w them

# creating new database called JoinDemon


create database JoinDemon;

use JoinDemon;

create table student(


student_id int primary key,
name varchar(50));

insert into student(student_id,name)


values
(101,"adam"),
(102,"bob"),
(103,"casey");

create table course(


student_id int primary key,
course varchar(50)
);

insert into course(student_id,course)


values
(102,"english"),
(105,"math"),
(103,"science"),
(107,"computer science");

select * from student;


select * from course;

# Applying inner join


#alias =>alternate name here s is the alias of student and c is the alias of course
# means in future we can use student as s and course as c

select * from student as s


inner join course as c
on s.student_id=c.student_id;

# Applying outer join-->left outer join


select * from student
left join course
on student.student_id=course.student_id;

# Applying outer join-->right outer join


select * from student
right join course
on student.student_id=course.student_id;
# Applying outer join-->full outer join sql me full join exist nahi karta postgray me karta hai
to ham left union right use kar skte hai iske liye
select * from student
full join course
on student.student_id=course.student_id;
# one more way to do full join in sql
SELECT * FROM student as s
LEFT JOIN course as c
ON s.student_id = c.student_id
UNION
SELECT * FROM student as s
RIGHT JOIN course as c
ON s.student_id = c.student_id;
now apart from these join there are some extra joins
1.Left Exclusive join
2.Right Exlcusive join
1.Left Exclusive join- matlab kewal left table ka values jo nahi b table me na ho nahi b table
ke sath common ho.
implemented using applying first pure left join + additional
2.Right Exlcusive join -matlab keal rihgt table ka values jo left table me na ho nahi a table ke
sath commom ho
implemented using applying first pure right join + additional

# Applying Left Exclusive join


select * from student as s
left join course as c
on s.student_id=c.student_id
where c.student_id is null;

# Applying right Exclusive join


select * from student as s
right join course as c
on s.student_id=c.student_id
where s.student_id is null;

What is a SELF JOIN?


A SELF JOIN is a regular join where a table is joined with itself. It is useful when you want
to compare rows within the same table.

Use Case:
A common use case is hierarchical relationships, like:
 Employees and their managers (from your employee table),
 Categories and subcategories,
 Friends-of-friends in social networks.
Example Table (employee):

id name manager_id

101 adam 103

102 bob 104

103 casey NULL

104 donald 103

Goal:
Show each employee and their manager's name.

SQL with SELF JOIN:


SELECT
e1.name AS Employee,
e2.name AS Manager
FROM
employee e1
LEFT JOIN
employee e2
ON
e1.manager_id = e2.id;

Output:

Employee Manager

adam casey

bob donald

casey NULL

donald casey

select b.name , a.name as Manager_name


from employee as a
join employee as b
where a.id=b.manager_id;
#union
# UNION removes duplicate names by default. Use UNION ALL if you want to include
duplicates.
# Make sure both employee and student tables have a name column with a compatible data
type.
select name from employee
union
select name from student;
select name from employee
union all
select name from student;

#sql subquery
#subquery select , from , where per lagti hai
# 1.subquery on where
use college;
select * from student;
#Question:aise students ke naam batao jinka marks pure student ke avg marks se jada ho
select name,marks
from student
where marks>(select avg(marks)from student);

#Question:aise students ke naam batao jinka roll no even hai


select name,rollno
from student
where rollno in (select rollno from student where rollno%2=0);

# 1.subquery on from
#Question:maximum marks print kro uss student ka jo delhi se ho
select max(marks) from
(select * from student where city="Delhi") as temp;

# 1.subquery on select
#Question:select max marks and thier name
select (select max(marks) from student),name from student;

#views
# A View in SQL is a virtual table based on the result of a SQL
# query. It does not store data itself but displays data from one or more tables.

create view view1 as


select rollno,name,marks from student;

select * from view1;


drop view view1;
What is a Trigger?
A trigger is a piece of SQL code that is automatically executed before or after an insert,
update, or delete operation on a table.

Basic Syntax of a Trigger (MySQL)


CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
-- trigger logic here
END;

create database triggerDb;


use triggerDb;
#to show triggers write
SHOW TRIGGERS;

CREATE TABLE employee (


id INT PRIMARY KEY,
name VARCHAR(100),
salary DECIMAL(10,2)
);

CREATE TABLE employee_log (


log_id INT AUTO_INCREMENT PRIMARY KEY,
emp_id INT,
action VARCHAR(50),
log_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
#creating triggers
DELIMITER //
create trigger after_employee_insert
after insert
on employee
for each row
begin
insert into employee_log(emp_id,action)
values
(new.id,"Insert");
end;
//

DELIMITER ;
select * from employee;
select * from employee_log;

INSERT INTO employee (id, name, salary)


VALUES (1, 'Raushan', 50000.00);
SQL Injection is a type of security vulnerability that allows an attacker to interfere with the
queries that an application makes to its database. It usually occurs when user input is
improperly sanitized and directly included in SQL statements.

Example of SQL Injection:


Let’s say you have the following SQL query in a login system:
SELECT * FROM users WHERE username = 'admin' AND password = '1234';
If the user enters the following malicious input for the username field:
' OR '1'='1
The resulting SQL becomes:
SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '...';
This always evaluates to true, potentially allowing an attacker to bypass login authentication.
Common SQL Injection Techniques
1. Authentication Bypass:
' OR 1=1 --
2. Union-Based Injection:
' UNION SELECT username, password FROM admin_table --
3. Error-Based Injection:
Trigger errors to reveal database info:
' AND 1=CONVERT(int, (SELECT @@version)) --
4. Blind SQL Injection:
Observe application behavior changes (like response times or error messages) when
altering the query:
' AND SUBSTRING(@@version, 1, 1) = '5' --

How to Prevent SQL Injection


1. Use Prepared Statements (Parameterized Queries)
For example in Node.js (using MySQL):
const sql = "SELECT * FROM users WHERE username = ? AND password = ?";
connection.query(sql, [username, password], (err, results) => {
// secure
});
2. Use ORM Frameworks
Tools like Sequelize, Prisma, or Mongoose in Node.js help abstract SQL and reduce
direct query risks.
3. Input Validation
Validate and sanitize user input (e.g., allow only alphanumeric characters where
needed).
4. Least Privilege Principle
Don’t use a DB user with root/admin access in your application.
5. Stored Procedures
Use them securely, but don’t concatenate strings inside them.

SQL Privileges (Permissions)


SQL privileges define what actions a user can perform on database objects like tables, views,
procedures, etc. They are part of access control in a database to ensure security and proper
usage.

Types of SQL Privileges


Data Manipulation Privileges (affect rows/data)
 SELECT: Read data from a table/view.
 INSERT: Add new rows.
 UPDATE: Modify existing data.
 DELETE: Remove rows.

Data Definition Privileges (affect schema structure)


 CREATE: Create new tables, views, or databases.
 ALTER: Change structure (e.g., add a column).
 DROP: Delete a table or database.
 INDEX: Create or remove indexes.

Administrative Privileges
 GRANT: Give privileges to other users.
 REVOKE: Remove privileges from users.
 ALL PRIVILEGES: Grant all permissions.

Examples
1. Granting Privileges
GRANT SELECT, INSERT ON database_name.table_name TO 'username'@'localhost';
Grants the user permission to read and insert data into a specific table.
2. Revoking Privileges
REVOKE INSERT ON database_name.table_name FROM 'username'@'localhost';
Removes only the INSERT permission.

3. Granting All Privileges (Be careful )


GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost';

Viewing Privileges
To see the privileges of a user:
SHOW GRANTS FOR 'username'@'localhost';

#index prcatical
create database indexEx;
use indexEx;
CREATE TABLE Servent (
id INT,
name VARCHAR(50),
age INT,
salary DECIMAL(10, 2)
);
INSERT INTO Servent (id, name, age, salary) VALUES
(1, 'Alice', 25, 45000.00),
(2, 'Bob', 30, 52000.00),
(3, 'Charlie', 28, 49000.00),
(4, 'David', 35, 60000.00),
(5, 'Eve', 26, 47000.00),
(6, 'Frank', 32, 55000.00),
(7, 'Grace', 29, 51000.00),
(8, 'Hank', 33, 58000.00),
(9, 'Ivy', 27, 46000.00),
(10, 'Jack', 31, 53000.00),
(11, 'Kathy', 24, 44000.00),
(12, 'Leo', 36, 62000.00),
(13, 'Mona', 28, 49500.00),
(14, 'Nate', 30, 52000.00),
(15, 'Olivia', 25, 45000.00),
(16, 'Paul', 34, 57000.00),
(17, 'Queen', 26, 46500.00),
(18, 'Rob', 33, 58000.00),
(19, 'Sara', 27, 48000.00),
(20, 'Tom', 29, 51000.00),
(21, 'Uma', 30, 52000.00),
(22, 'Victor', 28, 49500.00),
(23, 'Wendy', 32, 54000.00),
(24, 'Xander', 31, 53000.00),
(25, 'Yara', 27, 46000.00),
(26, 'Zack', 34, 57500.00),
(27, 'Aman', 26, 47000.00),
(28, 'Bhavna', 33, 56000.00),
(29, 'Chirag', 30, 52500.00),
(30, 'Divya', 28, 49500.00),
(31, 'Eshan', 27, 47500.00),
(32, 'Farah', 29, 50500.00),
(33, 'Gautam', 31, 53500.00),
(34, 'Heena', 25, 45000.00),
(35, 'Irfan', 30, 52000.00),
(36, 'Jaya', 26, 46000.00),
(37, 'Kunal', 34, 58000.00),
(38, 'Lata', 33, 56000.00),
(39, 'Manav', 28, 49500.00),
(40, 'Neha', 29, 51000.00),
(41, 'Om', 35, 61000.00),
(42, 'Pooja', 26, 47000.00),
(43, 'Qadir', 32, 54000.00),
(44, 'Rani', 27, 48000.00),
(45, 'Sunil', 31, 53000.00),
(46, 'Tina', 30, 52000.00),
(47, 'Umesh', 28, 49500.00),
(48, 'Vani', 29, 51000.00),
(49, 'Wasim', 33, 56000.00),
(50, 'Xena', 25, 45000.00),
(51, 'Yogesh', 34, 58000.00),
(52, 'Zeenat', 27, 46500.00),
(53, 'Abhay', 28, 49000.00),
(54, 'Bharti', 30, 52000.00),
(55, 'Chetan', 26, 47000.00),
(56, 'Deepa', 32, 55000.00),
(57, 'Emraan', 31, 53000.00),
(58, 'Fatima', 29, 50500.00),
(59, 'Ganesh', 35, 61000.00),
(60, 'Harsha', 28, 49500.00),
(61, 'Inder', 27, 47500.00),
(62, 'Jasmin', 25, 45000.00),
(63, 'Karan', 30, 52000.00),
(64, 'Lavanya', 26, 46500.00),
(65, 'Mihir', 33, 58000.00),
(66, 'Nisha', 28, 49500.00),
(67, 'Omkar', 31, 53000.00),
(68, 'Preeti', 29, 50500.00),
(69, 'Quincy', 32, 54000.00),
(70, 'Ravi', 34, 57000.00),
(71, 'Simran', 27, 46000.00),
(72, 'Tariq', 30, 52000.00),
(73, 'Urvashi', 25, 45000.00),
(74, 'Varun', 33, 56000.00),
(75, 'Wali', 29, 51000.00),
(76, 'Xavier', 30, 52500.42),
(77, 'Yamini', 28, 49500.00),
(78, 'Zaid', 27, 46500.00),
(79, 'Alok', 34, 58000.00),
(80, 'Bina', 26, 47000.00),
(81, 'Chandan', 32, 54000.00),
(82, 'Deepak', 35, 61000.00),
(83, 'Esha', 28, 49000.00),
(84, 'Faizan', 30, 52000.00),
(85, 'Gargi', 25, 45000.00),
(86, 'Hemant', 27, 47000.00),
(87, 'Indira', 33, 56000.00),
(88, 'Jatin', 31, 53000.00),
(89, 'Kavita', 29, 50500.00),
(90, 'Lokesh', 30, 52000.00),
(91, 'Mira', 26, 46500.00),
(92, 'Nakul', 28, 49500.00),
(93, 'Ojas', 27, 47500.00),
(94, 'Pankaj', 34, 58000.00),
(95, 'Rhea', 25, 45000.00),
(96, 'Shyam', 33, 56000.00),
(97, 'Tanu', 29, 51034.23),
(98, 'Uday', 31, 53000.00),
(99, 'Vidya', 30, 52000.00),
(100, 'Yusuf', 28, 49500.00);
drop table Servent;
select * from Servent;

CREATE INDEX emp_idxx ON employee(salary);


select * from employee where salary=30000;
SHOW INDEXES FROM employee;

DROP INDEX emp_idxx ON employee;


https://chatgpt.com/c/68760a83-cfa0-8005-955b-490b057a74c2
https://chatgpt.com/c/68761126-6ed8-8005-98e5-e7234de4a0bd

You might also like