SQL

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

SQL

---Some of the Most Important SQL Commands---

 SELECT - extracts data from a database


 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index
 Joins: Inner-Left-Right-Full-Cross
 Foreign Key: A foreign key is a key used to link two tables together. This
is sometimes also called as a referencing key.
A Foreign Key is a column or a combination of columns whose values
match a Primary Key in a different table.

Ex: CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

 Primary Key: The PRIMARY KEY constraint uniquely identifies each


record in a database table. Primary keys must contain UNIQUE values,
and cannot contain NULL values. A table can have only one primary key,
which may consist of single or multiple fields.

Ex: CREATE TABLE Persons (


ID int NOT NULL,
LastName nvarchar(255) NOT NULL,
FirstName nvarchar(255),
Age int,
PRIMARY KEY (ID)
);

--------------Different Types of SQL JOINs--------


 (INNER) JOIN: Returns records that have matching values in both
tables
 LEFT (OUTER) JOIN: Return all records from the left table, and the
matched records from the right table
 RIGHT (OUTER) JOIN: Return all records from the right table, and the
matched records from the left table
 FULL (OUTER) JOIN: Return all records when there is a match in either
left or right table

-------------------Inner Join-----------------
Select
S_FirstName,S_LastName,E_FirstName,E_LastName,S_Marks,S_Department,E_Salary
from Students
inner join Emp
on S_ID=E_ID

Order by S_LastName

-------------------Left Join-----------------
Select
S_FirstName,S_LastName,E_FirstName,E_LastName,S_Marks,S_Department,E_Salary
from Students
Left join Emp
on S_ID=E_ID

Order by S_LastName

-------------------Right Join-----------------
Select
S_FirstName,S_LastName,E_FirstName,E_LastName,S_Marks,S_Department,E_Salary
from Students
Right join Emp
on S_ID=E_ID

Order by S_LastName

-------------------Full Outer Join-----------------


Select
S_FirstName,S_LastName,E_FirstName,E_LastName,S_Marks,S_Department,E_Salary
from Students
FULL OUTER join Emp ON S_ID=E_ID;

Order by S_LastName

-----------------SQL Self JOIN--------------------


A self JOIN is a regular join, but the table is joined with itself.

SELECT S_FirstName AS F_Name,E_FirstName AS L_Name,E_Salary


FROM Students,Emp
WHERE S_ID <> E_ID
AND S_FirstName = E_FirstName
ORDER BY S_FirstName;

-----------------CROSS JOIN--------------------

This will return all records where each row from the first table is combined
with each row from the second table. A CROSS JOIN can be specified in two
ways: using the JOIN syntax or by listing the tables in the FROM clause
separated by commas without using a WHERE clause to supply join criteria.
Exmp:

SELECT * from Emp cross Join Students


Or
SELECT * from Emp,Students
OR
SELECT S_FirstName FROM Students
UNION OR ALL
SELECT E_FirstName FROM Emp

------Join 2 different tables in SLQ Server------------


select
S_FirstName,S_LastName,E_FirstName,E_LastName,S_Marks,S_Department,E_Salary
from Students,Emp

------Create Student Table in SLQ Server---------------

Create Table Students(S_FirstName nvarchar(50),S_LastName


nvarchar(50),S_ID INT, S_Marks INT,S_Department nvarchar(50));
Select * from Students

----------Insert Data into Students Tables----

INSERT INTO Students(S_FirstName,S_LastName,S_ID, S_Marks,S_Department)


VALUES('Harikrishna','Challa','1','100','ECE');
---------Students Table----------------
S_FirstName S_LastName S_ID S_Marks S_Department
Harikrishna Challa 1 99 ECE
Sathish Nandivelugu 1 100 ECE
Prateek Anand 3 98 Civils
Hasan Mahammad 4 80 CSE
Amar Nag 5 98 CSE
Mounica Reddy 8 85 Mech
Venu Velle 7 78 EEE

------Create Emp Table in SLQ Server-----------------


Create Table Emp(E_FirstName nvarchar(50),E_LastName nvarchar(50),E_ID INT,
E_Salary INT,E_Skill nvarchar(50));
Select * from Emp

-------------------Insert Data into Tables------------


INSERT INTO Emp(E_FirstName,E_LastName,E_ID, E_Salary,E_Skill)
VALUES('Harikrishna','Challa','1','48000','Testing');

---------Emp Table------------------

E_FirstName E_LastName E_ID E_Salary E_Skill


Harikrishna Challa 1 10000 Testing
Sathish Nandivelugu 2 12000 Dev
Prateek Anand 3 9000 Testing
Hasan Mahammad 3 13000 .NET
Amar Nag 5 14000 .NET
Mounica Reddy 7 8000 Suporting
Venu Valle 7 18000 Suporting

------Retrieve Data from the database---------


Select * from Students;
Select * from Emp;

---------Update Table Values------------------


UPDATE Emp
SET E_Skill = 'Testing'
WHERE E_ID=1;

------Rename the Table name---------------------


ALTER TABLE Students
RENAME TO EMP
------Find Duplicate Rows in Table SQL--------------

SELECT E_FirstName, E_LastName, COUNT(*) as CNT


FROM Emp
GROUP BY E_FirstName, E_LastName
HAVING COUNT(*) > 1;

How can I remove duplicate rows?

To Delete the Duplicate Rows:

DELETE users WHER RowID NOT IN (SELECT MIN(RowID) FROM users GROUP BY name,
email);

Or

DELETE FROM tblemp WHERE id IN(SELECT MIN(id) FROM tbemp GROUP BY title HAVING
COUNT(id)>1)

------------DELETE------------
The DELETE command is used to remove rows from a table. A WHERE clause can be
used to only remove some rows. If no WHERE condition is specified, all rows will be
removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the
transaction to make the change permanent or to undo it. Note that this operation will cause
all DELETE triggers on the table to fire.

Ex: DELETE FROM Emp;

DELETE FROM Emp


WHERE E_FirstName=Harikrishna';

---------------TRUNCATE--------------
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no
triggers will be fired. As such, TRUCATE is faster and doesn't use as much undo space as a
DELETE

EX: TRUNCATE TABLE Students;

------------------DROP---------------------
The DROP command removes a table from the database. All the tables' rows, indexes
and privileges will also be removed. No DML triggers will be fired. The operation cannot be
rolled back.

Ex: DROP TABLE Students;


---------The SQL GROUP BY Statement-------------------

The GROUP BY statement is often used with aggregate functions (COUNT, MAX,
MIN, SUM, AVG) to group the result-set by one or more columns.

----------The SQL ORDER BY Keyword--------

The ORDER BY keyword is used to sort the result-set in ascending or


descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort
the records in descending order, use the DESC keyword.

GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

EX:
---------- Group By --------------------
SELECT COUNT(S_ID),S_FirstName
FROM Students
GROUP BY S_FirstName

1 Amar
1 Harikrishna
1 Hasan
1 Mounica
1 Prateek
1 Sathish
1 Venu

---------- Order By --------------------


SELECT * FROM Students
ORDER BY S_FirstName ASC, S_LastName DESC;

S_FirstName S_LastName S_ID S_Marks S_Department


Amar Nag 5 98 CSE
Harikrishna Challa 1 99 ECE
Hasan Mahammad 4 80 CSE
Mounica Reddy 8 85 Mech
Prateek Anand 3 98 Civils
Sathish Nandivelugu 1 100 ECE
Venu Velle 7 78 EEE

-------The SQL SELECT DISTINCT Statement-------

The SELECT DISTINCT statement is used to return only distinct (different)


values.

Inside a table, a column often contains many duplicate values; and sometimes
you only want to list the different (distinct) values.

The SELECT DISTINCT statement is used to return only distinct (different)


values.

Ex:

------------SELECT DISTINCT Syntax--------


SELECT DISTINCT S_FirstName, S_LastName
FROM Students;

------------- WHERE Clause-------------------

The WHERE clause is used to filter records.

------The SQL AND, OR and NOT Operators---------

The WHERE clause can be combined with AND, OR, and NOT operators.

-----------------AND Syntax----------------
SELECT * From Students,EMP
WHERE S_FirstName = 'Harikrishna' AND E_LastName = 'Challa';

-----------------------OR Syntax--------------
SELECT * From Students,EMP
WHERE S_FirstName = 'Harikrishna' OR E_LastName = 'Challa';

---------------------NOT Syntax-------------------
SELECT * From Students
WHERE NOT S_FirstName = 'Harikrishna'

-----------------Combining AND, OR and NOT------------


SELECT * FROM Students

WHERE S_FirstName='Harikrishna' AND (S_ID='1' OR S_ID='3');

-------------SQL TOP, LIMIT or ROWNUM Clause------

The SELECT TOP clause is used to specify the number of records to return.

SELECT TOP 3 * FROM Students


WHERE S_FirstName='Harikrishna';

----------SQL MIN() and MAX() Functions--------------


---MIN() Example:
SELECT MIN(S_Marks) AS SmallestPrice
FROM Students;

---MAX() Example:
SELECT MAX(S_Marks) AS LargestPrice
FROM Students;

-----Get highest salary from the table

select * from Emp where E_salary in (select distinct top(3) E_salary from
Emp order by E_salary desc)

or
Select MAX(E_salary) from Emp

-------SQL COUNT(), AVG() and SUM() Functions---------


The COUNT () function returns the number of rows that matches a specified
criteria.
The AVG () function returns the average value of a numeric column.
The SUM () function returns the total sum of a numeric column.

-----COUNT() Syntax
SELECT COUNT(S_Marks)
FROM Students

--------No of Rows in a table

SELECT Count(*) FROM Students

-----AVG() Syntax
SELECT AVG(S_Marks)
FROM Students;

-----SUM() Syntax
SELECT SUM(S_Marks)
FROM Students;

---------SQL LIKE Operator------------------

The LIKE operator is used in a WHERE clause to search for a specified pattern in
a column.

There are two wildcards used in conjunction with the LIKE operator:

 % - The percent sign represents zero, one, or multiple characters


 _ - The underscore represents a single character

SELECT * FROM Students


WHERE S_FirstName LIKE 'h%';

------IN Operator Examples----------------


The following SQL statement selects all Students are Last Name.

SELECT * FROM Students

WHERE S_LastName IN ('Challa', 'Nandivelugu', 'Nag');

SELECT * FROM Students


WHERE S_LastName NOT IN ('Challa', 'Nandivelugu', 'Nag');

--------BETWEEN Example----------
SELECT * FROM Students

WHERE S_Marks BETWEEN 78 AND 100;

--------Alias for Columns Examples


SELECT S_FirstName as F_Name, S_LastName AS L_Name
FROM Students;

What will be the maximum number of index per table?


For SQL Server 2008 100 Index can be used as maximum number per table. 1 Clustered
Index and 999 Non-clustered indexes per table can be used in SQL Server.

1000 Index can be used as maximum number per table. 1 Clustered Index and 999 Non-
clustered indexes per table can be used in SQL Server.
What is the difference between SUBSTR and INSTR in the
SQL Server?
The SUBSTR function is used to return specific portion of string in a given string. But,
INSTR function gives character position in a given specified string.

1 SUBSTR(“Smiley”,3)

Gives result as Smi

1 INSTR(“Smiley”,’i’,1)

What is COALESCE in SQL Server?


COALESCE is used to return first non-null expression within the arguments. This function is
used to return a non-null from more than one column in the arguments.

Select COALESCE( E_salary, E_LastName) from Emp;

Column1
10000
12000
9000
13000
14000
8000
18000
48000

The UCASE() Function

The UPPER()&LOWER function converts the value of a field to uppercase.

select UPPER(S_FirstName) from Students;


The LEN() Function

The LEN() function returns the length of the value in a text.

select LEN(S_FirstName) from Students

How to find latest created tables in sql ?


SELECT * FROM Customer
ORDER BY date DESC

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy