Thursday 20 December 2012

More Code, More Problems



About a year ago, I wrote out some principles for web programming in PHP. I called it the MicroPHP Manifesto. The thing is, what I talked about wasn’t really specific to PHP. So, I’ve decided to explore the concepts again in the context of the other languages I work with.
What follows are some principles I try to keep in mind.

Learn languages, not frameworks

I like PHP, Python, and JavaScript, and I like making things in PHP, Python, and JavaScript. I’m not a Symfony developer, or a Django developer, or a jQuery developer.

I think this is an important distinction. It’s entirely possible to be a jQuery developer, but not a JavaScript developer. It’s possible to be a Django developer, but not a Python developer. Those are all certainly valuable and useful tools, but if I only know how to use one framework, my options for using the right tool for the job get pretty limited, and in my experience, large, full-stack frameworks are often not the right tool, particularly if flexibilty and performance are major concerns.

My experience has been that I become a better, more versatile developer when I focus on learning a language first. Diving head-first into a full-stack, complex framework when I’m starting out has allowed me to build finished products more quickly, but it also becomes a detriment when I need solutions outside of the framework’s scope. I often end up with a “plug and pray” approach to development, where I find a library or plugin that sounds like it will meet my needs, cross my fingers, and shove it in. That might get my app launched faster, but it makes stuff a lot harder down the road.

Additionally, learning a full-stack framework can be as complex as learning a new programming language. They often have complex architectures and nomenclatures — parts that don’t carry over to other frameworks and tools. I’d rather spend my time learning more about the language itself, knowing the skills that I learn will apply to anything I build in the language, no matter which libraries I use.
Build small things

Small units of code are good. The smaller it is, the easier it is to understand. It’s harder to screw it up — and I screw stuff up a lot, so limiting that is really important.
So, I strive to build small modules of code with a single purpose, or at most a few closely-related purposes. They should be self-contained pieces that solve individual problems. These pieces then work together to solve larger, more complex problems.

With simpler, modular code, fixing bugs is easier, because I can look at an individual piece and see clearly what it’s doing. And, if the modules are self-contained, testing my code is much easier.
Less code is better than more

To paraphrase Biggie Smalls, “more code, more problems.”
I want to manage less code. Larger codebases get harder to manage. Searching across the codebase takes longer. Navigating through complex file structures takes longer. Tracing execution through dozens of files is hard. Keeping it all straight in my brain gets challenging.
Bigger libraries and longer code seem to overflow my brain buffer. I have trouble keeping track of code flow when the source gets too long, or when execution is jumping between several source files, and visual noise really affects me, too. This is why I love syntax coloring so much, and consistent whitespace really helps. I use the code folding feature in my editor a lot, just to hide things, so I can focus better on the task at hand.
I also want to support less code. I’m responsible for all of the code that my app uses, not just the stuff I wrote — every single line of it. This means that bugs and security holes are my responsibility. How often do we see a WordPress or Drupal plugin get abandoned after a year or so? Am I sure I want to use a piece of code I don’t really understand, when a year down the road I may have to fix an exploit in it?
This is not to say that I would never use code that I didn’t write — I’d be hard-pressed to get much done that way, and frankly there are better programmers out there than me — but every line of code in my app matters, so I need to justify each one.

Create and use simple, readable code
I want code that is easy to understand. Understanding things quickly means getting stuff done faster. My time to productivity is shortened. My time to fix bugs is shortened.

I also want code that is easy to verify. My code should be testable, whether or not I get around to actually writing those tests, and I’ve consistently found that simpler, more modular code is more testable.

Readability should be a feature. Code should be simple and terse, but clear. Value clarity over cleverness. When I’m writing code, I try to consider how quickly another developer will be able to understand it at first glance. Alternately, will I be able to understand it when I come back to it in two months? The less time I waste trying to figure out how things work, the more there will be for getting things done.

I’d be lying if I said I always follow these principles. Sometimes, I just get lazy. Sometimes, time constraints mean I write hacky, complex code as fast as possible to get something working, or I pull in a library without reviewing it carefully, and hope it works. In the short term, writing simple, clear code is harder — it requires more discipline and frequent reassessment of technique. Particularly with time-sensitive projects, it’s hard to ever feel like I ever am entirely happy with the results.

But, when I make the time and put the effort in, it always pays off down the road — not just for myself, but for the other members of my team and people who use the code I’ve written, and that’s a really good feeling.

SOURCE LINK::http://webadvent.org/2012/more-code-more-problems-by-ed-finkler

Internal SQL Functions Index


1. Functions Introduction

Functions may be used within all expressions except aggregate functions that may only be used within the SELECT .... FROM clause.


2. Mathematical Functions

Returns the absolute value of a number.
Examples:
     SELECT ABS(-0.94)
==>  0.94
     SELECT ABS(9 - 200)
==>  191
SIGN(number)
Returns 1 if the number is positive, -1 if the number is negative and 0 if the number is zero.
Examples:
     SELECT SIGN(40)
==>  1
     SELECT SIGN(-40)
==>  -1
     SELECT SIGN(40 - 40)
==>  0
MOD(number1, number2)
Returns the modulo of number1 and number2 (equivalent to {number1 % number2} in Java).
Examples:
     SELECT MOD(15, 5)
==>  0
     SELECT MOD(33, 10)
==>  3
     SELECT ROUND(552 / 10), MOD(552, 10)
==>  55, 2
ROUND(number, decimal_places)
ROUND(number)
Rounds the number to 'n' decimal places. When no 'decimal_places' argument is provided the number is rounded to the nearest whole number.
This will round up if the fraction to the right is >= .5 otherwise it rounds down. This uses the {BigDecimal.setScale(decimal_places, BigDecimal.ROUND_HALF_UP)} method for rounding.
Examples:
     SELECT ROUND((943 * 13) / 99, 3)
==>  123.828
     SELECT ROUND((943 * 13) / 99, 2)
==>  123.83
     SELECT ROUND((943 * 13) / 99)
==>  124
POW(number1, number2)
Raises number1 to the power of number2.
Examples:
     SELECT POW(9, 6)
==>  531441
     SELECT POW(2, 32)
==>  4294967296
     SELECT POW(2, 64)
==>  18446744073709551616
     SELECT POW(2, -3)
==>  0.125
SQRT(number)
Finds the square root of the number argument.
Examples:
     SELECT SQRT(65536)
==>  256
     SELECT SQRT(-1)
==>  NULL
LEAST(val1, val2, ...)
This function accepts any number of arguments and returns the value that represents the least value of the set.
Examples:
     SELECT LEAST(4)
==>  4
     SELECT LEAST(90, 9.125, 3, 75)
==>  3
     SELECT LEAST('H', 'Z', 'B')
==>  B
     SELECT LEAST(10 / 3, 10 * 3,
                  POW(10, 3), MOD(10, 3))
==>  1
GREATEST(val1, val2, ...)
This function accepts any number of arguments and returns the value that represents the greatest value of the set.
Examples:
     SELECT GREATEST(4)
==>  4
     SELECT GREATEST(90, 9.125, 3, 75)
==>  90
     SELECT GREATEST('H', 'Z', 'B')
==>  Z
     SELECT GREATEST(10 / 3, 10 * 3,
                     POW(10, 3), MOD(10, 3))
==>  1000


3. String Functions

LOWER(str)
Returns a lower case version of the string literal argument.
Examples:
     SELECT LOWER('THis is sOME TEXT')
==>  this is some text
UPPER(str)
Returns an upper case version of the string literal argument.
Examples:
     SELECT UPPER('THis is sOME TEXT')
==>  THIS IS SOME TEXT
CONCAT(str1, str2, ...)
Returns the concatenation of the string arguments. This function can take any number of arguments.
Examples:
     SELECT CONCAT('This i', 's some text', '.')
==>  This is some text.
     SELECT CONCAT('-', 0.95)
==>  -0.95
LENGTH(str)
Returns the number of characters in the string argument.
NOTE: This may additionally be used on BLOB data to return the count of bytes in the BLOB.
Examples:
     SELECT LENGTH('This is some text')
==>  17
     SELECT LENGTH(0.544)
==>  5
     SELECT LENGTH('    Test')
==>  8
TRIM( [ [ LEADING | TRAILING | BOTH ] [ characters ] FROM ] str )
LTRIM(str)
RTRIM(str)
Trims characters from a string argument. The LTRIM and RTRIM form trim whitespace from the left and right of the string respectively.
Examples:
     SELECT TRIM(TRAILING 'a' FROM 'aaabcdaaa')
==>  aaabcd
     SELECT TRIM(LEADING 'a' FROM 'aaabcdaaa')
==>  bcdaaa
     SELECT TRIM('ab' FROM 'ababzzzzab')
==>  zzzz
     SELECT TRIM('  a string message ')
==>  a string message
SUBSTRING(str, start_index)
SUBSTRING(str, start_index, length)
Returns a substring of a string. The SUBSTRING function complies with the SQL specification. The start_index parameter is a value between 1 and the length of the string where 1 includes the first character, 2 includes the second character, etc. The length parameter represents the size of the substring.
Examples:
     SELECT SUBSTRING('Tobias Downer', 8)
==>  Downer
     SELECT SUBSTRING('abcd', 1, 2)
==>  ab
     SELECT SUBSTRING('abcd', 3, 4)
==>  cd
     SELECT SUBSTRING('abcd', 3, 5000)
==>  cd
     SELECT SUBSTRING('abcd', 0, 5000)
==>  abcd
     SELECT SUBSTRING('abcd', 1, 0)
==>  (string of 0 length)


4. Aggregate Functions
Aggregate functions can only operate within a group of a SELECT statement. They are used to compute statistics over a set of records.
COUNT(*)
COUNT(DISTINCT expression_list)
COUNT(column_name)
COUNT(expression)
The * version of this function returns the total number of rows in the group. If a column name is specified it returns the number of non-null values in the group. The 'expression' form of this function evaluates the expression for each row in the group and counts it only if it evaluates to NULL. COUNT(DISTINCT ... ) counts all distinct values of the expression list over the group.
Examples:
     SELECT COUNT(*)
       FROM Orders
     SELECT COUNT(*)
       FROM Orders
   GROUP BY division
     SELECT COUNT(id)
       FROM Orders
   GROUP BY division
     SELECT last_name, COUNT(DISTINCT last_name)
       FROM Customers
   GROUP BY age
SUM(column_name)
SUM(expression)
Calculates the sum of all values in a column/expression over a group. The expression form of this function is evaluated for each row in the group.
Examples:
     SELECT SUM(value) FROM Orders
     SELECT SUM(quantity * value)
       FROM Orders
     SELECT SUM(quantity * value) * 0.75
       FROM Orders
   GROUP BY division
AVG(column_name)
AVG(expression)
Calculates the average of the column/expression over the group. The expression form of this function is evaluated for each row in the group.
Examples:
     SELECT AVG(value) FROM Orders
     SELECT AVG(quantity * value)
       FROM Orders
     SELECT AVG(quantity * value) * 0.75
       FROM Orders
   GROUP BY division
MIN(column_name)
MIN(expression)
Finds the minimum value of a column/expression over a group.
Examples:
     SELECT MIN(value) FROM Orders
     SELECT MIN(quantity * value)
       FROM Orders
     SELECT MIN(quantity * value) * 0.75
       FROM Orders
   GROUP BY division
MAX(column_name)
MAX(expression)
Finds the maximum value of a column/expression over a group.
Examples:
     SELECT MAX(value) FROM Orders
     SELECT MAX(quantity * value)
       FROM Orders
     SELECT MAX(quantity * value) * 0.75
       FROM Orders
   GROUP BY division


5. Security Functions
Functions that provide security information about the session performing the query.
USER()
Returns the current user.
PRIVGROUPS()
Returns a comma deliminated list of priv groups the user belongs to. A user may belong to any number of groups which dictate the tables a user may access.


6. Branch Functions
IF(condition_expr, true_expr, false_expr)
If the first expression (condition_expr) evaluates to true this function returns the result of 'true_expr' otherwise returns the result of 'false_exp'.
Examples:
     SELECT IF(true, 5, 8)
==>  5
     SELECT IF(false, 5, 8)
==>  8
     SELECT IF(NULL, 5, 8)
==>  NULL
     SELECT IF(true, IF(false, 1, 2), 3)
==>  2
     SELECT IF(col1 = 0, 'N/A', col1) FROM MyTable
COALESCE(expr1, expr2, expr3, ....)
Returns the first non null value from the parameters or null if the entire list contains null values.
Examples:
     SELECT COALESCE(NULL, 'a')
==>  a
     SELECT COALESCE(NULL, NULL, NULL)
==>  NULL
     SELECT COALESCE(col1, 'N/A') FROM MyTable


7. Date/Time Functions
DATEOB(date_string)
Parses a string to a Date object that can be used on queries against TIMESTAMP / DATE / TIME columns. DATEOB with no arguments returns the current time of the machine running the database.
Since version 0.92 this function has been deprecated. Use the standard DATE, TIME and TIMESTAMP literals specified in SQL-92 instead.
Examples:
     SELECT DATEOB()
==>  Wed Aug 09 11:49:31 EDT 2000
     SELECT DATEOB('Aug 1, 2000')
==>  Tue Aug 01 00:00:00 EDT 2000
     SELECT number FROM Orders
      WHERE date_made >= DATEOB('Jan 1, 2000')


8. Misc Functions
UNIQUEKEY(table_name)
Returns a unique key for the given table name. This is an atomic operation that is guaranteed to return a unique number each call. It should be used to generate unique identification numbers for records. It is similar to the AUTO_INCREMENT feature of other database systems.
Examples:
     SELECT UNIQUEKEY('Orders')
     INSERT INTO Orders
        ( id, number, division, date_made, quantity,
          value )
       VALUES
        ( UNIQUEKEY('Orders'), CONCAT('Order-', id),
          'Bio Engineering', DATEOB(), 25, 1900.00 )
TONUMBER(expression)
Attempts to cast the expression to a number. If the expression is a boolean then this function will return 1 for true or 0 for false. If the expression is a String then it attempts to parse the string into a number. If the expression is a Date then it returns the date as the number of milliseconds since Jan 1st, 1970.
Examples:
     SELECT TONUMBER(DATEOB('Aug 1, 2000'))
==>  965102400000

SQL


Database

A database consists of one or more tables. A table is identified by its name. A table is made up of columns and rows. Columns contain the column name and data type. Rows contain the records or data for the columns.

Basic SQL

Each record has a unique identifier or primary key. SQL, which stands for Structured Query Language, is used to communicate with a database. Through SQL one can create and delete tables. Here are some commands:
  • CREATE TABLE - creates a new database table
  • ALTER TABLE - alters a database table
  • DROP TABLE - deletes a database table
  • CREATE INDEX - creates an index (search key)
  • DROP INDEX - deletes an index
SQL also has syntax to update, insert, and delete records.
  • SELECT - get data from a database table
  • UPDATE - change data in a database table
  • DELETE - remove data from a database table
  • INSERT INTO - insert new data in a database table

SELECT

The SELECT is used to query the database and retrieve selected data that match the specific criteria that you specify:

SELECT column1 [, column2, ...]
FROM tablename
WHERE condition

The conditional clause can include these operators

  • = Equal
  • > Greater than
  • < Less than
  • >= Greater than or equal
  • <= Less than or equal
  • <> Not equal to
  • LIKE pattern matching operator
SELECT * FROM tablename

returns all the data from the table.

Use single quotes around text values (most database systems will also accept double quotes). Numerical values should not be enclosed in quotes.
LIKE matches a pattern. The wildcard % is used to denote 0 or more characters.
  • 'A%' : matches all strings that start with A
  • '%a' : matches all strings that end with a
  • '%a%' : matches all strings that contain an a

CREATE TABLE

The CREATE TABLE statement is used to create a new table. The format is:

CREATE TABLE tablename
(column1 data type,
column2 data type,
column3 data type); 

  • char(size): Fixed length character string.
  • varchar(size): Variable-length character string. Max size is specified in parenthesis.
  • number(size): Number value with a max number of columns specified in parenthesis
  • date: Date value
  • number(size,d): A number with a maximum number of digits of "size" and a maximum number of "d" digits to the right of the decimal

INSERT VALUES

Once a table has been created data can be inserted using INSERT INTO command.

INSERT INTO tablename
(col1, ... , coln)
VALUES (val1, ... , valn) 

UPDATE

To change the data values in a pre existing table, the UPDATE command can be used.

UPDATE tablename
SET colX = valX [, colY = valY, ...]
WHERE condition 

DELETE

The DELETE command can be used to remove a record(s) from a table.

DELETE FROM tablename
WHERE condition

To delete all the records from a table without deleting the table do

DELETE * FROM tablename

DROP

To remove an entire table from the database use the DROP command.

DROP TABLE tablename 

ORDER BY

ORDER BY clause can order column name in either ascending (ASC) or descending (DESC) order.

ORDER BY col_name ASC

AND / OR

AND and OR can join two or more conditions in a WHERE clause. AND will return data when all the conditions are true. OR will return data when any one of the conditions is true.

IN

IN operator is used when you know the exact value you want to return for at least one of the columns

SELECT * FROM table_name WHERE col_name IN (val1val2, ...)

BETWEEN / AND

The BETWEEN ... AND operator selects a range of data between two values. These values can be numbers, text, or dates.

SELECT * FROM table_name WHERE col_name BETWEEN val1 AND val2

JOIN

There are times when we need to collate data from two or more tables. That is called a join. Tables in a database are related to each other through their keys. We can associate data in various tables without repeating them. For example we could have a table called Customers which could have information about customers like their name, address, phone numbers. We could have another table called Products that has information regarding the products like part number, product name, manufacturer, number in stock, unit price. A third table called Orders could have information regarding what product was ordered, by whom, the date the order was placed, and quantity. Here are the tables:
Customers
Cust_IDFirstNameLastNameAddressPhone
01MickeyMouse123 Gouda St.456-7890
02DonaldDuck325 Eider Ln.786-2365

Products
Part_NoNameManufacturerIn_StockPrice
20-45HammerStanley573.50
21-68ScrewDriverDeVries842.75

Orders
Order_NoPart_NoCust_IDDateQuantity
2005-2721-680231 Oct 20052
2005-3420-450102 Nov 20053

We can obtain information on who has ordered what:

SELECT Customers.FirstName, Customers.LastName, Products.Name
FROM Customers, Products, Orders
WHERE Customers.Cust_ID = Orders.Cust_ID AND Products.Part_No = Orders.Part_No 

We can select data from two tables with INNER JOIN. The INNER JOIN returns all rows from both tables where there is a match. If there are rows in Customers that do not have matches in Orders, those rows will not be listed.
SELECT Customers.FirstName, Customers.LastName, Orders.Date
FROM Customers
INNER JOIN Orders
ON Customers.Cust_ID = Orders.Cust_ID 

The LEFT JOIN returns all the rows from the first table (Customers), even if there are no matches in the second table (Orders). If there are rows in Customers that do not have matches in Orders, those rows also will be listed.
SELECT Customers.FirstName, Customers.LastName, Orders.Date
FROM Customers
LEFT JOIN Orders
ON Customers.Cust_ID = Orders.Cust_ID 

The RIGHT JOIN returns all the rows from the second table (Orders), even if there are no matches in the first table (Customers). If there had been any rows in Orders that did not have matches Customers, those rows also would have been listed.
SELECT Customers.FirstName, Customers.LastName, Orders.Date
FROM Customers
RIGHT JOIN Orders
ON Customers.Cust_ID = Orders.Cust_ID 

ALTER TABLE

With ALTER TABLE you can add or delete columns in an existing table. When you add a column you must specify a data type.
ALTER TABLE table_name
ADD col_name datatype

ALTER TABLE table_name
DROP COLUMN col_name 

UNION

The UNION command is used to select data from two tables very similar to the JOIN command. But the UNION command can be used only with columns having the same datatype. With UNION only distinct values are selected, i.e. if there are common data in the two tables only one instance of that data is returned.

SELECT Name FROM Customers_USA
UNION
SELECT Name FROM Customers_Asia

This will select all the customers from USA and Asia but if there is a name that occurs in both the tables it will return only one such name. To get all the names use UNION ALL instead.

SQL Functions

There are several built-in functins in SQL. The basic function types are:
  • Aggregate Functions: These are functions that operate against a collection of values, but return a single value.
  • Scalar Functions: These functions operate against a single value, and return a single value.
To use a built-in function the syntax is:

SELECT function (col_name) FROM table_name 

GROUP BY

The GROUP BY was added to SQL so that aggregate functions could return a result grouped by column values.

SELECT col_name, function (col_name) FROM table_name GROUP BY col_name 

HAVING keyword was introduced because the WHERE keyword could not be used. HAVING states a condition.

SELECT clo_name, function (col_name) FROM table_name
GROUP BY col_name
HAVING function (col_name) condition value 

CREATE VIEW

A view is a virtual table that is a result of SQL SELECT statement. A view contains fields from one or more real tables in the database. This virtual table can then be queried as if it were a real table.

CREATE VIEW view_name AS
SELECT col_name(s)
FROM table_name
WHERE condition

A view could be used from inside a query, a stored procedure, or from inside another view. You can add functions and joins to a view and present the data you want to the user.

Sample Text

Muthukumar. Powered by Blogger.

About Me

My photo
Hi i am Muthu kumar,software engineer.