SQL_commands2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

SQL:

SQL Commands
Constraints

DDL DML DCl TCL


(Data Definition Language) (Data Manipulation Language) (Data Control language) (Transaction Control Language)

Create Select Grant Commit

Alter Insert Revoke RollBack

Drop Update Save Point

Truncate Delete

rename

• In order to make schema, Table, Mention attributes that’s we do with the help of DDL
• But in order to insert values in that table we use DML
• In DCL we discuss about the access to users of our database
• In TCL we use for transactions like we use online payment (ACID properties work here like if
transaction is complete or in between the process or got failed)
• Constraints: Like when we mention attributes there, we mention constraints (like Keys, Check
constraints, Default, Unique, Default, Null)

Data Types:
In SQL, data types define the type of data that can be stored in a column of a table. Each database
system might have its own set of data types, but here's a list of common data types along with
examples:

1. INT (Integer):

Used for storing whole numbers.

2. VARCHAR(n) (Variable-Length Character String):

Used for storing strings of variable length up to 'n' characters.


3. CHAR(n) (Fixed-Length Character String):

Used for storing fixed-length strings of 'n' characters.

4. DATE:

Used for storing dates (year, month, day).

5. TIME:

Used for storing time of day.


6. DATETIME or TIMESTAMP:

Used for storing both date and time.

7. FLOAT or DOUBLE:

Used for storing floating-point numbers (decimal numbers).

8. BOOLEAN or BIT:

Used for storing boolean values (true or false).

9. BLOB (Binary Large Object):

Used for storing binary data like images, videos, etc.


10. ENUM:

Used for creating a set of predefined values that a column can take.

Connection :

conn sys/sys as sysdba

show user;

How to create a user in ORACLE


create user c##user3 identified by user3;

grant dba to c##user3;

conn c##user3/user3 ;

show user

DDL:
1. Create Command:

Let’s create a table structure

- Create table student (student_id int, Name varchar(30), Address varchar(50));

• In Table Name – we can’t use . or – or stu (space)table this should not be happening
• Table name should be single value
• Data types: Integer, varchar (4 byte size),
• After the last attribute don’t use comma(,) and after closing the bracket put ;(semi-column)

*In workbench its graphical user interface and CMD is character ser interface

Practice:

IN ORACLE:

SELECT table_name FROM user_tables ORDER BY table_name;


• Example1: Create table student (Student_id int, Name varchar(20), Address varchar(30));

desc student;

• Example2: create table student2(RollNumber dec(4) primary key, StudentName varchar(20)


not null, RegistrationNumber dec(5) unique, Course varchar(10), TotalMarks dec(3)
default(100), MarksObtained dec(3), check(MarksObtained<=TotalMarks));
Desc student1;

SQL Statement to Create the Table


CREATE TABLE student1 (
RollNumber DEC(4) PRIMARY KEY,
StudentName VARCHAR(20) NOT NULL,
RegistrationNumber DEC(5) UNIQUE,
Course VARCHAR(10),
TotalMarks DEC(3) DEFAULT 100,
MarksObtained DEC(3),
CHECK (MarksObtained <= TotalMarks)
);
Explanation
1. RollNumber DEC(4) PRIMARY KEY:
o RollNumber: A decimal number with a precision of 4 digits.
o PRIMARY KEY: This column uniquely identifies each record in the table. No two
students can have the same RollNumber.
2. StudentName VARCHAR(20) NOT NULL:
o StudentName: A variable character string with a maximum length of 20 characters.
o NOT NULL: This column cannot have a NULL value; every student must have a name.
3. RegistrationNumber DEC(5) UNIQUE:
o RegistrationNumber: A decimal number with a precision of 5 digits.
o UNIQUE: Each RegistrationNumber must be unique across the table, ensuring no two
students can have the same registration number.
4. Course VARCHAR(10):
o Course: A variable character string with a maximum length of 10 characters.
o No constraints, so this column can be NULL.
5. TotalMarks DEC(3) DEFAULT 100:
o TotalMarks: A decimal number with a precision of 3 digits.
o DEFAULT 100: If no value is specified for this column when a new record is inserted,
it defaults to 100.
6. MarksObtained DEC(3):
o MarksObtained: A decimal number with a precision of 3 digits.
o No constraints, so this column can be NULL.
7. CHECK (MarksObtained <= TotalMarks):
o CHECK: This constraint ensures that the value of MarksObtained cannot exceed the
value of TotalMarks.

Alter Command:
• alter table studentdetails add FatherName varchar(20) ;
• desc student1;


Other ways to use ALTER command
SQL> ALTER TABLE studentdetails ADD date_of_birth DATE;

SQL> ALTER TABLE studentdetails DROP COLUMN Course;

SQL> ALTER TABLE studentdetails MODIFY StudentName VARCHAR2(50);

SQL> ALTER TABLE studentdetails RENAME COLUMN TotalMarks TO MaxMarks;

SQL> ALTER TABLE studentdetails MODIFY MarksObtained DEC(3) NOT NULL;

SQL> ALTER TABLE studentdetails DROP CONSTRAINT check_marks;

Rename Command:
• Rename studentdetails to Studentdata;
• alter table student2 rename column Name to StudentName; (to change the column name in
a table)
• show tables;

Drop Command:
• drop table student1;
• show tables;

Truncate command:
This command will remove all rows from the studentdetails table, but the table structure will
remain intact. It's important to note that TRUNCATE cannot be used on tables that are
referenced by foreign key constraints unless you disable or remove the constraints temporarily.
• Truncate table studentdata;

DML:
Now we already have tables let’s insert values into cells of this table;
1. Insert Command:
insert into studentdetails values (101, 'Sanjay', 'Rajender Singh', 2020, 'B.Tech', 500,
469);
Select * from studentdetails;

2. Now in case of RollNumber is the primary key so it will not accept duplicate entry.

3. Now in registration number we mention it to be unique, so here it will show error.


insert into studentdata values(102, 'priya', 124, 'B.Tech', 100, 84, 'prakash kumar',
'vandana') ;

4. Now if you don’t mention any value for registrationNumber again it will show the error.

insert into studentdata values(103, 'joy', , 'B.Tech', 100, 74, 'pradipta', 'vanshika') ;
5. But if we will mention NULL it will accept it.

insert into studentdata values(103, 'joy',null , 'B.Tech', 100, 74, 'pradipta', 'vanshika') ;

6. If we want to add values for two attributes instead of adding for all

insert into studentdata(rollnumber, studentname) values(104, 'jordan') ;

Here TotalMarks are not null because we already set its default value as 100

7. We used check(MarksObtained<=TotalMarks)
insert into studentdata values(105, 'kriti' ,127, 'MBA' , 100, 101, 'jagnish prasad' , 'mamta
');
Lets use correct command-
insert into studentdata values(105, 'kriti' ,127, 'MBA' , 100, 98, 'jagnish prasad' , 'mamta '
);

Update Command:

update studentdata set fathername= 'prabh singh' where rollnumber = 104;


select * from studentdata;

Delete Command:
If want to delete any record from the table
delete from studentdata where rollnumber=104;
select * from studentdata;

Record is deleted now.

Compound WHERE Clause with multiple AND & OR


Conditions:
• Let’s introduce a new column in the stu table
• Alter table stu add fee int;
• desc studentdetails;
Example 1: Using AND and Where to Filter Rows
select * from stu where fee = 120000 ;
select * from stu where fee = 120000 and rollnumber=101;

Try the following:

• select * from stu where fee > 100000;


• select * from stu where fee > 100000 and rollnumber=101;
• select * from stu where fee=120000 and marksobtained=65;
select * from stu where fee=120000 and mothername='Sunita';

Example 1: Using WHERE,AND and OR to Filter Rows

Now the table is below mentioned:


select * from stu where (fee>100000 and course='pharma') or fee>100000;

JOINS:
SQL joins allow you to combine rows from two or more tables based on a related
column between them. Here are some common SQL join types in MySQL with
examples:

1. INNER JOIN:

The INNER JOIN retrieves records that have matching values in both tables.

• Create two tables having a foreign Key


• Table1: employees
• Create table employees (Emp_ID int primary key, Name varchar(20), Dept_ID
int);
• insert into employees values(1, 'Prakash', 101);
• insert into employees(Emp_ID, Name, Dept_ID) values(2, 'Pritosh', 102),(3,
'Rimple', 103),(4, 'Ridhima', 104);
• Table2 :departments
• Create table departments (Dept_ID int primary key, Dept_Name varchar(20));
• insert into departments(Dept_ID, Dept_Name) values(101, 'HR'),(102,
'HR'),(103, 'Sales'),(104, 'Sales');

• INNER JOIN:
To retrieve a list of employees along with their department names (only
employees who belong to a department):

- select employees.Name, departments.Dept_Name from employees inner


join departments on employees.Dept_ID = departments.Dept_ID;
OR
• select * from employees as emp inner join departments as dept on
emp.Dept_ID = dept.Dept_ID;
o Here * is representing that in resulting table we want to see
all the attributes of tables
o AS is an alias here that helps to give a short / Temporary name
o By using ON clause we mention that which two attributes in
our employees and department table are common to
perform inner join
o In output we will see all attributes and the tuples which are
common in both tables

LEFT JOIN:
In database management systems (DBMS), a LEFT JOIN, also known as a LEFT
OUTER JOIN, is a type of SQL join operation that combines rows from two or
more tables based on a related column, and it returns all rows from the left
table (table1) and matching rows from the right table (table2). If there is no
match found in the right table, NULL values are returned for columns from
the right table.

• select employees.Name,employees.Emp_ID, departments.Dept_Name,


departments.Dept_ID from employees left join departments on
employees.Dept_ID = departments.Dept_ID;
- select employees.Name,employees.Emp_ID, departments.Dept_Name,
departments.Dept_ID from employees inner join departments on
employees.Dept_ID = departments.Dept_ID;

Or
Inner Join
select employees.Name, departments.Dept_Name from employees inner join
departments on employees.Dept_ID = departments.Dept_ID;
Left Join:
select employees.Name, departments.Dept_Name from employees left join
departments on employees.Dept_ID = departments.Dept_ID;

OR

• select * from employees as emp left join departments as dept on emp.Dept_ID


= dept.Dept_ID;
o Here need to note that after ON clause whatever the table we will
mention (emp.Dept_ID = dept.Dept_ID; ) on that table only the left join
will get applied.
o Like now it will show all the data of emp table and just the common
that of dept table

Right Join:
The RIGHT JOIN keyword returns all records from the right table (table2), and the matching
records from the left table (table1). The result is 0 records from the left side, if there is no
match.
Now the tables look like this:

• select employees.Name, departments.Dept_Name from employees right join


departments on employees.Dept_ID = departments.Dept_ID;
Here we can see it is showing null values for the record that doesn’t matches in Table 1
(Employees).

OR

• select * from employees as emp right join departments as dept on


emp.Dept_ID = dept.Dept_ID;

Full Join :
The FULL OUTER JOIN keyword returns all records when there is a match in left (table1) or
right (table2) table records.
| Emp_ID | Name | Dept_ID |
+--------+---------+---------+
| 1 | Prakash | 101 |
| 2 | Pritosh | 102 |
| 3 | Rimple | 103 |
| 4 | Ridhima | 104 |
| 5 | Priya | 101 |
| 6 | Ridha | 101 |
| 7 | Seema | 102 |
| 8 | ritika | NULL |
| 9 | manya | NULL |

Table2:
select * from departments;
+---------+-----------------+
| Dept_ID | Dept_Name |
+---------+-----------------+
| 101 | HR |
| 102 | Sales |
| 103 | marketing |
| 104 | Production |
| 105 | Accounts |
| 106 | Design Thinking |
+---------+-----------------+

• select * from employees as emp left outer join departments as dept on


emp.Dept_ID = dept.Dept_ID union select * from employees as emp right join
departments as dept on emp.Dept_ID = dept.Dept_ID;
• Here for seeing the result we use UNION
• UNION= it simply just combines two tables
• It doesn’t includes duplicate values in the resulting table.
Self Join:
A self-join is a SQL query in which a table is joined with itself. In other words, you use the same
table twice within a single SQL statement, treating it as if it were two separate tables. Self-
joins are often used to model hierarchical or recursive relationships within a table.

• Now let’s say this is new table and for Emp_ID there is a manager with ID = 7
• If we check whole table Seema is the manager of Prakash with Emp_ID= 1
• Now if for better clarity I want to see all details of Seema as a manager of
Prakash in a single tuple then we do that by self join

• select * from employees as t1 join employees as t2 on t2.Emp_ID =


t1.manager_ID;
o here join represents inner join
• select t1.Name as employee_name, t2.Name as manager_name from employees as
t1 join employees as t2 on t2.Emp_ID=t1.manager_ID;

Here if we want to just see employee name and his/her manager name then we will use the
upper mentioned command.

UNION:
Now we have two tables employees and employees2 having an entry common in between
If we use union to join these two tables it will not include duplicate entries
• select employees.Emp_ID, employees.Name from employees union select
employees2.Emp_ID, employees2.Name from employees2;

• Here we can see earlier if we count the total entries in employees and employees2
table it was 11
• But when we use union to combine these tables it didn’t show the duplicate entry and
total count of entries is 10

UNION ALL

• select employees.Emp_ID, employees.Name from employees union all select


employees2.Emp_ID, employees2.Name from employees2;

Cross Join:-

CROSS JOIN is also known as the Cartesian product / Cartesian join.

• A cross join, also known as a Cartesian join or a cross product, is a type of join operation
in relational database management systems (RDBMS). It combines every row from one
table with every row from another table, resulting in a Cartesian product of the two
tables. Unlike other join types like inner joins or outer joins, cross joins do not require
a specific condition or criteria for matching rows; they simply combine all possible
combinations.
• It simply multiplies each row of table 1 with each row of table 2
• Example :

• select * from employees cross join employees2;

You might also like