SQL Server Queries
SQL Server Queries
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’
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
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.
Identity Column
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)
)
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)
--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;
Data Types
smalldatetime
date with time of day. The time is based on 24 hour day with seconds always zero(:00)
Identity Column
When identity insert is on, you have to manually enter the value for identity column.
TRIGGERS
UNIQUE KEY
Create
CREATE TABLE tblPerson
ADD CONSTRAINT UQ_tblPerson_Email UNIQUE Email
Drop
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
ORDER BY
Interview:
Find top paid salary
TOP
SELECT TOP 2 Name, Age FROM tblPerson;
SELECT TOP 2 * FROM tblPerson;
GROUP BY
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
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
SELF JOIN
Joining table with itself so self join
-inner
-outer(left/right/full)
-cross self join
//MATCHING ROWS
SELECT e.Name AS Employee, d.Name AS Manager
FROM tblEmployee e
INNER JOIN tblEmployee d ON d.EmployeeID = e.ManagerID
//CROSS JOIN
Cartesian product
# rows firstTable * # rows second table
4 * 5 = 20 rows
Replace NULL
1. ISNULL function
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
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