0% found this document useful (0 votes)
4 views

SQL Queries

SQL queries

Uploaded by

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

SQL Queries

SQL queries

Uploaded by

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

Index:

1. Create and delete database and tables in DBMS


2. Insert values in a database table and select a table command in SQL.
3. Alter and update command in SQL
4. Update command in SQL
5. Where clause in SQL
6. Delete, drop and truncate in SQL
7. Not null constraint in SQL
8. Unique constraint in SQL
9. Primary key in SQL
10. Foreign key in SQL
CREATE AND DELETE DATABASE AND TABLES IN DBMS
Create database:

Syntax:
Create database database-name;

Example:
Create database school1;

Open or use a database

Syntax:
Use database-name;

Example:
Use school1;

Delete database:

Syntax:
DROP DATABASE database-name;

Example:
DROP DATABASE school1;

Create table:

Syntax:
CREATE TABLE table_name (column1 datatype (range), column2 datatype (range),
column3 datatype (range), .... column “n” datatype(range));

Example:
Create table student1 (Sid int (5), sname varchar (25));

Delete table:

Syntax:
DROP TABLE table_name;

Example:
Drop table Student1;
INSERT VALUES IN A DATABASE TABLE AND
SELECT A TABLE COMMAND IN SQL
Insert into table:

In selected columns only:

Syntax:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2,
value3, ...);

Example:
INSERT INTO Student1 (Sid, Sname) VALUES (02, ‘Vikas’);

In all columns
If we wanted to add values in all the columns of the table, then no need to mention any
column name, just pass the values.

Syntax:
INSERT INTO table_name VALUES (value1, value2, value3, ...);

Example:
INSERT INTO Student1 VALUES (02, ‘Vikas’);

Please note that in the above statement the order of the values should be followed as per the
column structure.

Select a table:

Selected columns only:

Syntax:
SELECT column1, column2, ... FROM table_name;

Example:
Select Sid, Sname from student1;

Select all columns

Syntax:
Select*from table-name;

Example:
Select*from student1;
Selects distinct values only:
Avoid repeated values

Syntax:
Select distinct column_name from table_name;

Example:
Select distinct Sid from student1;
ALTER AND UPDATE COMMAND IN SQL
To add new column
Syntax:
ALTER TABLE table_name ADD column_name datatype(data range);

Example:
ALTER TABLE student1 ADD city varchar(15);

To drop an existing column


Syntax:
ALTER TABLE table_name DROP COLUMN column_name(data range);

Example:
ALTER TABLE student1 Drop column city;

To Modify an existing column


Syntax:
ALTER TABLE table_name MODIFY column_name datatype(data range);

Example:
ALTER TABLE student1 Modify city char(20);

To change the position of an existing column


Syntax:
ALTER TABLE table_name MODIFY column_name datatype(data range) new position;

Example:
ALTER TABLE student1 Modify city char(20) after name;

To change column name


Syntax:
ALTER TABLE table_name change existing_column_name new_column_name
datatype(data range);

Example:
ALTER TABLE student1 change city Town varchar(15);

To rename a table
Syntax:
ALTER TABLE existing_table_name rename new_table_name;

Example:
ALTER TABLE student1 rename stud1;
UPDATE COMMAND

To update a table
Syntax:
Update table_name set column_name= ‘New value’;

Example:
Update student1 set town= ‘Alwar’;

To update a specific value after add a new column


Syntax:
Update table_name set column_name= ‘New value’ where column_name= ‘existing value’;

Example:
Update student1 set town= ‘jaipur’ where sid= ‘01’;

To update an existing value


Syntax:
Update table_name set column_name= ‘New value’ where column_name= ‘existing value’;

Example:
Update student1 set town= ‘jaipur’ where sid= ‘01’;

To update multiple values


Syntax:
Update table_name set 1st column_name= ‘New value’, 2nd column_name= ‘New value’
where column_name= ‘existing value’;

Example:
Update student1 set town= ‘Tonk’, class= ‘10’ where sid= ‘01’;
WHERE CLAUSE
Equal
To select a row or a record of one entity
Syntax
Select*from table_name where column_name = ‘value’;

Example:
Select*from student1 where sid= ‘01’;

Greater than
Syntax
Select*from table_name where column_name > ‘value’;

Example:
Select*from student1 where sid > ‘01’;

less than
Syntax
Select*from table_name where column_name < ‘value’;

Example:
Select*from student1 where sid < ‘01’;

Greater than or equal


Syntax
Select*from table_name where column_name >= ‘value’;

Example:
Select*from student1 where sid >= ‘01’;

less than or equal


Syntax
Select*from table_name where column_name <= ‘value’;

Example:
Select*from student1 where sid <= ‘01’;

Not equal
Syntax
Select*from table_name where column_name <> ‘value’;

Example:
Select*from student1 where sid <> ‘01’;
Between
Syntax
Select*from table_name where column_name between ‘value1 and value 2’;

Example:
Select*from student1 where sid between ‘1 and 2’;

In
Syntax
Select*from table_name where column_name in (‘value1, value 2’);

Example:
Select*from student1 where city in (‘Tonk’, ‘Jaipur’);
DELETE, DROP AND TRUNCATE IN SQL

Delete

To delete a specific row


Syntax:
Delete from table_name where column_name = ‘value’;
Example:
Delete from student1 where sid = ‘03’;

Delete complete table


Syntax:
Delete from table_name;
Example:
Delete from student1;

Drop

To drop a column
Syntax:
Alter table table_name drop column_name;
Example:
Alter table student1 drop town;

To drop a table or a database


Syntax:
Drop table table_name;
Example:
Drop table student1;

Syntax:
Drop database database_name;
Example:
Drop database school1;

Truncate table
Syntax:
Truncate table table_name;
Example:
Truncate table student1;
NOT NULL CONSTRAINT IN SQL
While create table:
Syntax:
Create table table_name (column1 datatype not null, column2 datatype(range));

Example:
Create table student2(sid int not null, name varchar(5));

Alter an existing column


Syntax:
Alter table table_name Modify column_name datatype Not Null;

Example:
Alter table persons Modify Age int Not Null;
UNIQUE CONSTRAINT IN SQL

Apply on single column

At the end of a query


Syntax:
Create table table_name (column1 datatype not null, column2 datatype (range), unique
(column_name));

Example:
Create table student2 (id int not null, name varchar (15), unique (id));

In middle of a query
Syntax:
Create table table_name (column1 datatype not null unique, column2 datatype (range));

Example:
Create table student2 (id int not null unique, name varchar (15));

Apply on multiple columns

At the end of a query


Syntax:
Create table table_name (column1 datatype not null, column2 datatype (range), constraint
UC_table_name unique (column1, column2));

Example:
Create table student2 (id int not null, name varchar (15), constraint UC_student2 unique
(id,name));

In middle of a query
Syntax:
Create table table_name (column1 datatype not null unique, column2 datatype (range)
unique);

Example:
Create table student2 (id int not null unique, name varchar (15) unique);

Add Unique in an existing table


Syntax:
Alter table table_name Add Unique (column_name);

Example:
Alter table student2 Add Unique (Sid);
Drop Unique constraint from an existing table
Syntax:
Alter table table_name drop constraint column_name;

Example:
Alter table student2 drop constraint sid;
PRIMARY KEY IN SQL

With single column during table creation time

With the column name


Syntax:
CREATE TABLE Table_name (column1 datatype NOT NULL primary key, column2
datatype(range));

Example:
CREATE TABLE Std_pk (sid int NOT NULL primary key, name varchar (30));

After the column names


Syntax:
CREATE TABLE Table_name (column1 datatype NOT NULL, column2 datatype(range),
PRIMARY KEY (column1));

Example:
CREATE TABLE Std_pk (sid int NOT NULL,name varchar(30), PRIMARY KEY (sid));

With multiple columns


Syntax:
CREATE TABLE Table_name (column1 datatype NOT NULL, column2 datatype(range),
PRIMARY KEY (column1, column2));

Example:
CREATE TABLE Std_pk (sid int NOT NULL,name varchar(30),
PRIMARY KEY (sid,name));

Add primary key in an existing column

With single column


Syntax:
Alter table table_name add primary key (column_name);

Example:
Alter table Std_pk add primary key (sid);

With multiple columns


Syntax:
Alter table table_name add primary key (column1, column2);

Example:
Alter table Std_pk add primary key (Sid, name);
Drop a primary key
Syntax:
Alter table table_name drop primary key;

Example:
Alter table Std_pk drop primary key;
FOREIGN KEY IN SQL

Apply foreign key at table creation time

Syntax:
Create table table_name (column1 datatype(range), column2 datatype(range), foreign key
(column_name) references primary key table_name (primary key column_name));

Example:
create table std_fk (id int, city varchar (15), foreign key (id) references std_pk (sid));

Here in this query two tables are used.


First table is the table in which we apply foreign key such as “std_fk”.
Second table is the table in which we apply primary key such as “std_pk”.

Both tables are being created separately and individually.


For more details, please watch the video.

Add foreign key in an existing table


First delete all the values of the existing table.

Syntax:
Alter table table_name add foreign key (column_name) references primary key table_name
(primary key column_name);

Example:
Alter table stdfk add foreign key (sid) references std_pk(sid);

Here in this query two tables are used.


First table is the table in which we add foreign key such as “stdfk”.
Second table is the table in which we applied primary key such as “std_pk”.

Both tables are being created separately and individually.


For more details, please watch the video.

Drop foreign key constraints in a table


The method is quite different from Primary Key.
First apply this query to show the code block of the table’s query.

syntax
Show create table table_name;

Example:
Show create table stdfk;

After this query the code block of the table is shown. Find out the foreign key constraint
name.
Now apply this constraint name with Alter table query.

Syntax:
Alter table table_name drop foreign key constraint_name;

Example:
Alter table stdfk drop foreign key stdfk_ibfk_1;

After follow this whole procedure we can remove the foreign key from a table.
I personally suggest that please watch the video.
INDEX
1. Order By Command
2. Auto-Increment Command
3. SQL Index Constraint
4. And, Or, Not Operators In SQL
5. SQL Limit Clause, Min & Max Function
6. Count, Sum & Avg Function In SQL
7. SQL In, Between Operator
8. Like Operator In SQL
9. Alias And Group by Clause In SQL
10. Group By
11. All, Any/Some Operators In SQL
ORDER BY COMMAND
Simple order
Syntax:
Select*from table_name order by column_name;
Example:
Select*from s_index order by age;

In Descending order
Syntax:
Select*from table_name order by column_name desc;
Example:
Select*from s_index order by age desc;

Choose Multiple columns


Syntax:
Select*from table_name order by column1_name, column2_name;
Example:
Select*from s_index order by age,class;

Multiple columns with random order


Syntax:
Select*from table_name order by column1_name asc, column2_name desc;
Example:
Select*from s_index order by age asc, class desc;
AUTO-INCREMENT COMMAND
Apply Auto_increment
Syntax:
Create table table_name (column1 datatype(range) auto_increment, column2
datatype(range));
Example:
Create table s_autoincrement (Sid int auto_increment, name varchar (20));
By default, value is 1.
We can start it by any number like 51.

Alter the running value


Syntax:
Alter table table_name auto_increment=starting value;
Example:
Alter table s_autoincrement auto_increment=51;
SQL INDEX CONSTRAINT

CREATE INDEX
Syntax:
CREATE INDEX index_name ON table_name (column1, column2, ...);
Example:
CREATE INDEX index_city ON std1 (city);
AND, OR, NOT OPERATORS IN SQL
And Operator
Select all columns which satisfy the condition
Syntax:
SELECT * FROM table_name WHERE condition 1 AND condition 2;
Example:
SELECT * FROM s_index WHERE city='Jaipur' AND Sid='7';

Select single or selected columns which satisfy the condition


Syntax:
SELECT column1, column2, ……. column N FROM table_name WHERE condition1 AND
condition2 AND condition;
Example:
SELECT name, age FROM s_index WHERE city='Jaipur' AND Sid='7';

Or Operator
Select all columns which satisfy the condition
Syntax:
SELECT * FROM table_name WHERE condition 1 or condition 2;
Example:
SELECT * FROM s_index WHERE city='Jaipur' or Sid='7';

Select single or selected columns which satisfy the condition


Syntax:
SELECT column1, column2, ……. column N FROM table_name WHERE condition1 AND
condition2 AND condition;
Example:
SELECT name, age FROM s_index WHERE city='Jaipur' or Sid='7';
Not Operator
Select all columns which satisfy the condition
Syntax:
SELECT * FROM table_name WHERE Not condition 1;
Example:
SELECT * FROM s_index WHERE not city='Jaipur';

Select single or selected columns which satisfy the condition


Syntax:
SELECT column1, column2, ……. column N FROM table_name WHERE Not condition1;
Example:
SELECT name, age FROM s_index WHERE Not city='Jaipur';

And-Or Operator
Select all columns which satisfy the condition
Syntax:
SELECT * FROM table_name WHERE condition 1 And (condition2 or condition 3);
Example:
SELECT * FROM s_index WHERE age='16' and (city=’Jaipur’ or city=’patna’);

Select single or selected columns which satisfy the condition


Syntax:
SELECT column1, column2, ……. column N FROM table_name WHERE condition 1 And
(condition2 or condition 3);
Example:
SELECT name, age FROM s_index WHERE age='16' and (city=’Jaipur’ or city=’patna’);
Not-And Operator
Select all columns which satisfy the condition
Syntax:
SELECT * FROM table_name WHERE Not condition 1 And Not condition2;
Example:
SELECT * FROM s_index WHERE not age='16' and not city=’Jaipur’;

Select single or selected columns which satisfy the condition


Syntax:
SELECT column1, column2, ……. column N FROM table_name WHERE Not condition 1
And Not condition2;
Example:
SELECT name, age FROM s_index WHERE not age='16' and not city=’Jaipur’;
SQL LIMIT CLAUSE, MIN & MAX FUNCTION

Set Limit or Select Top


Syntax:
SELECT*FROM table_name WHERE condition LIMIT number;
Example:
SELECT*FROM std1 WHERE condition=’Value’ LIMIT 2;

Maximum
Syntax:
SELECT MAX(column_name) As temporary_view_name FROM table_name;
Example:
SELECT MAX(age) As maximum_age FROM std1;

Minimum
Syntax:
SELECT Min(column_name) As temporary_view_name FROM table_name;
Example:
SELECT Min(age) As minimum_age FROM std1;
COUNT, SUM & AVG FUNCTION IN SQL

Count Command (apply on all datatypes)


Syntax:
SELECT count (column_name) from table_name;
Example:
SELECT count (Sid) from std1;

Average command (only Numeric datatypes)


Syntax:
SELECT Avg (column_name) from table_name;
Example:
SELECT Avg (age) from std1;

Summation command (only Numeric datatypes)


Syntax:
SELECT Sum (column_name) from table_name;
Example:
SELECT Sum (age) from std1;
SQL IN, BETWEEN OPERATOR
IN Operator
To select specific values
Syntax:
SELECT*FROM table_name WHERE column_name IN (value1, value2, ...);
Example:
SELECT*FROM s_index WHERE age IN (‘14’,’16’);

Not to select specific values


Syntax:
SELECT*FROM table_name WHERE column_name not IN (value1, value2, ...);
Example:
SELECT*FROM s_index WHERE age not IN (‘14’,’16’);

Between Operator
To select specific values
Syntax:
SELECT*FROM table_name WHERE column_name Between value1 and value2;
Example:
SELECT*FROM s_index WHERE age between ‘14’ and ’16’;

Not to select specific values


Syntax:
SELECT*FROM table_name WHERE column_name not Between value1 and value2;
Example:
SELECT*FROM s_index WHERE age not between ‘14’ and ’16’;
LIKE OPERATOR IN SQL
Like Operator
Syntax:
SELECT*FROM table_name WHERE column_name like ‘ ’;
Example:
SELECT*FROM s_index WHERE city like ‘a%’;

Here is the list of all LIKE operators with '%' and '_' wildcards:

LIKE Operator Description


WHERE column_value LIKE 'a%' Finds any values that start with "a"
WHERE column_value LIKE '%a' Finds any values that end with "a"
WHERE column_value LIKE '%or%' Finds any values that have "or" in any position
WHERE column_value LIKE '_r%' Finds any values that have "r" in the second
position
WHERE column_value LIKE 'a_%' Finds any values that start with "a" and are at
least 2 characters in length
WHERE column_value LIKE 'a__%' Finds any values that start with "a" and are at
least 3 characters in length
WHERE column_value LIKE 'a%o' Finds any values that start with "a" and ends with
"o"
ALIAS AND GROUP BY CLAUSE IN SQL
ALIAS
SQL aliases are used to give a table, or a column in a table, a temporary name.
An alias is created with the AS keyword.
Operations on column of a table
Syntax:
SELECT column_name AS alias_name FROM table_name;
Example:
SELECT name AS Student_name FROM std1;

Merge Multiple columns


Syntax:
SELECT concat_ws (‘,’, column1_name, column2_name) AS alias_name FROM
table_name;
Example:
SELECT concat_ws (‘,’, name, class) AS details FROM student;

Operation on multiple tables


Syntax:
SELECT alias.column1_name, alias.column2_name from table1_name as alias_name,
table2_name as alias_name where condition in table1_name = condition in table2_name;
Example:
SELECT l.bid, l.bname, s.name from library as l, student as s where s.sid = l.sid;
GROUP BY
It groups the rows which have same values in search results.
Most of the time used with aggregate functions like Count, Max, Min etc.
Without any specific sorting order
Syntax:
Select count (column1_name), column2_name from table_name Group by column_name;
Example:
Select count (bid), bname from library Group by bid;

With a specific sorting order


Syntax:
Select count (column1_name), column2_name from table_name Group by column_name
order by Column_name asc/desc;
Example:
Select count (bid), bname from library Group by bname order by bname asc/desc;
ALL, ANY/SOME OPERATORS IN SQL
Any/Some
Use a subquery to execute main query.
Use Boolean function.
Execute the main query if Any of the subquery values meet the condition.
Syntax:
SELECT ColumnX_name from table_name where columnY_name operator any (select
columnY_name from table_name where condition);
Example:
SELECT sname from std5 where percentage_in_last_class > any (select
percentage_in_last_class from std5 where class = 10);

SOME
Syntax:
SELECT ColumnX_name from table_name where columnY_name operator some (select
columnY_name from table_name where condition);
Example:
SELECT sname from std5 where percentage_in_last_class > some (select
percentage_in_last_class from std5 where class = 10);

ALL
Use a subquery to execute main query.
Use Boolean function.
Execute the main query if all of the subquery values meet the condition.
Syntax:
SELECT ColumnX_name from table_name where columnY_name operator all (select
columnY_name from table_name where condition);
Example:
SELECT sname from std5 where percentage_in_last_class > all (select
percentage_in_last_class from std5 where class = 10);
INDEX
1. Case statement in SQL
2. Insert into select statement in SQL
3. Copy data from one table to another
4. SQL view statement & create table from another table
5. Having clause in SQL
6. Exists clause in SQL
7. Join in SQL | types of joins | inner join
8. Left join, right join & full outer join in SQL
9. Right join
10. Full outer/ outer join
11. Cross join
12. Natural join
13. Self join
CASE STATEMENT IN SQL
Syntax:
Select column_name
Case
when condition1 then result1
when condition2 then result2
when conditionn then resultn
else result
End as alias_name
From table_name;
Example:
Select sname
Case
when percentage_in_last_class>70 then 1st_division
else 2nd_division
End as division
From std5;
INSERT INTO SELECT STATEMENT IN SQL
COPY DATA FROM ONE TABLE TO ANOTHER
For all data
Syntax:
Insert into table2 select * from table1 where condition;
Example:
Insert into std6 select * from student where class=10;

For selected data


Syntax:
Insert into table2 (column1, column2,…column n) select column1, column2,…column n
from table1 where condition;
Example:
Insert into std6 (sid, name, class) select sid, name, class from std5 where class=10;
SQL VIEW STATEMENT & CREATE TABLE FROM
ANOTHER TABLE
View
Create view
Syntax:
Create view view_name as select column1, column2, ... From table_name where condition;
Example:
Create view class_10 as select sid, sname, class from std5 where class=10;

Show view
Syntax:
Select*from view_name;
Example:
Select*from class_10;

Show view
Syntax:
Drop view view_name;
Example:
Drop view class_10;

Create table from another table


Syntax:
Create table new_table_name as select column1, column2,...from existing_table_name where
....;
Example:
Create table topper as select sid, sname from std5 where class=10;
HAVING CLAUSE IN SQL
Syntax:
Select column_name from table_name group by column_name having condition;
Example:
Select count(bid), bname from library group by bname having count(bid)>=1;

With where clause


Syntax:
Select column_name from table_name where condition group by column_name having
condition;
Example:
Select count(bid), bname from library where sid=1 group by bid having count(bid)>=1

With a specific order


Syntax:
Select column_name from table_name where condition group by column_name having
condition order by column_name(s);
Example:
Select count(bid), bname from library where sid=1 group by bid having count(bid)>=1 order
by bname;
EXISTS CLAUSE IN SQL
Syntax:
Select column_name from table_name where exists (select column_name from table_name
where condition);
Example:
Select bname, name from library natural join student where exists (select name from student
where student.sid=library.sid);
JOIN IN SQL | TYPES OF JOINS | INNER JOIN
INNER JOIN
SELECTED COLUMN
Syntax:
Select column_name from table1 inner join table2 on table1.column_name =
table2.column_name;

Example:
Select std1.sid, name, bid, bname from std1 inner join library on std1.sid = library.sid;

Join all columns


Syntax:
Select*from table1 inner join table2 on table1.column_name = table2.column_name;

Example:
Select*from std1 inner join library on std1.sid = library.sid;
LEFT JOIN, RIGHT JOIN & FULL OUTER JOIN IN SQL
LEFT JOIN
SELECTED COLUMN
Syntax:
Select column_name from table1 left join table2 on table1.column_name =
table2.column_name;
Example:
Select std1.sid, name, bid, bname from std1 left join library on std1.sid = library.sid;

Join all columns


Syntax:
Select*from table1 left join table2 on table1.column_name = table2.column_name;

Example:
Select*from std1 left join library on std1.sid = library.sid;
RIGHT JOIN
SELECTED COLUMN
Syntax:
Select column_name from table1 right join table2 on table1.column_name =
table2.column_name;
Example:
Select std1.sid, name, bid, bname from std1 right join library on std1.sid = library.sid;

Join all columns


Syntax:
Select*from table1 right join table2 on table1.column_name = table2.column_name;
Example:
Select*from std1 right join library on std1.sid = library.sid;
FULL OUTER/ OUTER JOIN
SELECTED COLUMN
Syntax:
Select column_name from table1 LEFT join table2 on table1.column_name =
table2.column_name
UNION
Select column_name from table1 right join table2 on table1.column_name =
table2.column_name;

Example:
Select std1.sid, name, bid, bname from std1 LEFT join library on std1.sid = library.sid
UNION
Select std1.sid, name, bid, bname from std1 right join library on std1.sid = library.sid;

Join all columns


Syntax:
Select*from table1 LEFT join table2 on table1.column_name = table2.column_name
UNION
Select*from table1 RIGHT join table2 on table1.column_name = table2.column_name;
Example:
Select*from std1 LEFT join library on std1.sid = library.sid
UNION
Select*from std1 right join library on std1.sid = library.sid;
CROSS JOIN
SELECTED COLUMN
Syntax:
Select column_name from table1 CROSS join table2;
Example:
Select std1.sid, name, bid, bname from std1 CROSS join library;

Join all columns


Syntax:
Select*from table1 CROSS join table2;
Example:
Select*from std1 right join library;
NATURAL JOIN
SELECTED COLUMN
Syntax:
Select column_name from table1 NATURAL join table2;
Example:
Select std1.sid, name, bid, bname from std1 NATURAL join library;

Join all columns


Syntax:
Select*from table1 NATURAL join table2;
Example:
Select*from std1 NATURAL join library;
SELF JOIN
Syntax:
Select column_name from table1 t1, table1 t2 where condition;
Example:
Select e1.ename “employee”, e2.ename “manager” from emp e1, emp e2 where
e2.eid=e1.manager_id;

You might also like