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

SQL Server Queries

The document discusses various SQL commands for creating, modifying, and deleting databases and tables. It also covers topics like data types, constraints, joins, and functions. Key points include: - Databases can be created, renamed, and dropped using commands like CREATE DATABASE, ALTER DATABASE, and DROP DATABASE. - Tables are created with CREATE TABLE and altered using commands like ALTER TABLE, DROP TABLE, and TRUNCATE TABLE. - Data can be inserted, updated, and deleted from tables. Integrity constraints like primary keys, foreign keys, unique keys, checks, defaults, and indexes can be added. - Queries can retrieve data using joins, grouping, aggregation, filtering and sorting

Uploaded by

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

SQL Server Queries

The document discusses various SQL commands for creating, modifying, and deleting databases and tables. It also covers topics like data types, constraints, joins, and functions. Key points include: - Databases can be created, renamed, and dropped using commands like CREATE DATABASE, ALTER DATABASE, and DROP DATABASE. - Tables are created with CREATE TABLE and altered using commands like ALTER TABLE, DROP TABLE, and TRUNCATE TABLE. - Data can be inserted, updated, and deleted from tables. Integrity constraints like primary keys, foreign keys, unique keys, checks, defaults, and indexes can be added. - Queries can retrieve data using joins, grouping, aggregation, filtering and sorting

Uploaded by

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

Create/Rename/Drop DB

Create Db
CREATE DATABASE basebossFFX;
.mdf file - actual file
.ldf file - transaction log file

Rename DB
-ALTER DATABASE basebossFFX MODIFY Name = basebFFX;
- sp_renameDB ‘oldname’, ‘newname’

Drop DB(deletes mdf/ldf file)


1) Drop database basebossFFX
2) If db in use, set the db to single user mode first
Alter database basebossFFX
SET SINGLE_USER With Rollback Immediate

To change database
Use [basebossFFX]
GO

Create/Rename/Drop Table

Create table
CREATE TABLE tblGender
(
ID int NOT NULL Primary Key,
Gender nvarchar(50) NOT NULL
)

Adding ForeignKey
Alter table tblPerson add constraint tblPerson_GenderID_FK
Foreign Key (GenderId) references tblGender(ID)

Insert Data
INSERT INTO tblPerson (ID, Name, Email)
VALUES (7, ‘sumia’, ‘[email protected]’)

Delete Record
DELETE FROM tblPerson
WHERE Name=’sumia’

Adding Constraints

Alter existing column to add default Constraints


ALTER TABLE tblPerson
ADD CONSTRAINT DF_tblPerson_GenderId
DEFAULT 3 FOR GenderId

Add a new column with default value


ALTER TABLE tblPerson
ADD GenderId varchar(50) NULL
CONSTRAINT DF_tblPerson_GenderId
DEFAULT 3

Drop Constraint/Check Constraint


ALTER TABLE tblPerson
DROP CONSTRAINT DF_tblPerson_GenderId

Cascade referential integrity constraint

Values
No Action: would not allow you to delete the row.
Cascade: if we delete fk from its original table, the dependent table will delete the records
containing that fk
Set Null: the value will be replaced by null.
Set Default: the value will be replaced by default value for that fk.

Adding check constraint

ALTER TABLE tblPerson


ADD CONSTRAINT CK_tblPerson_Age
CHECK (Age > 0 AND Age < 150)

Identity Column

Find datatype of a column


- Column folder on the object explorer
- Highlight table name and press alt+F5
Finding Missing Date Ranges

Step1:
(The volume of numbers in table will be equal to the number of days in the year 2007)
SET NONCOUNT ON –doesn’t return affected row count
--create auxiliary table
DECLARE @startDate smalldatetime, @endDate smalldatetime
SELECT @startDate=’Jan 01, 2007’ @endDate = DATEADD(yy,1,@startDate)

IF EXISTS
(SELECT * FROM sysobjects
WHERE
ID = (OBHECT_ID(‘sequence’)) AND
xtype = ‘U’
)
DROP TABLE sequence;
CREATE TABLE sequence(num INT NOT NULL PRIMARY KEY);

WITH numbers AS
(
SELECT 1 AS num
UNION ALL
SELECT num + 1 FROM numbers
WHERE num < (SELECT DATEDIFF(dd, @startDate, @endDate)
)

INSERT INTO sequence


SELECT num FROM numbes
OPTION(MAXRECURSION 0);

Step2:
(Generate test data and load the data into a sample table. Then produce the gaps by deleting
dates where the number of days since Jan 01, 1900 divided by 4 or 5 or 6 has zero remainder)

DECLARE @iniDate datetime;


SELECT @iniDate = ‘Dec 31, 2006’
IF EXISTS(SELECT * FROM sysobjects
WHERE ID = (OBJECT_ID(‘sampleDates’)) AND xtype = ‘U’)
DROP TABLE sampleDates;

CREATE TABLE sampleDates(theDate smalldatetime PRIMARY KEY)


INSERT INTO sampleDates
SELECT DATEADD(dd, num, @iniDate) theDate
FROM sequence;

--create gaps
DELETE sampleDates
WHERE DATEDIFF(dd, 0, theDate) % 3 = 0
OR DATEDIFF(dd, 0, theDate) % 4 = 0
OR DATEDIFF(dd, 0, theDate) % 5 = 0;
SELECT * FROM sampleDates;

Technique 1 – The simple list


The first technique is quite common and uses outer join

Common Solution – Where missing days are represented by NULLs

SELECT theDate FROM sequence t1


LEFT OUTER JOIN sampleDates t2
ON DATEADD(dd, t1.num, ‘DEC 31, 2006’) = t2.theDate;

The solution that shows only missing days


SELECT DATEADD(dd, num, ‘Dec 31, 2006’) missingDate
FROM sequence t1 LEFT OUTER JOIN sampleDates t2
ON DATEADD(dd, t1.num, ‘Dec 31, 2006’) = t2.theDate
WHERE t2.theDate IS NULL;

Data Types
smalldatetime
date with time of day. The time is based on 24 hour day with seconds always zero(:00)

Identity Column

SET IDENTITY_INSERT tblPerson ON


SET IDENTITY_INSERT tblPerson OFF

When identity insert is on, you have to manually enter the value for identity column.

DBCC CHECKIDENT(‘tblPerson’, RESEED, 0)

--Create Table with Identity Column


Create TABLE Test1
(
ID int IDENTITY(1,1)
Value nvarchar(20)
)

– returns last generated value for identity column


SELECT SCOPE_IDENTITY() –same session and same scope
SELECT @@IDENTITY –same session but any scope
IDENT_CURRENT(‘tableName’) – specific table across any session and any scope.

TRIGGERS

CREATE TRIGGER triggerName ON test1 FOR INSERT--actionname


AS
BEGIN
INSERT INTO test2 VALUES (‘XX’)
END

UNIQUE KEY

Create
CREATE TABLE tblPerson
ADD CONSTRAINT UQ_tblPerson_Email UNIQUE Email

Drop

ALTER TABLE tblPerson


DROP CONSTRAINT UQ_tblPerson_Email

Interview
1. Difference between primary and unique

Primary Unique
To identify a row To prevent duplicates
Cannot be null Can be null
Only one primary key in a table Multiple unique key in table
2. When to use primary and when unique
both ensures uniqueness of column, so when only one col needs to be unique, we can
use primary key. When uniqueness is required in two or more columns, we choose
unique key.
Operators
<>, != NOT EQUAL

Wild Card

% - specifies 0 or more characters


_ - specified exactly one character
[] = any character with in the brackets
[^] – not any character within the bracket

LIKE ‘_@_.com’ – one character


LIKE ‘[MST]%’ – list of characters (starts with MST)
LIKE ‘[^MST]%’ – doesn’t start with MST

ORDER BY

SELECT * FROM tblPerson ORDER BY Name DESC, AGE ASC

Interview:
Find top paid salary

SELECT * FROM tblPerson ORDER BY Salary DESC;

TOP
SELECT TOP 2 Name, Age FROM tblPerson;
SELECT TOP 2 * FROM tblPerson;

SELECT TOP 50 PERCENT FROM tblPerson;

GROUP BY

--total salary of each city


SELECT City, SUM(Salary) as TotalSalary
FROM tblEmployee
GROUP BY City;

HAVING
SELECT * FROM tblEmployees
HAVING SUM(Salary) > 4000
Interview Question:
Diff between where and having

WHERE HAVING
can be used with update/delete/select Only select
Filters rows before aggregation(grouping) After aggregation
Aggregate functions cannot be used with Aggregate functions can be used with having
where clause unless having is used in a clause
subquery

JOIN

1) INNER
2) OUTER
- LEFT JOIN/LEFT OUTER JOIN
- RIGHT JOIN/RIGHT OUTER JOIN
- FULL JOIN/FULL OUTER JOIN
3) CROSS

 JOIN/INNER JOIN – matching rows only


SELECT Name, Gender, Salary, DepartmentName
FROM tblEmployee
JOIN tblDepartment ON tbEmployee.DepartmentID = tblDepartment.ID
 LEFT/LEFT OUTER JOIN – all columns from left table either matching or non matching
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;

 RIGHT JOIN/RIGHT OUTER JOIN


SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;

Full Outer JOIN

FULL OUTER JOIN keyword returns all the rows from the left table (Customers),
and all the rows from the right table (Orders). If there are rows in "Customers"
that do not have matches in "Orders", or if there are rows in "Orders" that do
not have matches in "Customers", those rows will be listed as well.
CROSS JOIN
-produces Cartesian product of two tables
# NON matching rows from left
SELECT * FROM tblEmployee e
LEFT JOIN tblDepartment d ON d.DeptID = e.DeptID
WHERE d.DeptID/e.DeptID IS NULL

# NON matching rows from right


SELECT * FROM tblEmployee e
RIGHT JOIN tblDepartment d ON d.DeptID = e.DeptID
WHERE e.DeptID IS NULL

# NON matching rows from both left and right


SELECT * FROM tblEmployee e
FULL JOIN tblDepartment d ON d.DeptID = e.DeptID
WHERE e.DeptID IS NULL OR d.DeptID IS NULL

SELF JOIN
Joining table with itself so self join
-inner
-outer(left/right/full)
-cross self join

//ALL MATCHING AND NON MATCHING ROWS FROM LEFT TABLE


SELECT e.Name AS Employee, d.Name AS Manager
FROM tblEmployee e
LEFT JOIN tblEmployee d ON d.EmployeeID = e.EmployeeID
WHERE e.ManagerID = d.EmployeeID

//MATCHING ROWS
SELECT e.Name AS Employee, d.Name AS Manager
FROM tblEmployee e
INNER JOIN tblEmployee d ON d.EmployeeID = e.ManagerID

//ALL MATCHING AND NON MATCHING ROWS FROM RIGHT TABLE


SELECT e.Name AS Employee, d.Name AS Manager
FROM tblEmployee e
RIGHT JOIN tblEmployee d ON d.EmployeeID = e. ManagerID

//CROSS JOIN
Cartesian product
# rows firstTable * # rows second table
4 * 5 = 20 rows

SELECT e.Name AS Employee, d.Name AS Manager


FROM tblEmployee e
CROSS JOIN tblEmployee d

Replace NULL
1. ISNULL function

SELECT e.Name AS EmployeeName, ISNULL(d.Name, ‘No Manager’) AS ManagerName


FROM tblEmployee e
LEFT JOIN tblEmployee d ON d.EmployeeID = e.ManagerID

2. COALESCE – returns first non null value (spelling - coal escape e)

SELECT e.Name AS EmployeeName, COALESCE(d.Name, ‘No Manager’) AS ManagerName


FROM tblEmployee e
LEFT JOIN tblEmployee d ON d.EmployeeID = e.ManagerID

3. CASE

SELECT E.EmployeeID as Employee, CASE WHEN ‘No Manager’ ID NULL ELSE D.Name END as
Manager
FROM tblEmployee E
LEFT JOIN tblEmployee D ON D.EmployeeID = E.ManagerID
COALESCE

SELECT COALESCE(FirstName, MiddleName, LastName)


FROM tblEmployee; // will return the name that is not null s

UNION
-removes dupicates
-also sorts data which makes it time consuming

UNION ALL
- Get all rows including duplicates
- does not sort data, so faster than UNION

#common to both
data types and column num has to be the same for both of the tables

You might also like