Friday, 22 July 2011

SQL Predicates


sql - predicates

SQL Predicates are found on the tail end of clauses, functions, and SQL expression inside of existing query statements. We've actually already covered a few SQL predicates already and most on this list should be familiar to you.

SQL Predicates:

AND
OR
LIKE
BETWEEN
AS
TOP(LIMIT)

sql - top

SQL Top is used to limit the number of results returned by a query. The top command is generally followed by a number that indicates the maximum number of results to return for a given query.

SQL Code:

use mydatabase;
 
SELECT TOP 2 *
FROM orders

SQL Results:

id
customer
day_of_order
product
quantity
1
Tizag
2008-08-01 00:00:00.000
Pen
4
2
Tizag
2008-08-01 00:00:00.000
Stapler
3

SQL Commands


sql - commands

SQL commands are lines of SQL code that ask the SQL application to perform simple tasks against with data inside of a database. Often we refer to commands as query statements or scripts; all of these terms are synonymous. Most of the commands and statements you will see in this tutorial are fairly standard and will work across multiple database applications despite the fact this tutorial is aimed for the SQL Server Express user.

SQL commands are declarative sentences or 'orders' executed against a SQL database. The typical command is comprised of several different components including clauses, functions, expressions, or objects but the only required components are a SQL Clause and the data object (a database or a database table).

sql - clauses

A SQL clause is the word or phrase that begins each SQL command statement and the single most important component to any SQL command. Looking at the clause of any given SQL command usually tells the SQL programmer what that particular command intends to do to the database. For instance, a SELECT command begins with the SELECT clause and any level of SQL programmer will recognize the SELECT query as a command selecting data from the database.
Other SQL clauses include:
  • Add
  • Drop
  • Create
  • Insert
  • Select
  • Update
  • Replace
  • Delete

sql - sample commands

SQL Code:

SELECT getdate(); -- Selects the current (server) date and time.
 
CREATE DATABASE MyDatabase; -- Creates a database named Mydatabase;
 
INSERT INTO orders 

 -- Inserts data into a database table
VALUES('A+Maintenance','8/16/08','Hanging Files',12);

SQL Platforms


sql - platforms applications


There are many, many different SQL applications in existence. A handful of platforms are available for free and are the preferred choice among individuals and small businesses. Other SQL platforms are designed with enterprise level customers in mind and are much more expensive


.

SQL Applications:

  • IBM's DB2
  • MySQL
  • PostgreSQL
  • Oracle
  • Microsoft's SQL Server



sql - mysql and postgresql


MySQL and PostgreSQL are open source database programs rich in functionality and flexibility. They are often the choice of web developers and small businesses simply because they are light-weight and are offered at the right price: free. Most open source software will also work across multiple different operating systems, which is yet another benefit to small businesses.


sql - sql server

Microsoft's SQL Server is steadily on the rise in the commercial world gaining popularity slowly. This platform is only available to Windows users at this time, but offers its users very user-friendly interface that is great for beginning SQL developers. A free trial version can be downloaded at the Microsoft website.


sql - db2 and oracle

By far the selection of choice for large corporations is either Oracle or DB2. Companies that have large ties to IBM stick to their DB2 software whereas others have made the switch to Oracle. These systems run on personal computers as well as large corporate mainframes and are ideal for processing vast amounts of data at the enterprise level.

SQL History


sql - historical information


In the '60's database software required the use of complex mainframe machines that were difficult to maintain and run. Information technologists worked around the clock monitoring, updating, and manually uncorrupting these machines.
Each mainframe ran different software from different manufacturers. IBM pulled ahead in software development internationally with efforts of software aimed at database management. The problem was that each mainframe ran a different type of "language".
Enter SQL, the new standard for any database program: Structured Query Language. SQL bridged the barriers between mainframes and allowed large corporations to network their efforts. SQL was introduced in the 1970's and quickly gained international popularity. SQL allows a programmer to tell a program exactly what data to retrieve and how to display it.


sql - under development


Software at the time was still underdeveloped and several continuous problems plagued database storage. Transactions happening at the same time were often combined, mixed together, or even lost altogether. For instance, say two individuals made a deposit at exactly the same time from two different locations. The software was unable to cope with this, and their bank transactions were completely switched. Suzy deposited $10,000 while Joe withdrew $15. Because of the faulty software Joe's withdrawal was posted on Suzy's account and Suzy's deposit was posted to Joe's account.
Along came Relational Database Management Systems (RDBMS). This software is still being used and is quite powerful. Relational databases allow developers to build relationships between databases and tables. This provides tremendous opportunities for data management and is still the favorite software used today. MySQL, SQL Server, DB2, and Oracle are all RDBMSs, and each have a substantial hold in the market share to this day.

SQL Expressions


sql - expressions

SQL Expressions are the pieces of a SQL query that compare values against other values or perform arithmetic calculations. Expressions can be found inside of any SQL command usually in the form of a conditional statement. In the SQL world, conditional statements and expressions test or compare values against other values.

 

 

 

sql - boolean expressions

Boolean expressions return rows (results) when a single value is matched.

SQL Boolean Expression:

USE mydatabase;
 
SELECT * FROM orders WHERE id = '1';

SQL Results:

id
customer
day_of_order
product
quantity
1
Tizag
2008-08-01 00:00:00.000
Pen
4

sql - numeric expression

Numeric Expressions return a single numeric value instead of an entire row and usually perform calculations.

SQL Code:

USE mydatabase;
 
SELECT 15 + 4;

SQL Code:

USE mydatabase;
 
SELECT (15 / 5) * 10;

SQL Code:

USE mydatabase;
 
SELECT ((5+5) * (5+5));
Each of the examples above returns a numeric value which is displayed inside the results pane of the SQL application. SQL also offers several built-in functions to perform what is known as aggregate data calculations against a table or a specific table column.
  • AVG() -- Returns the average value of a stated column.
  • COUNT(*) -- Returns a count of the number of rows of table.
  • SUM() -- Returns the sum of a given column.
Using one of the following functions also returns a numeric value:

SQL Code:

USE mydatabase;
 
SELECT COUNT(*) AS "Number of Orders"
FROM orders;

SQL Code:

USE mydatabase;
 
SELECT SUM(quantity)AS "Total Number of Items Purchased"
FROM orders;

SQL Code:

USE mydatabase;
 
SELECT AVG(quantity) AS "Average Number of Items Purchased"
FROM orders;
We can also combine these queries into a single query so that the results are viewable all at once.

SQL Code:

USE mydatabase;
 
SELECT COUNT(*) AS "Number of Orders",
SUM(quantity)AS "Total Number of Items Purchased",
AVG(quantity)AS "Average Number of Items Purchased"
FROM orders;

sql - date expressions

As the name suggests, Date Expressions return date/time values.
  • GetDate() -- Returns the current date/time.
  • Current_Timestamp -- Returns the current timestamp.
Date expressions as you may have guessed, return date values. We will be taking a closer look at date expressions later on in this tutorial. Stay tuned.

SQL Code:

USE mydatabase;
 
SELECT Current_Timestamp;
SELECT  GETDATE();

SQL Tuning or SQL Optimization


SQL Tuning or SQL Optimization

Sql Statements are used to retrieve data from the database. We can get same results by writing different sql queries. But use of the best query is important when performance is considered. So you need to sql query tuning based on the requirement. Here is the list of queries which we use reqularly and how these sql queries can be optimized for better performance.

 

 

 

SQL Tuning/SQL Optimization Techniques:

1) The sql query becomes faster if you use the actual columns names in SELECT statement instead of than '*'.
For Example: Write the query as
SELECT id, first_name, last_name, age, subject FROM student_details;
Instead of:
SELECT * FROM student_details;

2) HAVING clause is used to filter the rows after all the rows are selected. It is just like a filter. Do not use HAVING clause for any other purposes. 
For Example: Write the query as
SELECT subject, count(subject) 
FROM student_details 
WHERE subject != 'Science' 
AND subject != 'Maths' 
GROUP BY subject;
Instead of:
SELECT subject, count(subject) 
FROM student_details 
GROUP BY subject 
HAVING subject!= 'Vancouver' AND subject!= 'Toronto';

3) Sometimes you may have more than one subqueries in your main query. Try to minimize the number of subquery block in your query. 
For Example: Write the query as
SELECT name 
FROM employee 
WHERE (salary, age ) = (SELECT MAX (salary), MAX (age) 
FROM employee_details) 
AND dept = 'Electronics'; 
Instead of:
SELECT name 
FROM employee
WHERE salary = (SELECT MAX(salary) FROM employee_details) 
AND age = (SELECT MAX(age) FROM employee_details) 
AND emp_dept = 'Electronics';

4) Use operator EXISTS, IN and table joins appropriately in your query. 
a) Usually IN has the slowest performance. 
b) IN is efficient when most of the filter criteria is in the sub-query. 
c) EXISTS is efficient when most of the filter criteria is in the main query.
For Example: Write the query as
Select * from product p 
where EXISTS (select * from order_items o 
where o.product_id = p.product_id)
Instead of:
Select * from product p 
where product_id IN 
(select product_id from order_items

5) Use EXISTS instead of DISTINCT when using joins which involves tables having one-to-many relationship. 
For Example: Write the query as
SELECT d.dept_id, d.dept 
FROM dept d 
WHERE EXISTS ( SELECT 'X' FROM employee e WHERE e.dept = d.dept);
Instead of:
SELECT DISTINCT d.dept_id, d.dept 
FROM dept d,employee e 
WHERE e.dept = e.dept;

6) Try to use UNION ALL in place of UNION. 
For Example: Write the query as
SELECT id, first_name 
FROM student_details_class10 
UNION ALL 
SELECT id, first_name 
FROM sports_team;
Instead of:
SELECT id, first_name, subject 
FROM student_details_class10 
UNION 
SELECT id, first_name 
FROM sports_team;

7) Be careful while using conditions in WHERE clause. 
For Example: Write the query as
SELECT id, first_name, age FROM student_details WHERE age > 10;
Instead of:
SELECT id, first_name, age FROM student_details WHERE age != 10;
Write the query as
SELECT id, first_name, age 
FROM student_details 
WHERE first_name LIKE 'Chan%';
Instead of:
SELECT id, first_name, age 
FROM student_details 
WHERE SUBSTR(first_name,1,3) = 'Cha';
Write the query as
SELECT id, first_name, age 
FROM student_details 
WHERE first_name LIKE NVL ( :name, '%');
Instead of:
SELECT id, first_name, age 
FROM student_details 
WHERE first_name = NVL ( :name, first_name);
Write the query as
SELECT product_id, product_name 
FROM product 
WHERE unit_price BETWEEN MAX(unit_price) and MIN(unit_price)
Instead of:
SELECT product_id, product_name 
FROM product 
WHERE unit_price >= MAX(unit_price) 
and unit_price <= MIN(unit_price)
Write the query as
SELECT id, name, salary 
FROM employee 
WHERE dept = 'Electronics' 
AND location = 'Bangalore';
Instead of:
SELECT id, name, salary 
FROM employee 
WHERE dept || location= 'ElectronicsBangalore';
Use non-column expression on one side of the query because it will be processed earlier.
Write the query as
SELECT id, name, salary 
FROM employee 
WHERE salary < 25000;
Instead of:
SELECT id, name, salary 
FROM employee 
WHERE salary + 10000 < 35000;
Write the query as
SELECT id, first_name, age 
FROM student_details 
WHERE age > 10;
Instead of:
SELECT id, first_name, age 
FROM student_details 
WHERE age NOT = 10;
8) Use DECODE to avoid the scanning of same rows or joining the same table repetitively. DECODE can also be made used in place of GROUP BY or ORDER BY clause. 
For Example: Write the query as
SELECT id FROM employee 
WHERE name LIKE 'Ramesh%' 
and location = 'Bangalore';
Instead of:
SELECT DECODE(location,'Bangalore',id,NULL) id FROM employee 
WHERE name LIKE 'Ramesh%';
9) To store large binary objects, first place them in the file system and add the file path in the database.
10) To write queries which provide efficient performance follow the general SQL standard rules.
a) Use single case for all SQL verbs
b) Begin all SQL verbs on a new line
c) Separate all words with a single space 
d) Right or left aligning verbs within the initial SQL verb

Related Posts Plugin for WordPress, Blogger...