An Introduction to PostgreSQL

MySQL is much more commonly provided by web hosts. PostgreSQL is a much more mature product. Apparently, MySQL is fast when concurrent access levels are low, and when there are many more reads than writes. On the other hand, it exhibits low scalability with increasing loads and write/read ratios.

PostgreSQL is relatively slow at low concurrency levels, but scales well with increasing load levels, while providing enough isolation between concurrent accesses to avoid slowdowns at high write/read ratios. It goes on to link to a number of performance comparisons because these things are very sensitive to conditions.

So if your decision factor is, “which is faster?” Then the answer is “it depends on the usage”. If it really matters, test your application against both.”

And if you really, really care, you get in two DBAs (one who specializes in each database) and get them to tune the crap out of the databases, and then choose. It’s astonishing how expensive good DBAs are, and they are worth every cent.

When it matters.

Which it probably doesn’t, so just pick whichever database you like the sound of and go with it; better performance can be bought with more RAM and CPU, and more appropriate database design, and clever stored procedure tricks and so on – and all of that is cheaper and easier for random-website-X than agonizing over which to pick, MySQL or PostgreSQL, and specialist tuning from expensive DBAs.

PostgreSQL database is Open Source product and available without cost. Postgres, developed originally in the UC Berkeley Computer Science Department, pioneered many of the object-relational concepts now becoming available in some commercial databases.

It provides SQL92/SQL99 language support, transactions, referential integrity, stored procedures and type extensibility.

PostgreSQL is an open-source descendant of this original Berkeley code.

Postgres Pros:

  • Transactions

  • Foreign keys ( via refint )

  • Triggers

  • Subselects

  • Views ( mostly )

  • User-defined datatypes

  • User-defined functions in a variety of languages: sql, c, pl/pgsql, pl/tcl

  • Sequences

  • Proper date handling

PostgreSQL feels quite a bit like Oracle. There is no SHOW TABLES, it’s \dt (IIRC). To quit it’s not QUIT or EXIT, it’s \q.

PostgreSQL didn’t have built in replication until recently.

Postgres doesn’t support ‘UPDATE a,b SET’ syntax. This would need to be translated into:

UPDATE a SET a.id=b.id FROM b WHERE a.f2 = b.f2; to work on Postgres.

Postgres does not provide a way to order columns inside the db.

Altering columns:

ALTER TABLE a ALTER COLUMN b TYPE integer;

ALTER TABLE a ALTER COLUMN b SET NOT NULL;

Postgres has no auto_increment option. Instead, use the type ‘serial’ For example:

CREATE TABLE a (

b INTEGER PRIMARY KEY NOT NULL AUTO_INCREMENT

);

would become

CREATE TABLE a (

b SERIAL PRIMARY KEY

);

plain INDEX’s cannot be added during table creation, Instead, you must issue a second query:

CREATE INDEX indexname ON tablename(columnname);

the syntax for defining constraints (such as UNIQUE or FOREIGN KEY) varies between the two databases.

For example, in your table definition if you had:

UNIQUE INDEX a1 (f1, f2) this would be changed to:

CONSTRAINT a1 UNIQUE (f1, f2) to be compatible with Postgres. Note that Postgres creates indices by default for

UNIQUE and FOREIGN KEY constraints.

There are many data types that do not exist in Postgres that you may be used to using in MySQL.

These include: blob, tinyint, integer unsigned

http://www.postgresql.org/docs/9.0/static/

Source: Codewebber

Learn About MySQL Stored Procedures

MySql 5 introduced the concept of stored procedure functionality. If you have already worked on other DBMS (Database management System) or Mysql,  you might be familiar with the concept of stored procedure. We will learn more about it in detail here.

What is mysql stored procedure?

Stored procedure is a set of SQL codes stored in a database server which can be invoked by a program, trigger or stored procedure itself.

Stored procedure is a way to execute tasks/business logic directly on your database server. Generic tasks can be performed  which are dependent on database table data.

So rather to go multiple time on database to fetch data into your program and perform your business logic stored procedure give some generic way of coding for your business logic and take data return or you can save your processed data into your database.

Let us take an example

A loan officer wants to change the floating interest levied for a customer’s loan account.

What is your normal course of action? (using your program?) From the database you will fetch capital, rate of interest, duration and calculate interest.  You will go back to the database and save data. In this case we enter the database twice. But, if we use a stored procedure we just need to write this operation within our stored procedure and call it through the program one time. You can fetch capital, rate of interest and duration from the database and save data after processing.  We interrupt the database server only one time. Thanks to the stored procedure, conservation of server resources – check!

Advantages of Mysql Stored Procedure:

Multiple applications running in different environments sharing a database.

Business logic which is independent of programming language.

When security is a main concern use of stored procedure is vital. By doing your operation through the database you can log all performed actions.

Stored procedure does not give direct table access which is one more way to secure data and transactions.

Stored procedure increases performance of your application. When a stored procedure is created and compiled, it never goes to parser, directly fetch the record and execute. Whereas normal SQL query fired on database server get parsed every time so using stored procedure you can save parsing time.

If your application is big or your database server is on a remote system,  using stored procedure can decrease traffic between your database server and application server.

Since stored procedure is written in your database server and application calls it separately, the degree of reusability increase because despite going in much detail you can call stored procedure to perform your action.

Disadvantages of using stored procedure :

Following are the situations where in we should avoid using mysql store procedure.

Sometimes use of stored procedure is a bit risky. Stored procedure follow “define one use many time” philosophy. Doing change in stored procedure directly affect your data so it should always be used very carefully. Stored procedure is a set of sql commands that forms a logic. This makes it very hard to debug.

Managing stored procedure is a little difficult because it does not have any object oriented paradigm.

Since stored procedure has its own advantages and disadvantages, before choosing the option of using stored procedure we should be very careful and decide whether we should use stored procedure or not.

Example

As we have discussed earlier mysql stored procedures are simple SQL statements like normal query but  difference is that query never saved and when you will run stored procedure it will be saved in your RDBMS system.

Let us create a simple stored procedure which will select one string.

mysql > create procedure helloworld() Select ‘hello test’;

Query OK, 0 rows affected (0.00 sec)

To call this procedure you need to run the following mysql query

mysql > CALL helloworld();

Now this query will run select ‘hello test’.

This is simple.

Let us experiment with something more complex.

Mysql stored procedure never return value directly. Either you need to specify output parameter in your stored procedure or you have to put select statement inside the procedure which will fill data in your resource.

Writing a mysql procedure involves 3 steps

  1. Definition of the procedure – Create procedure syntax with the name
  2. Definition of the input parameter – There are three types of parameters you can define. ‘in’ parameter, ‘out’ parameter and ‘inout’ parameter.

Using ‘in’ parameter you can define inputs of the stored procedure,

‘out’ parameter specifies the output parameter.

‘inout’  defines shared parameter, it can also be used either as input parameter or output parameter.

  1. Body of the procedure:- Normally we write within the BEGIN and END tag.

Let us create a simple stored procedure:

DELIMITER $$

CREATE

PROCEDURE `test`(IN capital DOUBLE , IN rate INT , IN duration INT , OUT interest DOUBLE)

BEGIN

SET interest = (capital * rate * duration)/100;

INSERT INTO `administrators`(`interest`) VALUES(interest);

END$$

DELIMITER ;

The procedure called  test  which takes inputs as capital , rate, duration and calculates interest and returns interest in output variable and interest into database.

Let us run this procedure.

mysql > call test(100 , 7 , 3 , @primary_interest);

mysql > select @primary_interest;

Now @primary_interest will give you the interest calculated by the stored procedure.

You can use input parameter input in query written within stored procedure.

For example:

DELIMITER $$

CREATE

PROCEDURE `restaurant`.`another_test`(IN restaurant_name VARCHAR(255))

BEGIN

SELECT * FROM `restaurants` WHERE `restaurants`.`name` = restaurant_name;

END$$

DELIMITER ;

As we discussed earlier, in mysql you can put all your database based business operations. Writing a mysql stored procedure is almost similar to writing any high level program in any language.  All you have to learn is variable declaration, conditional operators and Mysql Cursor to write a mysql stored procedure program.

Variable Declaration and operation on variable in stored procedure:

Like other languages in mysql stored procedure you can declare variables too. You should declare the variable at the beginning of the code/program. Which means right after the BEGIN tag.

You can declare variable in mysql programming like this:

DECLARE i INT(3)

DECLARE j INT(9) DEFAULT 6;

In mysql we use DECLARE tag to declare the variable. You have to specify the datatype of the variable to declare the variable. I recommend to specify size of the variable if it is required like int(4), For some of the variables you can not declare the variable without size like varchar.

Scope of the variable in mysql is limited to END tag. If you have declared the variable in stored procedure then after END tag variable will be lost. You can initialize the variable after declaration like this:-

DECLARE i INT(3);

SET i = 10;

In mysql you can take value in the variable from the query also from the help of INTO keyword. Example:

DECLARE student_name VARCHAR(23);

SELECT student.name INTO student_name FROM student_table.

Condition statement in Mysql programming:

Condition statement will give you power to execute code on the basis of the same value.  Similar to any high level programming language, you can add conditional statements in mysql stored procedure.

Example:

DECLARE count_student INT(5) default 0;

SELECT count(*) INTO count_student FROM student_table;

IF count_student > 5 THEN

SELECT * FROM student_table;

ELSE

SELECT ‘Very less student’;

END IF;

For every IF statement in Mysql you have to specify END IF statement. In mysql you can also use ELSEIF for recursive statements. You can also use switch case based conditional statement in mysql, style of writing switch is a little different.

Example:

CASE

WHEN i >2 THEN

SELECT ‘it is two’;

WHEN i  < 2 THEN

Select ‘it is less then 2′;

ELSE

SELECT ‘no eyse’;

END CASE;

Every CASE will be closed with END CASE, Like a any program we have default tag with name ELSE.

Iteration control(Loop control) in mysql: In mysql you can use loop also as you do in your programming language. Here you can implement loop using WHILE , REPEAT and LOOP Tag.

Source: CodeWebber