sql wksht-2

11
SQL Simple Queries – Ch 5 Prof. Mukesh N. Tekwani Page 1 of 11 SQL Queries - Basics Worksheet - 2 DATABASE OPERATIONS 1 CREATE Database Statement: This statement is used to create a database. Syntax CREATE DATABASE { databasename } Arguments database Is the name of the database which is to be created.. Example: CREATE DATABASE student 2 Deleting a database with DROP statement This statement is used to delete a database. Syntax DROP DATABASE { databasename } Arguments: database Example: DROP DATABASE student TABLE OPERATIONS 3 Creating a Table – the CREATE TABLE statement CREATE TABLE tablename (Column1, Column2, Column3,…) Each column is created as ColumnName DataType Options Example: CREATE TABLE Student ( RollNo nvarchar(32), DOB DATE, FullName nvarchar(50), Address NVARCHAR(120), City NvarChar(40), State NVarChar(50), PostalCode nvarchar(20), HomePhone nvarchar(20), );

Upload: mukesh-tekwani

Post on 20-Jan-2015

694 views

Category:

Education


2 download

DESCRIPTION

SQL

TRANSCRIPT

  • 1. SQL Simple Queries Ch 5SQL Queries - Basics Worksheet - 2DATABASE OPERATIONS1 CREATE Database Statement:This statement is used to create a database.SyntaxCREATE DATABASE { databasename }Arguments databaseIs the name of the database which is to be created..Example:CREATE DATABASE student2 Deleting a database with DROP statementThis statement is used to delete a database.SyntaxDROP DATABASE { databasename }Arguments: databaseExample:DROP DATABASE student TABLE OPERATIONS3 Creating a Table the CREATE TABLE statementCREATE TABLE tablename (Column1, Column2, Column3,)Each column is created asColumnName DataType OptionsExample:CREATE TABLE Student(RollNo nvarchar(32),DOB DATE,FullName nvarchar(50),Address NVARCHAR(120),City NvarChar(40),State NVarChar(50),PostalCode nvarchar(20),HomePhone nvarchar(20),);Prof. Mukesh N. TekwaniPage 1 of 11

2. SQL Simple Queries Ch 54Delete a table with DROP TABLE statement DROP TABLE TableNameCOLUMN OPERATIONS5How will you specify unique values in a column? You may want a column to receive a unique value for each of its records. To specify that a column will require unique values, use the UNIQUE keyword. USE College; CREATE TABLE Students ( RollNo int UNIQUE, FirstName nvarchar(50), LastName nvarchar(50) NOT NULL ); When a column has been marked as unique, during data entry, the user must provide a unique value for each new record created. If an existing value is assigned to the column, this would produce an error: USE College; CREATE TABLE Students ( StudentNumber int UNIQUE, FirstName nvarchar(50), LastName nvarchar(50) NOT NULL ); INSERT INTO Students VALUES(2, Jitesh, Patel), (9, Rani, Shah), (4, Preeti, Patel), (9, Deepak, Tiwari), (6, Priyanka, Chopra); By the time the fourth record is entered, since it uses a student number that exists already, the database engine would produce an error.6What is a check constraint? Explain, with the help of a suitable example, how to create a check constraint. Check Constraint: When performing data entry, in some columns, we may want to restrict a range of values that are allowed. We can create a rule that must be followed on a combination of columns before the record can be created. For example, you can ask the database engine to check that at least one of two columns received a value. For example, on a table that holds information about customers, you can ask the database engine to check that, for each record, either the phone number or the email address of thePage 2 of [email protected] 3. SQL Simple Queries Ch 5customer is entered.The ability to verify that one or more rules are respected on a table is called a checkconstraint. A check constraint is a Boolean operation performed by the SQLinterpreter. The interpreter examines a value that has just been provided for acolumn.If the value is appropriate: a. The constraint produces TRUE b. The value gets accepted c. The value is assigned to the columnIf the value is not appropriate: a. The constraint produces FALSE b. The value gets rejected c. The value is not assigned to the columnYou create a check constraint at the time you are creating a table.Example:1. To create a table that has a check mechanism, type the following:CREATE TABLE Customers(CustomerID int ,AccountNumber nchar(10) UNIQUE,FullName nvarchar(50) NOT NULL,PhoneNumber nvarchar(20),EmailAddress nvarchar(50),CONSTRAINT CK_CustomerContactCHECK ((PhoneNumber IS NOT NULL) OR (EmailAddress IS NOT NULL)));2. To add records to the new table, type the following:INSERT INTO Customers(AccountNumber, FullName,PhoneNumber, EmailAddress)VALUES(39, Anita, 301-128-3506, [email protected]),(62, Preeti, (202) 050-1629, [email protected]),(86, Julie, 410-114-6820, [email protected]);3. To try adding a new record to the table, type the following:INSERT INTO Customers(AccountNumber, FullName) VALUES(22, Jiten)Notice that you receive an error.7 Explain how a default value can be given to a column.A default value is one that a column would apply to its record if a value is notProf. Mukesh N. TekwaniPage 3 of 11 4. SQL Simple Queries Ch 5 provided. You can assign a default value when creating a table. To specify the default value in a SQL statement, when creating the column, before the semi-colon or the closing parenthesis of the last column, assign the desired value to the DEFAULT keyword. After creating the table, the user does not have to provide a value for a column that has a default. If the user does not provide the value, the default would be used when the record is saved. Example 1: CREATE TABLE Employees ( FullName NVARCHAR(50), Address NVARCHAR(80), City NVARCHAR(40), State NVARCHAR(40) DEFAULT Maharashtra, PinCode NVARCHAR(4) DEFAULT 400001, Country NVARCHAR(20) DEFAULT India ); Example 2: The default value can also come from a function. CREATE TABLE Employees ( EmployeeName nvarchar(50), DateHired datetime DEFAULT GETDATE(), Address nvarchar(50), City nvarchar(40), State nchar(2) DEFAULT Maharashtra, PostalCode NVARCHAR(4), Country NVARCHAR(20) ); Example 3: If the table exists already and you want to add a column that has a default value, use this method: ALTER TABLE TableName ADD ColumnName Options Here is an example: USE Exercise1; ALTER TABLE Employees ADD HomePhone nvarchar(20) default (000) 000-0000;8Explain how a column can contain an expression. An expression used on a column is a combination of operators and operands used to produce the value of the column. The user will not enter a value for such a column.Page 4 of 11 [email protected] 5. SQL Simple Queries Ch 5Example 1:To create an expression in SQL, in the placeholder of the column, enter the name ofthe column, followed by AS, and followed by the desired expression.CREATE TABLE Circle(CircleID int NOT NULL,Radius decimal(8, 3) NOT NULL,Area AS Radius * Radius * PI());When performing data entry, we must not provide a value for a column that has anexpression; the SQL interpreter would provide the value automatically.INSERT INTO Circle(Radius) VALUES(46.82);INSERT INTO Circle(Radius) VALUES(8.15);INSERT INTO Circle(Radius) VALUES(122.57);RECORD OPERATIONS9 Updating a RecordUpdating a record means changing or more of its values. SQL provides the UPDATEkeyword:Example 1:UPDATE TableNameSET ColumnName = ExpressionExample 2:UPDATE TableNameSET ColumnName = ExpressionWHERE Condition(s)Example 3:UPDATE VideosSET YearReleased = 1996WHERE VideoID = 5;10How can a column or a table be renamed?The sp_rename command changes the name of an object.Syntaxsp_rename object_name , new_name , object_typeobjecttype is the type of the object being renamed. This object may be a TABLE, aCOLUMN, a DATABASE, or an INDEX.To change the name of a column, we specify the command as shown below:Prof. Mukesh N. TekwaniPage 5 of 11 6. SQL Simple Queries Ch 5 Example 1: This example renames the contact title column in the customers table to title. EXEC sp_rename customers.[contact title], title, COLUMN Example 2: To rename a column called rno to RollNo in the tybsc table: EXEC sp_rename tybsc.rno, RollNo, COLUMN To change the name of a table, we specify the command as shown below: EXEC sp_rename tybscit, tybsc11 How can a database be deleted? The DROP DATABASE command is used to delete or DROP a database. Syntax DROP DATABASE database_name [ ,...n ] One or more databases can be deleted in this way. To use DROP DATABASE, the database context of the connection must be in the master database. A database that is currently in use cannot be dropped. Example 1: Drop a single database called publishing, DROP DATABASE publishing Example 2: Delete databases called sybscit and tybscit. DROP DATABASE sybscit, tybscit12 Explain functions in SQL. In Transact-SQL, the primary formula of creating a function is: CREATE FUNCTION FunctionName() For a function to be useful, it must produce a result and return a value. When creating a function, we must specify the type of value that the function would return. To provide this information, after the name of the function, type the RETURNS keyword followed by a definition for a data type.Page 6 of [email protected] 7. SQL Simple Queries Ch 5Example 1:CREATE FUNCTION Addition()RETURNS Decimal(6,3)After specifying the type of value that the function would return, you can create abody for the function. The body of a function starts with the BEGIN and ends with theEND keywords.CREATE FUNCTION Addition()RETURNS Decimal(6,3)BEGINENDBetween the BEGIN and END keywords, we can define the statements the function mustperform. After performing this assignment, just before the END keyword, you must specifythe value that the function returns. This is done by typing the RETURN keyword followedby an expression.CREATE FUNCTION Addition()RETURNS Decimal(6,3)BEGINRETURN ExpressionENDFunction Calling:After a function has been created, we can use the value it returns. Using a function isalso referred to as calling it. To call a function, you must qualify its name. To do this,type the name of the database in which it was created, followed by the periodoperator, followed by dbo, followed by the period operator, followed by the name ofthe function, and its parentheses. The formula to use is:DatabaseName.dbo.FunctionName()A Parameterized FunctionTo create a function that takes a parameter, specify a name and the type of value ofthe parameter(s) in its parentheses. Here is an example:CREATE FUNCTION Addition(@Number1 Decimal(6,2))When a function takes a parameter, in the body of the function, you can use theparameter as if you knew its value, as long as you respect the type of that value. Hereis an example:CREATE FUNCTION Addition(@Number1 Decimal(6,2))RETURNS Decimal(6,2)BEGINRETURN @Number1 + 1450ENDProf. Mukesh N. TekwaniPage 7 of 11 8. SQL Simple Queries Ch 513 Explain what is meant by a procedure in SQL. A procedure is a collection of SQL statements. One of the simplest procedures is selecting columns from a table. This is done with the SELECT operator. For example, to create a stored procedure that would hold a list of students from a table named Students, we would create the procedure as follows: CREATE PROCEDURE GetStudDetails AS BEGIN SELECT FirstName, LastName, DateOfBirth, Gender FROM Students END Executing a Procedure To execute a procedure, you use the EXECUTE keyword followed by the name of the procedure. EXECUTE ProcedureName Instead of EXECUTE, you can use the EXEC keyword: EXEC ProcedureName For example, if you have a procedure named GetStudDetails, to execute it, we would type: EXECUTE GetStudentIdentification Example 3: Write a procedure that creates the full name using the fields FirstName and LastName CREATE PROCEDURE GetStudentIdentification AS BEGIN SELECT FullName = FirstName + + LastName,DateOfBirth, Gender FROM Students END Example 4: Write a procedure that calls a function in its body. USE STUDENT; CREATE PROCEDURE GetStudentsAges AS BEGIN SELECT FullName = FirstName + N+ LastName,DATEDIFF(year, DateOfBirth, GETDATE()) AS Age,Gender FROM Students ENDPage 8 of 11 [email protected] 9. SQL Simple Queries Ch 514How can a procedure be modified?ALTER PROCEDURE ProcedureNameASBody of ProcedureHow can a procedure be deleted?When we dont need a procedure anymore, we can delete it.There are various types of stored procedures, some of which are consideredtemporary. Those types of procedures delete themselves when not needed anymore,such as when the person who created the stored procedure disconnects from thedatabase or shuts down the computer. Otherwise, to delete a procedure, you can useeither the Object Explorer or SQL.To delete a procedure in SQL, the syntax to use is:DROP PROCEDURE ProcedureNameINDEX15What is an index?If you take a look at the last pages of a book (such as a book about mathematics,computer science, etc), you may find a series of pages that start in a section labelIndex. The words in that series allow you to locate a section of the book thatmentions, explains, or describes the word and related topics. An index in a bookmakes it easy and fast to get to a section of a book that deals with a particular topic.Like a book, a table or a view can use the mechanism provided by an index. In a tableor a view, an index is a column (or many columns) that can be used to locate recordsand take a specific action based on some rule reinforced on that (those) column(s).16How can an index be created in SQL?To create an index in SQL, the basic formula to follow is:CREATE INDEX IndexName ON Table/View(Column(s))The creation on an index starts with the CREATE INDEX expression, followed by aname for the index, followed by the ON keyword. In the Table/View placeholder, enterthe name of the table or view for which you want to create the index, followed byparentheses in which you enter at least one column.Example 1:-- =============================================-- Database: Exercise-- =============================================USE masterProf. Mukesh N. TekwaniPage 9 of 11 10. SQL Simple Queries Ch 5 -- Drop the database if it already exists IF EXISTS (SELECT nameFROM sys.databasesWHERE name = Exercise ) DROP DATABASE Exercise CREATE DATABASE Exercise USE Exercise; -- ============================================= -- Database: Exercise -- Table;Employees -- ============================================= CREATE TABLE Employees ( EmployeeNumber int NOT NULL, LastName nvarchar(20) NOT NULL, FirstName nvarchar(20), Username nchar(8) NOT NULL, DateHired date NULL, HourlySalary money ); GO INSERT INTO Employees VALUES(62480, James, Haans, jhaans, 1998-10-25, 28.02), (35844, Gertrude, Monay, gmonay, 2006-06-22, 14.36), (24904, Philomne, Guillon, pguillon, 2001-10-16, 18.05), (48049, Eddie, Monsoon, emonsoon, 08/10/2009, 26.22), (25805, Peter, Mukoko, pmukoko, 03-10-2004, 22.48), (58405, Chritian, Allen, callen, 06/16/1995, 16.45); GO CREATE INDEX IX_Employees ON Employees(EmployeeNumber); GO If the index will include more than one column, list them separated by commas. Here is an example: CREATE INDEX IX_Employees ON Employees(LastName, Username); GO17 How can an index be deleted? If you dont need an index anymore, you can delete it. The basic syntax to delete an index is: DROP INDEX IndexName ON TableName;Page 10 of 11 [email protected] 11. SQL Simple Queries Ch 5In this formula, replace the TableName with the name of the table that contains theindex. Replace the IndexName with the name of the index you want to get rid of.Here is an example:USE Exercise;GODROP INDEX IX_Employees ON Employees; TRIGGERS18What is a trigger?When an action has been performed on a table, such as adding a new record, changing(editing/updating) an existing record, or deleting a record, the table produces anotification. We say that the table fires an event. You can use this occurring event totake some action.A trigger is an action that is performed behind-the-scenes when an event occurs on atable.Prof. Mukesh N. TekwaniPage 11 of 11