Documente Academic
Documente Profesional
Documente Cultură
By Mr. Mwegi
Introduction to SQL
The Structured Query Language (SQL) is used to interact with a database to access and edit data in it. SQL statements are divided, according to their nature, into three parts
Data Definition Language (DDL) and Data Manipulation Language(DML). Data control language (DCL)
To perform an operation, SQL requires only few lines of code compared to other languages. SQL statements include select which is used to access fields, tables and range of records in a database, inserts for adding new data, and deletes for removing data. When a query is processed the result will be returned in a RecordSet.
Integer Approximate Numeric Exact Numeric Special Date and Time Money Auto-incrementing Datatypes Synonyms User-defined
Comments Stores character strings. Stores binary information in two-byte pairs. Stores integer values. Stores approximate numeric information. Stores exact numeric information. Stores a single bit, character information greater than 255 bytes, or image data. Stores dates and times. Stores currency values. Stores values that are automatically incremented or set by the SQL Server. Maps ANSI datatypes to SQL Server datatypes. You can create your own datatypes to store information.
Nullability
The nullability of a column refers to whether or not an entry is required for that column. If you would like to allow a column to be empty, then specify NULL. If you would like to insist that each row have an entry in that column, specify NOT NULL. If you do not specify NULL or NOT NULL, the system default will be used. When you first install SQL Server, the system default will be NOT NULL. As with most options things in SQL Server, this default can be modified.
Strings
Strings contain character data that is comprised of letters, numbers, and symbols. You can store character data in either a fixed-length or a variable-length format using the char(n) or varchar(n) keywords. You can store a maximum of 255 characters in these datatypes. When you create a fixed-length field, you are specifying that this field will always contain n bytes of information. If the data that you entered in the field is less than n, it will be padded with spaces so that it always takes up n bytes. If you try to put more than n bytes of data in the field, it will be truncated. Table 5.3 shows you some examples of entering data into a field declared as Fname char(*)
Example 3
Here is a sample CREATE TABLE statement: CREATE TABLE employees (emp_id tinyint IDENTITY NOT NULL, Fname char(15),Lname char(20) NOT varchar(30),Address2 varchar(NULL,Address1 30),city varchar(30),state char(2),zipcode char(10),start_date datetime)
Deleting tables
Dropping Tables To drop a table using SQL, you should run the DROP TABLE statement. For example, to drop the tblEmployees table, you would run: DROP TABLE tblEmployees
DEFAULT VALUES
There is one more variation of the simple, single row INSERT statement, which is used when you don't want to include a list of column names, but do want SQL Server to use default values where they exist (this includes NULLs and identity values). You can use the keyword DEFAULT in the actual values list, as a way of telling SQL Server that it should determine what value should be used. For example: insert into publishers values(`9950', DEFAULT, DEFAULT,`AK', DEFAULT)
Gary Daniel
Manipulating Data
You can manipulate data in your query results to produce new columns that display computed values, new string values, converted dates, and more. Your query results can be manipulated using arithmetic operators, mathematical functions, string functions, datetime functions, and system functions. You also can use the CONVERT function to convert from one datatype to another for easier data manipulation. Arithmetic Operators You can use arithmetic operators on the following datatypes: int, smallint, tinyint, numeric, decimal, float, real, money, and smallmoney. Table 10.1 shows the arithmetic operators and the datatypes you can use with them.
Mathematical operations
For example, Select 5 + 5 * 5 = 30 (The multiplication is done first.) but Select (5 + 5) * 5 = 50 (The nested expression is evaluated first.) Mathematical operations can also be performed on table columns as shown in the next example
Manipulation of data
Example Select unitprice*quantity as Total cost from products Select 0.25*quantity as 25% of quantity from products Select 0.85* unitprice as price reduced by 15% from products
Examples
Select productName, Supplier FROM products; Select ProductName TO DateofPurchase FROM products; SELECT * FROM products;
Example
To retrieve all product information from the products table where the ProductID is 1005247, we would use the following statement: SQL> SELECT * FROM products WHERE productID=1005247; The above select statement will select all columns BUT one row.
SELECTING PARTICULAR COLUMNS AND ROWS To view a specific set of rows and columns from a table, the syntax will be as follows SELECT <columnName1>, columnName2> FROM <tableName> WHERE <condition>;
Ordering Data
The sort order can either be ASC for ascending or DESC for descending. Example SELECT * FROM Products ORDER BY productId DESC; Example 2 SELECT EmpID, Firstname, Lastname FROM customers ORDER BY EmpID ASC;
Example - deletion
Will delete only those records that meet the specified condition or delete criteria. Example DELETE FROM Suppliers WHERE Town= Mombasa ;
Update example
Example UPDATE Employees SET Sal = Sal + (Sal * 0.40); This example increases the salary of all employees by 40%
Expressions
They are generally used to carry out simple arithmetic and logical operations. Example To retrieve productname, productID and compute 5% of the selling_price, we would use the following statement. SELECT productname, productID, selling_price*(5/100) as increment FROM Products;
Example -expressions
example 3 Select sal as "Old Salary",(sal*0.40) as "Increment(40%)", sal+(sal*0.40) as "New Pay" From Emp
LOGICAL OPERATORS
The AND Operator It instructs the sql engine to display the result only when all the conditions specified using the AND operator are satisfied. Example SELECT Ename, Sal, Job FROM Emp WHERE sal>1400 AND sal <2900;
The OR operator
Sql will process all rows in a table and display the result when one of the conditions specified in the OR operator are satisfied. Example SELECT * FROM Emp WHERE (Comm >0) OR (sal>3000);
Range Searching
The between operator is used to select data that is within a range of values. Example 1
SELECT * FROM products WHERE Unitprice BETWEEN 50 and 200;
Example 2 SELECT ename, job, deptno FROM EMP WHERE sal BETWEEN 1000 AND 2000;
Pattern Matching
The LIKE predicate allows for comparison of one string value with another string value which is not identical. This is achieved using wild-card characters. Two wild-card characters are available for this kind of operation. The percentage sign (%) matches any string The underscore (_) matches any single character
SQL FUNCTIONS
Functions are used in manipulating data items and returning a result. Functions are also capable of accepting user-supplied variables or constants and operating on them. Such variables or constants are called arguments. Any number of arguments can be passed to a function in the following format Function_name(argument1, argument2, )
Results Average of the values in the numeric expression, either all or distinct Number of selected rows Number of values in the expression, either all or distinct Highest value in the expression Lowest value in the expression Total of the values in the numeric expression, either all or distinct
Classes of functions
Functions can be classified as follows
Group functions Scalar functions
Functions that act on a set of values are called group functions. An example is the SUM function which calculates the total set of numbers. A group function returns a single result row for a group of queried rows. Scalar functions act on only one value at a time. For example, LENGTH is a function that calculates the length of one particular string value. A single row function returns one result for every row of a queried table or view.
Result Converts to lowercase Returns data without leading blanks Repeats char_expr integer_expr number of times Returns the reverse of char_expr Returns the character string starting integer_expr characters from the right Returns data without trailing blanks Returns a four-digit (SOUNDEX) code to evaluate the similarity of two character strings Returns a string of repeated spaces equal to
integer_expr
Converts to uppercase
Result
71 abcde 2 CDE EDCBA
SELECT ASCII(`G') SELECT LOWER(`ABCDE') SELECT PATHINDEX(`%BC%','ABCDE') SELECT RIGHT(`ABCDE',3) SELECT REVERSE(`ABCDE')
Date functions
Function
DATEADD(datepart, . number, date) DATEDIFF(datepart, date1, date2) DATENAME(datepart, date)
DATEPART(datepart, date)
GETDATE ()
esults Adds the nu be o dateparts to the date Speci ies the nu be o datepart s bet een t o dates Retu ns the AS II value fo the specified datepart fo the date listed Retu ns an intege value fo the specified datepart fo the date listed Specifies the cu ent date and ti e in inte nal fo at
Function
SELECT GETDATE() SELECT DATEADD(mm, 6, `1/1/97') SELECT DATEADD(mm -5, `10/6/97')
Results
Apr 29, 1997 2:10AM Jul 1, 1997 2:10AM May 6, 1997 2:10AM
Example compute by
SELECT type, ytd_sales FROM titles ORDER BY type COMPUTE SUM(ytd_sales) BY type
SELECT type, ytd_sales FROM titles ORDER BY type COMPUTE SUM(ytd_sales)
type -----------business business business business sum ========= 30788 type -----------mod_cook mod_cook sum ========= 24278 type -----------popular_comp popular_comp popular_comp sum ========= 12875 type --------psychology psychology psychology psychology psychology
BY
type
Aggregate functions
Here are a few examples using the aggregate functions. SELECT COUNT(*)FROM employees result----- 43(1 row(s) affected) ANALYSIS: This query returned a count of the total number of rows in table employee. SELECT MAX(ytd_sales)FROM titles result-----22246(1 row(s) affected)
User-defined integrity
user-defined constraints are created by programmers to enforce certain business rules. For example, the rule that the lowest paid employee should earn Ksh. 4,600/= can be enforced by a user-defined constraint. Business rules that are enforced on data being stored are called constraints.
constraints
They are simply tools used in implementing integrity rules Examples of constraints are
Primary key constraint Composite key Foreign key Check constraint Unique constraint Default constraint
Primary key
A primary key is one or more columns in a table used to uniquely identify each row in the table. A primary key column has special attributes:
The column can not be left blank data held across the column must be UNIQUE. A multicolumn primary key is called a composite key.
DROPPING CONSTRAINTS
A constraint can be eliminated or removed using the DROP CONSTRAINT statement. Example 1 ALTER TABLE Products DROP PRIMARY KEY; ALTER TABLE Orders DROP CONSTRAINT Order_key; A constraint can either be dropped by referring to it using its name or by using its type.
TABLE JOINS
Sometimes it is necessary to work with multiple tables as though they were a single entity. A single SQL statement can then manipulate data from all tables. Joins are used to achieve this. Tables are joined on columns that have the same data type and data width. Joins enable retrieving data from two tables using a single SQL construct
Joins - example
We can join the two tables emp and dept on the common field deptno using the following SQL statements. SELECT ename, job, sal, dname, loc FROM emp, dept WHERE emp.deptno =dept.deptno ORDER BY sal DESC;
Types of joins
There are three types of table joins
Inner joins Cross joins Outer joins Outer joins are further divided into three groups Left outer join Right outer join Full outer join
Inner joins
Inner joins produce information where matching information is found in both tables. The most common types of inner joins are equijoins and natural joins. Example SELECT * FROM publishers inner join pub_info On publishers.pub_id = pub_info.pub_id
The two tables joined are publishers and pub_info
Cross joins
Cross or unrestricted joins return a combination of all rows of all tables in the join as the result set. A cross or unrestricted join is created not by using the WHERE clause in SQL Server. Example SELECT titles.title, titleauthor.au_id FROM titles CROSS JOIN titleauthor
Outer joins
LEFT OUTER JOIN
Includes all rows from the first table and only the matching rows in the second table.
THE END
ASSIGNMENT
.