SQL Programming Knowledge
equal : =
not equal: : != or <>
Note: to see the line numbers: Tools ==>Options...==>Text Editor==>All languages==>General==>Check Line numbers==>ok
Note: If you want to do any changes but you are not allowed you can :
Tools==> Options...===>Designers==>uncheck Prevent saving changes that require table re creation
Database
Create Database
Method #1:
You can create a database by using GUI(Graphical User Interface):
Object Explorer==>Databases==>Right click==> New Database...==> type a name ==> Ok
Method #2:
You can create a database by using T SQL
click on the New Query icon then write the following commands highlight them and press F5 or
Press Execute button
create database dbtest1; ; in SQL is optional
Create database db2
create database db3
alter database db3 modify name=db3_test
drop database db2
Note: if you want to see this new database go to the Object Explorer window, select Databases, and then
Press Refresh icon
New version of SQL is not case sensitive for syntax and names of tables and databases and columns, it is case sensitive just
for values inside tables
Create DataBASE dbMaryam;
go go is optional, and you can use it at the end of each batch to separate batches
Drop/delete Database
Method #1: by using GUI: Object Explore==> expand Databases==> Choose the name of database that you
want to delete then R.C. on it ==> Delete==>ok
Method #2:By using T SQL
drop database dbtest1
go
Ex: create a new database called dbnew
create database dbnew
go
change name of Database
change name of dbnew to dbnew2 or dbnew2 to dbnew3
Method #1: by using GUI: In Object Explorer R.C. on dbnew and Select Rename then type dbnew2
Method #2: by using T SQL:
Alter database dbnew modify name=dbnew1
Ex: drop dbnew1 by using T SQL
drop database dbnew1
Ex: Again create a new database called dbtest1
create database dbtest1
change working database
change your working database from master to dbtest1
Method#1:GUI: above Object Explorer you can see the master press arrow and then select dbtest1
Method#2:T SQL
create database mydb
use mydb
Types of SQL commands:
SQL DML, DDL, DCL, and TCL Commands
1.
*SQL DDL Commands*
In SQL, DDL means Data Definition Language. The Sql Server DDL commands are used to create
and modify the structure of a database and database objects like tables, views, procedures,....
Examples of Sql Server DDL commands are
CREATE – Create an object. I mean, create a database, table, triggers, index, functions, stored procedures, etc.
DROP – This SQL DDL command helps to delete objects. For example, delete tables, delete a database, etc.
ALTER – Used to alter the existing database or its object structures.
TRUNCATE – This SQL DDL command removes records from tables
RENAME – Renaming the database objects
2.
*SQL DML Commands*
DML means Data Manipulation Language in Sql Server. As its name suggests, these Sql Server DML
commands will perform data manipulation( manipulate data presented in the server).
Examples of DML commands in SQL Server are
SELECT – This SQL DML command selects records or data from a table
INSERT – Insert data into a database table.
UPDATE – This SQL DML command will update existing records within a table
DELETE – Delete unwanted records from a table
Difference between delete and truncate:
DELETE:
DELETE is a DML (Data Manipulation Language) command.
It is used to remove specific rows from a table based on a condition you provide.
You can use DELETE with a WHERE clause to specify which rows to delete.
TRUNCATE is a DDL (Data Definition Language) command.
It is used to remove all the rows from a table quickly, effectively resetting the table.
TRUNCATE doesn't use a WHERE clause because it removes all rows by default.
3.
*SQL DCL Commands*
The Sql Server DCL means Data Control Language. These DCL commands in SQL Server will control
the Data access permission.
Sql Server DCL commands Examples are
GRANT – It permits users to access the database.
REVOKE – This SQL DCL command withdraws the permission given by GRANT to access the database.
4.
*SQL TCL Commands*
TCL means Transaction Control Language. These Sql Server TCL commands will control the Transactions..
Examples of TCL commands in SQL Server are
COMMIT – This SQL TCL command will commit the running transaction
ROLLBACK – Rollback(Undo) the current transaction
SAVEPOINT – You can set a save point so that, next time it will start from that point
SET TRANSACTION – Specify the characteristics of the transactions
Create Table
Method #1:Using GUI: Object Explorer==> Choose the name of the database that you want to create a table
inside it==>expand it by press plus sign==>R.C. on Tables==>New==>Table...
type column name, data type, and check or uncheck Allow Nulls and continue for all columns
after that Ctrl+S to save it and name table then refresh Object Explorer and follow the slides
page 26
make sure you assign same data type for GenderId in tblperson and Id in tblGender
go
alter table tblperson
add constraint FK_tblperson_tblgender foreign key (genderid) references tblgender(id)
go
for insert data by using GUI:
RC(Right Click) on table from object explorer select Edit top 200 rows
for print data:
RC(Right Click) on table from Object Explorer select top 1000 rows
Method#2: Using T SQL
retrieve data: for printing all records in tblPerson
select * from tblPerson * means all columns
or
select * from [tblPerson]
or
select * from dbo.tblPerson
0r
select * from [dbo].[TblPerson]
SELECT TOP 3 * FROM tblPerson;
go
Note: If you want to just print some particular columns you should specify the name of those columns
one column
Ex: Retrieve name of people in tblperson
select name from tblPerson
Ex: Retrieve name and email of people in tblperson
more than column: use , between name of columns
select name , EMail from TblPerson
Alias: SQL aliases are used to give a table, or a column in a table, a temporary name.
select name as Name_Of_people from tblPerson as is optional and Name_Of_people is alias
or
select name Name_Of_people from tblPerson
or
select name [Name_Of_people] from tblPerson
if you want to use space in name you have to use sqaure brackets
select name [Name Of people] from tblPerson
select name as [Name of Student] , email as [Email of Student] from tblPerson
or
select name [Name of Student] , email [Email of Student] from tblPerson
go
Note: If you want to do any changes but you are not allowed you can :
Tools==> Options...===>Designers==>uncheck Prevent saving changes that require table re creation
use
Creating tables by using T SQL
create table tblPerson1
(ID int not null,
fname nvarchar(50) not null,
lname nvarchar(50))
go
Insert data(rows)(records)(observations)
Note: for categorical columns, you must wrap their values inside single quotes
Note: In SQL you must wrap characters by using single quotation marks, not double quotation marks
inserting one record
insert into tblPerson1 values
(1,'Maryam','Kazemi')
inserting more than one record:
you can use the insert command for each record or use one insert command for all of them
If you use one insert for several records you should wrap each record in parentheses and
separate records by comma
insert into tblPerson1 values
(2,'Adil','Fagiri'),
(3,'Bachittar','Dhaliwal'),
(4,'Gurdeep','Sandhu')
retrieve data
Select * from tblPerson1
go
Primary Key
primary key :The PRIMARY KEY constraint uniquely identifies each record in a table
1.has to be unique and
2.not empty(not null)
(Primary keys must contain UNIQUE values, and cannot contain NULL values)
3.A table can have at most only ONE primary key; and in the table,
this primary key can consist of single or multiple columns (fields).
Note: We can assign P.K. to one table during the creation of that table or after creating it, but
Be careful after creating and inserting some records, you cannot assign pk to the column that
has duplicated values or has missing values because a primary key
1.has to be unique and
2.not empty(not null)
Create a primary key for existing table
assigning pk to existing table:
Method#1: GUI: R.C. on that table from Object Explorer ==>Design==>
The left side of that column you can :
set P.K. or remove P.K.
Note: make sure that column doesn't have duplicated values or Missing values
Note: If you want to do any changes but you are not allowed you can :
Tools==> Options...===>Designers==>uncheck Prevent saving changes that require table re creation
Method#2: T SQL:
alter table tblperson1
add primary key (Id)
Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must
already have been declared to not contain NULL values (when the table was first created) and It must
have unique values
Note: I will tell you how to assign a specific name to P.K.
in this example the name of p.K. was assigned by SQL and you can find it in Object Explorer by
finding the name of the table then expand the Keys
Drop Pk by using T SQL
alter table tblperson1
drop constraint[PK__tblPerso__3214EC27BE671F31] you should drag and drop the name of P.K here from Object explorer
you can find the name of pk by Object Explore==>expand the table==> expand Keys
or you can name your pk when you add it in the alter command
Assign a specific name for the PRIMARY KEY constraint
ALTER TABLE tblPerson1
ADD CONSTRAINT pk_tblperson_ID PRIMARY KEY (ID); pk_tblperson_ID is the name that i wanted to assign to P.K
Drop Pk by using T SQL
alter table tblperson1
drop constraint pk_tblperson_ID
Assign a name for PRIMARY KEY constraint, and defining a PRIMARY KEY constraint on multiple columns
ALTER TABLE tblPerson1
ADD CONSTRAINT pk_tblperson_ID_and_fname PRIMARY KEY (ID,fName);
I used CONSTRAINT pk_tblperson_ID_and_fname before primary key keyword to assign a name
to my primary key
pk_tblperson_ID_and_fname is the name of Pk
ALTER TABLE tblPerson1
DROP CONSTRAINT pk_tblperson_ID_and_fname;
Assigning PK during creation of table
create table tblGender2
(Id int Not null primary key, not null is optional because Pk by default can't be null
Gender nvarchar(20))
create table tblGender3
(Id int primary key, not null is optional because Pk by default can't be null
Gender nvarchar(20))
In two above example the name of p.K. were assigned by sql if you want to assign specific name you should do similar to code bellow
create table tblgender_4
(id int not null,
Gender nvarchar(20),
constraint PK_tblgender_4_Id primary key(id))
CREATE TABLE Employee (
ID int NOT NULL,
Employee_name varchar(255) NOT NULL,
Employee_designation varchar(255),
Employee_Age int,
UNIQUE(ID)
);
select * from Employee
drop a table
Method #1: using GUI :
Method#2:using T SQL
drop table tblGender3
select * from tblGender3 You will get an Error because tblGender3 does not exist any more
go
Note: in T_sql there is a difference between deleting a table and dropping a table:
when you delete a table by T SQL (delete statement) you just remove all records of that table
not the structure of the table, you just making that table empty
But by dropping a table you remove that table object and all its records from the database
delete tblperson
select * from tblperson
drop table tblperson
select * from tblperson You will get an error because that tblperson is not exist anymore
create table tblperson
(Id int not null primary key, not null is optional :According to the SQL Specification, a primary key can not contain NULL. This means that decorating a column with either "NOT NULL PRIMARY KEY" or just "PRIMARY KEY" should do the same thing.
name nvarchar(50),
email nvarchar(50),
genderid int) if you want to refer this genderid to id in tblgender(FK) you must use the same data type
drop tblperson
drop table tblperson
Assigning a name to the primary key during the creation of the table
Note: the name of Pk is a random name that Sql was created for it
If you want to assign any name you should do like following code
create table tblperson
(Id int not null, not null is optional: According to the SQL Specification, a primary key cannot contain NULL. This means that decorating a column with either "NOT NULL PRIMARY KEY" or just "PRIMARY KEY" should do the same thing.
name nvarchar(50),
email nvarchar(50),
genderid int,
Constraint pk_tblperson_ID primary key(ID))
go
Create a database and name it dbtest2
create database dbtest2
use dbtest2
Please take a look to page 26 in slides of Lecture 1
create table tblperson
(Id int , not null is optional : According to the SQL Specification, a primary key can not contain NULL. This means that decorating a column with either "NOT NULL PRIMARY KEY" or just "PRIMARY KEY" should do the same thing.
name nvarchar(50),
email nvarchar(50),
genderid int, if you want to refer this genderid to id in tblgender(FK) you must use the same data type
Constraint pk_tblperson_ID primary key(ID))
create table tblGender
(Id int Not null primary key,
Gender nvarchar(20))
A FOREIGN KEY
A foreign key is a column or group of columns in a relational database table that provides
a link between data in two tables.
A FOREIGN KEY is a field (or collection of fields) in one table that refers to
another column(usually primary key) in another table.
The table containing the foreign key is called the child table, and the table containing the
candidate key is called the referenced or parent table.
A foreign key can refer to either a unique or a primary key of the parent table.
If the foreign key
refers to a non primary unique key, you must specify the column names of the key explicitly.
F.k. Vs. P.K.
The PRIMARY KEY constraint uniquely identifies each record in a table like studentId
(its values must be unique and can not be missing)
A FOREIGN KEY is a field (or collection of fields) in one table that refers to
another column(usually primary key) in another table
1. unlike PK we can have more than one FK
2.unlike PK , FK can have missing values
3.unlike PK , FK can have duplicated values
Assigning FK to an existing table
Assigning FK to genderid in tblperson reffer it to id in tblgender
Object Explorer ==>tblgender==>Keys
For viewing Dependency :
Object Explorer ==>tblgender==>RC ==>view Dependencies
For creating Database diagram :
Object Explorer ==>expand dbtest2==>Database Diagrams==>R.C ==>New Database Diagram
press Ctrl and select two tables ==>add
Like P.K. If you remove constraint FK_tblperson_tblgender SQL will assign a random name for F.K.
ALTER TABLE tblperson
ADD FOREIGN KEY (genderid) REFERENCES tblgender(id);
Assigning FK during creation of table
Assigning FK to gendercode in tblperson2 refer it to id in tblgender
method #1:allowing sql to select a random name
create table tblperson3
(id int primary key,
name nvarchar(50),
email nvarchar(50),
genderid int references tblgender(id)) here Sql will assign names for Pk and FK
go
**************** method #2:assigning a specific name to F.K or P.K ******************
create table tblperson4
(id int not null,
name nvarchar(50),
email nvarchar(50),
genderid int,
constraint PK_tblperson4 primary key(id),
constraint FK_tblPerson4_tblGender_ID foreign key (genderid) references tblGender(Id))
go
Interview Question: What are the differences between P.K. and F.K.?
The PRIMARY KEY constraint uniquely identifies each record in a table.
primary key has to be unique and not empty(not null) and a table can have at most only ONE primary key;
and in the table, this primary key can consist of single or multiple columns (fields).
A FOREIGN KEY is a field (or collection of fields) in one table that refers to
another column(usually primary key) in another table and unlike P.k. it can be null and have duplicated
values and we can have several FKs in one table
The table containing the foreign key is called the child table, and the table containing the candidate key
is called the referenced or parent table
insert data to table
insert into tblGender values
(1,'male'),(2,'female'),(3,'unknown')
insert into tblperson3 values
(1,'Maryam','maryamkazemi@yahoo.com',2),
(2,'Mary','m@mcoleg',3)
select
select * from tblperson3 * means all columns
select * from tblGender
select name from tblperson3
select name as [first name] from tblperson3 as is optional
select name [first name] from tblperson3
select name ,email from tblperson3 you have to put "," between columns' name
select name [first name],email personal_email from tblperson3
select name fullname,email [personal email] from tblperson3 use hard bracket if you want to have space or special charechters
select * from tblGender
delete
Delete contents of a table= make a table empty not drop that table
delete tblperson
select * from tblperson
insert into tblperson values
(1,'Maryam','maryamkazemi@yahoo.com',2),
(2,'Mary','m@mcoleg',3)
select * from tblperson3 remind me to show dependency diaGRam)
The following example creates a table named T1. Then the second statement drops the table.
The third statement performs no action because the table is already deleted, however it
does not cause an error.
use dbtest1
go
CREATE TABLE T1 (Col1 int);
GO
Drop table T1
Drop table T1 since T1 was dropped we got an ERROR because it does not exist any more
GO
DROP TABLE IF EXISTS T1; IF EXISTS does not work in some version of SQL
DAY 2
评论
发表评论