πŸŽ‰ New: Top 75 PHP Interview Questions for 2026 β€” Free for all learners

SEO Cheatsheet β€” Learn On-Page, Off-Page, and Technical SEO with Practical Tips

What is SEO (Search Engine Optimization)?

SEO stands for Search Engine Optimization, a set of techniques used to improve your website’s visibility in search engine results pages (SERPs) like Google or Bing.
The goal is simple: attract organic traffic by ranking higher for the right keywords.

It includes three major areas:

  1. On-Page SEO β€” Optimizing content, titles, meta tags, and images.
  2. Off-Page SEO β€” Building backlinks and improving authority.
  3. Technical SEO β€” Improving website speed, structure, and indexing.

On-Page SEO Optimization Guide

ElementBest PracticeExample
Title TagKeep under 60 characters, include keyword at startβ€œSEO Cheatsheet β€” Master Search Optimization Techniques”
Meta Description150–160 characters, keyword-richβ€œLearn on-page, off-page, and technical SEO with this complete cheatsheet.”
Headings (H1–H6)Use one H1 per page; include target keyword<h1>SEO Cheatsheet for Beginners</h1>
URL StructureShort, lowercase, hyphen-separated/seo-cheatsheet
Keyword Density1–2% of total textUse β€œSEO Cheatsheet” naturally
Image Alt TextDescribe images with keywordsalt="SEO optimization process"
Internal LinksLink related pages like PHP, HTML, or PythonHTML Cheat Sheet

Keyword Research and Planning

Keyword research helps you understand what users are searching for.
Use tools like Google Keyword Planner, Ahrefs, or Ubersuggest to find:

βœ… High-volume keywords
βœ… Low competition terms
βœ… Long-tail keywords for conversions

TypeExampleSearch Intent
Short-tailSEO tipsInformational
Long-tailbest on-page seo optimization guideEducational
Transactionalhire seo expert onlineCommercial
NavigationalGoogle Search Console loginNavigational

Technical SEO Cheatsheet

Technical ElementBest Practice
Website SpeedLoad under 3 seconds (use PageSpeed Insights)
Mobile ResponsivenessTest with Google Mobile-Friendly Test
HTTPS SecurityUse SSL Certificate
XML SitemapSubmit via Google Search Console
Robots.txtBlock non-essential pages
Canonical TagsPrevent duplicate content
Structured DataUse JSON-LD schema markup
Core Web VitalsOptimize LCP, CLS, and FID metrics

Off-Page SEO Strategies

Off-page SEO improves domain authority (DA) and trustworthiness.
Key strategies include:

βœ… Building High-Quality Backlinks from relevant websites
βœ… Guest Posting on authority blogs
βœ… Social Media Promotion for content visibility
βœ… Forum & Community Engagement (e.g., Reddit, Quora)
βœ… Local SEO Citations for Google My Business

Backlink SourceTypeSEO Value
Guest PostsDoFollowHigh
Social Media SharesNoFollowMedium
Directory ListingsMixedMedium
Blog CommentsNoFollowLow
Press ReleasesDoFollowHigh

Content SEO Best Practices

  • Write unique, keyword-rich, long-form articles (over 1000 words).
  • Use LSI keywords and natural synonyms.
  • Optimize first 100 words with target keyword.
  • Add relevant media (images, infographics, code samples).
  • Include FAQs for Google’s featured snippets.
  • Keep a clear content hierarchy (H1 β†’ H6).

SEO Tools for Beginners and Experts

ToolPurposeWebsite
Google Search ConsoleMonitor site indexingsearch.google.com/search-console
AhrefsBacklink and keyword analysisahrefs.com
SEMrushSEO audits and rank trackingsemrush.com
MozKeyword and link metricsmoz.com
Screaming FrogTechnical SEO crawlerscreamingfrog.co.uk
Yoast SEOOn-page optimization (WordPress)yoast.com
seo cheatsheet, seo optimization guide, on-page seo checklist, technical seo, seo tools list, google ranking factors, seo best practices, meta tags seo, keyword research, backlinks strategy, schema markup guide

Local SEO Optimization

Local SEO focuses on helping your business appear in local searches.
To rank locally:

  1. Add your business to Google My Business.
  2. Use NAP consistency (Name, Address, Phone).
  3. Encourage customer reviews.
  4. Add location-based keywords (e.g., β€œSEO expert in Delhi”).

Schema Markup (Structured Data)

Use JSON-LD Schema to help Google understand your page context.
Example:

{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": "SEO Cheatsheet β€” Complete Optimization Guide",
  "author": "PHPOline.in",
  "datePublished": "2025-10-28",
  "publisher": {
    "@type": "Organization",
    "name": "PHPOline.in"
  }
}


FAQ β€” SEO Cheatsheet

Q1. What is the main purpose of SEO?
To increase your website’s visibility on Google and attract organic traffic.

Q2. How long does SEO take to show results?
Typically, 3–6 months depending on competition and content quality.

Q3. What’s the difference between on-page and off-page SEO?
On-page focuses on content and structure, while off-page involves backlinks and authority.

Q4. Do meta keywords still matter?
Not for Google ranking, but they can help internal search engines.

Q5. What are Core Web Vitals?
Google’s performance metrics: LCP, FID, and CLS, measuring speed and interactivity.

REST API Cheatsheet β€” Learn RESTful API Architecture, HTTP Methods, and JSON Requests

What is REST API?

A REST API (Representational State Transfer) is a web architecture principle that allows systems to communicate using HTTP methods and resources (URLs). It’s lightweight, stateless, and widely used for connecting mobile apps, web applications, and cloud services.

For example, when your mobile app fetches user data from a server β€” it’s making a REST API call.


Core Principles of REST API

PrincipleDescription
StatelessnessEvery request is independent; the server stores no client context.
Client-Server ArchitectureSeparation of UI (client) and data storage (server).
CacheableResponses can be stored and reused.
Uniform InterfaceStandardized method of communication using HTTP.
Layered SystemAPIs can have multiple layers (gateway, authentication, etc.).
Resource-Based URLsEach endpoint represents a unique resource (like /users or /posts).

Common HTTP Methods in REST API

MethodPurposeExample EndpointOperation
GETRetrieve data/api/usersRead
POSTCreate new data/api/usersCreate
PUTReplace existing data/api/users/1Update
PATCHUpdate partial data/api/users/1Partial Update
DELETERemove data/api/users/1Delete
rest api cheatsheet, rest api tutorial, rest api methods, rest api examples, restful api design, api authentication, http status codes, json response, crud operations api, api development guide, api endpoints

REST API Example Structure

GET     /api/products        β†’ Fetch all products  
GET     /api/products/10     β†’ Fetch a specific product  
POST    /api/products        β†’ Add a new product  
PUT     /api/products/10     β†’ Update product details  
DELETE  /api/products/10     β†’ Delete product  

Example: REST API Call using JavaScript Fetch

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error fetching data:', error));

POST Example:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    title: 'Learning REST API',
    body: 'This is a RESTful example',
    userId: 5
  })
})
.then(response => response.json())
.then(data => console.log('Created:', data));

PHP REST API Example

<?php
$apiURL = "https://jsonplaceholder.typicode.com/posts";
$data = array("title" => "New Post", "body" => "Learning REST API", "userId" => 10);

$options = array(
  "http" => array(
    "header"  => "Content-Type: application/jsonrn",
    "method"  => "POST",
    "content" => json_encode($data),
  ),
);

$context = stream_context_create($options);
$result = file_get_contents($apiURL, false, $context);
echo $result;
?>

Node.js REST API Example

const express = require('express');
const app = express();
app.use(express.json());

let users = [{ id: 1, name: "Alice" }];

app.get('/api/users', (req, res) => res.json(users));

app.post('/api/users', (req, res) => {
  const newUser = { id: users.length + 1, name: req.body.name };
  users.push(newUser);
  res.status(201).json(newUser);
});

app.listen(3000, () => console.log('Server running on port 3000'));

Python REST API Example

from flask import Flask, jsonify, request

app = Flask(__name__)
users = [{"id": 1, "name": "Alice"}]

@app.route("/api/users", methods=["GET"])
def get_users():
    return jsonify(users)

@app.route("/api/users", methods=["POST"])
def add_user():
    new_user = request.json
    users.append(new_user)
    return jsonify(new_user), 201

if __name__ == "__main__":
    app.run(debug=True)

HTTP Response Codes Reference Table

CodeMeaningExample Scenario
200 OKSuccessful requestData fetched successfully
201 CreatedResource createdUser registration successful
400 Bad RequestInvalid dataMissing parameter in request
401 UnauthorizedAuthentication failedInvalid API token
403 ForbiddenNo permissionAccess denied
404 Not FoundResource missingUser ID not found
500 Internal Server ErrorServer issueAPI crashed unexpectedly

REST API Authentication Techniques

TypeUsageExample
API KeySimple, used in header or query?apikey=123456
Bearer Token (JWT)Modern authenticationAuthorization: Bearer TOKEN
OAuth 2.0Third-party authenticationUsed by Google, GitHub APIs
Basic AuthEncoded username/passwordAuthorization: Basic base64string

Working with JSON in REST APIs

Convert JavaScript object to JSON:

const obj = { name: "Bob", age: 25 };
console.log(JSON.stringify(obj));

Parse JSON response:

let json = '{"status":"success"}';
let data = JSON.parse(json);
console.log(data.status);

REST API CRUD Operations Cheatsheet

OperationHTTP MethodEndpoint Example
CreatePOST/api/posts
ReadGET/api/posts
UpdatePUT / PATCH/api/posts/1
DeleteDELETE/api/posts/1

REST API Best Practices

βœ… Use HTTPS for all API calls
βœ… Keep endpoints noun-based (/users, /products)
βœ… Use versioning (/api/v1/...)
βœ… Handle errors gracefully with clear JSON responses
βœ… Document APIs using Swagger or Postman
βœ… Test using curl, Postman, or Insomnia


FAQ β€” REST API Cheatsheet

Q1. What does REST stand for?
REST means Representational State Transfer, a standard way for systems to exchange data over HTTP.

Q2. What’s the difference between REST and SOAP APIs?
REST is lightweight and uses JSON, while SOAP uses XML and more strict messaging protocols.

Q3. How do I test a REST API?
You can use Postman, curl, or built-in browser tools to send and inspect requests.

Q4. What is an endpoint in REST API?
An endpoint is a specific URL where an API can be accessed β€” e.g., /api/products/1.

Q5. Can REST API return XML instead of JSON?
Yes. Though JSON is standard, you can configure REST APIs to return XML responses if needed.

API Integration Cheatsheet β€” The Complete Developer Reference

API Integration is one of the most important skills for modern developers. APIs (Application Programming Interfaces) connect software applications, enabling them to exchange data, trigger actions, and automate workflows.

This API Integration Cheatsheet helps you understand how APIs work, how to connect to them securely, and how to use them in JavaScript, PHP, Python, Node.js, and cURL.


What Is API Integration?

API Integration allows two applications to communicate seamlessly using structured protocols such as HTTP, REST, SOAP, or GraphQL.

For example, when you sign in using Google or fetch live weather data from OpenWeather API β€” that’s API integration in action.


Core Concepts of API Integration

TermDefinition
API EndpointThe URL where requests are sent (e.g., https://api.example.com/users)
HTTP MethodDefines the action (GET, POST, PUT, DELETE)
HeadersContain authentication, content type, and API key
Request BodyData sent with POST or PUT methods
ResponseServer’s reply, usually in JSON or XML
AuthenticationValidates access via tokens, API keys, or OAuth
api integration cheatsheet, rest api tutorial, api fetch example, axios api call, php api integration, json api request, http headers, oauth authentication, api testing tools, web api development

HTTP Methods Overview

MethodDescriptionExample Use Case
GETRetrieve dataFetch user info
POSTCreate dataAdd new product
PUTUpdate existing dataEdit profile
DELETERemove dataDelete record
PATCHPartially updateChange single field

Example: Simple API Call Using Fetch (JavaScript)

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

POST Request with Fetch API

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'Learn API Integration',
    body: 'This is a demo post',
    userId: 1
  })
})
.then(res => res.json())
.then(data => console.log(data));

API Integration Using Axios (Modern JS Library)

import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/users')
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

POST Example:

axios.post('https://api.example.com/login', {
  username: 'admin',
  password: '12345'
})
.then(res => console.log('Token:', res.data.token))
.catch(err => console.error('Login failed:', err));

PHP API Integration Example

<?php
$url = "https://jsonplaceholder.typicode.com/posts";
$data = array("title" => "API Example", "body" => "Hello World", "userId" => 1);
$options = array(
  "http" => array(
    "header"  => "Content-Type: application/jsonrn",
    "method"  => "POST",
    "content" => json_encode($data),
  ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
?>

Python API Integration Example

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.json())

POST Example:

import requests

data = {"title": "Python API", "body": "Learning integration", "userId": 10}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=data)
print(response.json())

Node.js API Integration Example

const fetch = require("node-fetch");

fetch("https://jsonplaceholder.typicode.com/users")
  .then(res => res.json())
  .then(data => console.log(data));

Using cURL for API Testing

curl -X GET https://jsonplaceholder.typicode.com/posts

POST Example:

curl -X POST https://jsonplaceholder.typicode.com/posts 
-H "Content-Type: application/json" 
-d '{"title":"cURL Demo","body":"API Integration via cURL","userId":1}'

API Authentication Techniques

TypeUsage
API KeySimple and fast; used in headers or query strings
Bearer Token (JWT)Common in REST APIs; secure and time-limited
OAuth 2.0Used for third-party access (Google, Facebook)
Basic AuthUses username and password (less secure)

Example (Bearer Token):

fetch("https://api.example.com/data", {
  headers: {
    "Authorization": "Bearer YOUR_ACCESS_TOKEN"
  }
});

Handling JSON Data in APIs

Convert to JSON (JS):

let data = {name: "Alice", age: 22};
console.log(JSON.stringify(data));

Parse JSON:

let response = '{"status":"success"}';
let obj = JSON.parse(response);
console.log(obj.status);

Best Practices for API Integration

βœ… Always use HTTPS
βœ… Keep your API keys private
βœ… Implement rate limiting and caching
βœ… Use environment variables for secrets
βœ… Log and handle errors gracefully
βœ… Test your endpoints with tools like Postman or Insomnia


Common HTTP Response Codes

CodeMeaning
200OK – Request successful
201Created – Resource created
400Bad Request
401Unauthorized
403Forbidden
404Not Found
500Internal Server Error

Popular Public APIs for Practice

API NamePurposeExample URL
JSONPlaceholderDummy REST API for testinghttps://jsonplaceholder.typicode.com
OpenWeatherMapWeather datahttps://api.openweathermap.org
TheCatAPIRandom cat imageshttps://api.thecatapi.com
CoinGeckoCrypto priceshttps://api.coingecko.com
REST CountriesCountry infohttps://restcountries.com

Related Topic


FAQ β€” API Integration Cheatsheet

Q1: What does API stand for?
API means Application Programming Interface β€” a bridge that allows apps to communicate.

Q2: What’s the difference between REST and SOAP APIs?
REST uses lightweight JSON and HTTP; SOAP uses XML and heavier protocols.

Q3: How do I test my API calls?
Use tools like Postman, Insomnia, or browser DevTools β†’ Network tab.

Q4: Is API integration difficult?
Not at all! With Fetch or Axios, you can integrate APIs easily using just a few lines of code.

Q5: What is an API key?
An API key is a unique identifier used for authenticating requests to an API.

AJAX Cheatsheet β€” The Complete Developer Reference

AJAX (Asynchronous JavaScript and XML) is one of the most essential technologies for creating dynamic and interactive web applications. It allows developers to send and receive data from a server without reloading the page.

This AJAX Cheatsheet provides a complete guide for beginners and professionals who want to master AJAX with XMLHttpRequest, Fetch API, and jQuery AJAX methods β€” all in one place.


What is AJAX in Web Development?

AJAX isn’t a programming language β€” it’s a combination of technologies that work together to make asynchronous communication possible between the client and server.

Core Components of AJAX:

  • HTML/CSS β€” Display data and layout
  • JavaScript β€” Handle client-side logic
  • XMLHttpRequest or Fetch API β€” Send/receive data
  • PHP/Python/Node.js β€” Process backend requests
  • JSON/XML β€” Exchange data formats

Example Scenario:
When you type in a search box and results appear instantly β€” that’s AJAX at work!


Basic AJAX Workflow

StepDescription
1User triggers an event (e.g., button click)
2JavaScript creates an AJAX request
3Request is sent to the server
4Server processes the request
5Server sends back data (JSON/XML)
6JavaScript updates the webpage dynamically
ajax cheatsheet, ajax tutorial, ajax javascript, ajax fetch api, ajax example in php, ajax post request, ajax form submission, ajax json response, jquery ajax, asynchronous programming

AJAX Using XMLHttpRequest

Example: Simple AJAX GET Request

<!DOCTYPE html>
<html>
<body>
<h3>AJAX Example with XMLHttpRequest</h3>
<button onclick="loadData()">Load Data</button>
<div id="result"></div>

<script>
function loadData() {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "data.php", true);
  xhr.onload = function() {
    if (xhr.status == 200) {
      document.getElementById("result").innerHTML = xhr.responseText;
    }
  };
  xhr.send();
}
</script>
</body>
</html>

data.php

<?php
echo "Hello, this is a response from the server!";
?>

AJAX Using POST Method

<script>
function sendData() {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "submit.php", true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.onload = function() {
    alert(xhr.responseText);
  };
  xhr.send("name=John&age=25");
}
</script>

AJAX with JSON Response

fetch('user.php')
  .then(response => response.json())
  .then(data => {
    console.log(data.name);
  });

user.php

<?php
$user = array("name" => "Alice", "email" => "alice@example.com");
echo json_encode($user);
?>

AJAX Using Fetch API (Modern Way)

The Fetch API is the modern replacement for XMLHttpRequest.

fetch('data.php')
  .then(response => response.text())
  .then(data => document.getElementById("output").innerHTML = data)
  .catch(error => console.error('Error:', error));

AJAX in jQuery

jQuery simplifies AJAX syntax dramatically:

$.ajax({
  url: "server.php",
  type: "POST",
  data: { name: "John", age: 30 },
  success: function(response) {
    $("#output").html(response);
  },
  error: function() {
    alert("Error fetching data!");
  }
});

Shortcut Methods:

$.get("data.php", function(response){ console.log(response); });
$.post("submit.php", {id:1}, function(data){ console.log(data); });

Handling JSON with jQuery AJAX

$.getJSON("user.php", function(data){
  $("#name").text(data.name);
  $("#email").text(data.email);
});

AJAX Error Handling

Use .catch() or error callbacks to manage request failures:

fetch('invalid.php')
  .then(response => {
    if (!response.ok) throw new Error('Network error');
    return response.json();
  })
  .catch(error => console.error('Error:', error));

Common AJAX Status Codes

Status CodeMeaning
200OK β€” Request succeeded
201Created β€” Resource created
400Bad Request
401Unauthorized
404Not Found
500Internal Server Error

AJAX Security Best Practices

βœ… Validate and sanitize all input on the server side
βœ… Use HTTPS to secure data transfer
βœ… Set proper CORS headers
βœ… Prevent CSRF attacks with tokens
βœ… Never expose sensitive data in AJAX responses


AJAX Examples with PHP Backend

Form Submission Without Page Reload:

<form id="contactForm">
  <input type="text" name="name" placeholder="Enter your name">
  <input type="email" name="email" placeholder="Enter your email">
  <button type="submit">Send</button>
</form>

<div id="response"></div>

<script>
document.getElementById("contactForm").onsubmit = function(e) {
  e.preventDefault();
  fetch("submit.php", {
    method: "POST",
    body: new FormData(this)
  })
  .then(res => res.text())
  .then(data => document.getElementById("response").innerHTML = data);
};
</script>

submit.php

<?php
echo "Thank you, " . htmlspecialchars($_POST['name']) . "! We received your message.";
?>

Advantages of Using AJAX

  • Enhances user experience
  • Reduces server load and bandwidth usage
  • Enables real-time updates (used in chat, notifications)
  • Improves page responsiveness
  • Supports asynchronous form submissions


FAQ β€” AJAX Cheatsheet

Q1: What does AJAX stand for?
AJAX stands for Asynchronous JavaScript and XML. It enables web pages to fetch data from a server without reloading.

Q2: Can AJAX work with JSON instead of XML?
Yes, modern web apps mostly use JSON for data exchange due to its simplicity.

Q3: Is AJAX used in React or Vue.js?
Yes, both frameworks support AJAX through the Fetch API or Axios library.

Q4: How can I debug AJAX requests?
Use browser DevTools β†’ Network tab to inspect requests and responses.

Q5: What is the difference between Fetch and XMLHttpRequest?
Fetch API provides a modern, promise-based interface, whereas XMLHttpRequest uses callbacks.

JSON Cheatsheet β€” The Ultimate Developer Reference

JSON (JavaScript Object Notation) is a lightweight and language-independent data-interchange format widely used in web development, APIs, and configuration files.
It allows systems to exchange structured data in a readable format, making it a universal data language across platforms.

This JSON Cheatsheet gives you a complete reference β€” from syntax basics to real-world examples β€” for developers working with JavaScript, Python, PHP, Node.js, and APIs.


What is JSON?

JSON is a text-based format for representing structured data. It uses simple syntax with key-value pairs, arrays, and nested objects.

βœ… Key Benefits:

  • Easy to read and write
  • Lightweight and language-independent
  • Compatible with most modern APIs
  • Easily parsed into native data structures

Example of JSON:

{
  "name": "John Doe",
  "age": 30,
  "skills": ["HTML", "CSS", "JavaScript"],
  "active": true
}

JSON Syntax Rules

ElementDescriptionExample
DataName/value pairs"name": "Alice"
Objects{} contain key/value pairs{"city": "New York"}
Arrays[] contain ordered values["red", "green", "blue"]
KeysMust be strings, enclosed in double quotes"language"
ValuesCan be string, number, boolean, array, object, or null"PHP", 123, true
WhitespaceIgnored by parserOptional
CommaUsed to separate key/value pairs"a": 1, "b": 2
json cheatsheet, json tutorial, json syntax, json examples, json parser, json objects and arrays, json format rules, json vs xml, json in javascript, json in php, json api response

JSON Data Types

TypeExample
String"language": "Python"
Number"year": 2025
Boolean"active": true
Array"colors": ["blue", "green", "red"]
Object"user": {"id": 1, "name": "John"}
Null"address": null

JSON Objects and Arrays

Object Example:

{
  "id": 101,
  "title": "Developer",
  "salary": 75000
}

Array Example:

[
  "JavaScript",
  "Python",
  "PHP"
]

Array of Objects:

[
  { "id": 1, "name": "Alice" },
  { "id": 2, "name": "Bob" }
]

Nested JSON Example

{
  "student": {
    "name": "Sara",
    "grade": "A",
    "subjects": ["Math", "Science", "English"],
    "address": {
      "city": "New Delhi",
      "country": "India"
    }
  }
}

Working with JSON in JavaScript

Parsing JSON

Convert JSON string β†’ JavaScript object:

const jsonData = '{"name": "John", "age": 25}';
const obj = JSON.parse(jsonData);
console.log(obj.name); // John

Stringify JSON

Convert JavaScript object β†’ JSON string:

const user = { name: "Alice", age: 22 };
const jsonString = JSON.stringify(user);
console.log(jsonString);

Working with JSON in PHP

<?php
$json = '{"name":"Alice","age":22}';
$data = json_decode($json, true);  // Convert to PHP array
echo $data['name']; // Alice

$user = array("name"=>"John", "age"=>30);
echo json_encode($user);
?>

Working with JSON in Python

import json

data = '{"name": "John", "age": 30}'
parsed = json.loads(data)
print(parsed['name'])

person = {"name": "Alice", "city": "London"}
json_string = json.dumps(person)
print(json_string)

JSON in REST APIs

A typical API response in JSON:

{
  "status": "success",
  "data": {
    "id": 101,
    "title": "Learn JSON",
    "category": "Programming"
  }
}

JSON Formatting Tips

βœ… Always use double quotes for keys and strings
βœ… Avoid trailing commas
βœ… Use online tools like phponline.in/json-formatter for clean formatting
βœ… Validate JSON before using it in production


JSON vs XML

FeatureJSONXML
ReadabilityEasierVerbose
SyntaxKey-valueTags
Data SizeSmallerLarger
Parsing SpeedFasterSlower
Browser SupportNative in JSRequires parser
Data TypesSupports multipleAll as string

JSON Errors & Validation

Common issues:

  • Missing double quotes
  • Extra commas
  • Unescaped characters

You can validate JSON using:

npm install -g jsonlint
jsonlint file.json

JSON Pretty Print

Format JSON for readability:

JSON.stringify(data, null, 2);

Best Practices for JSON

βœ… Use lowercase keys for consistency
βœ… Avoid deeply nested objects (affects performance)
βœ… Keep structure consistent across APIs
βœ… Include metadata like status, message, or timestamp



FAQ β€” JSON Cheatsheet

Q1: What is JSON used for?
JSON is used for data exchange between a client and server in web applications and APIs.

Q2: How is JSON different from JavaScript objects?
JSON is a text format, while JavaScript objects are in-memory structures.

Q3: Can JSON contain comments?
No, JSON doesn’t support comments β€” use metadata instead.

Q4: What tools can validate JSON?
You can use JSONLint, Postman, or online validators like json-validator.

Q5: How do I convert JSON to CSV?
You can use Python’s pandas library or online converters to transform JSON data into CSV.

Vue.js Cheatsheet β€” The Ultimate Developer Reference

Vue.js is a progressive JavaScript framework for building dynamic user interfaces and single-page applications (SPAs).
It’s lightweight, fast, and easy to integrate into existing web projects β€” making it one of the most popular front-end frameworks in modern development.

This Vue.js Cheatsheet is your quick go-to reference for writing clean, efficient Vue code β€” perfect for both beginners and experienced developers.


What is Vue.js?

Vue.js is an open-source front-end JavaScript framework designed to make UI development simple and flexible.
It uses a declarative and component-based approach, allowing developers to easily manage data, logic, and presentation.

βœ… Key Features:

  • Reactive Data Binding
  • Virtual DOM Rendering
  • Component-based Architecture
  • Two-way Data Binding
  • Transitions and Animations
  • Routing and State Management

Setting Up Vue.js

1. Using CDN

<script src="https://unpkg.com/vue@3"></script>

2. Creating a Vue App

<div id="app">
  {{ message }}
</div>

<script>
const app = Vue.createApp({
  data() {
    return {
      message: "Hello Vue.js!"
    }
  }
});
app.mount('#app');
</script>

Vue.js Template Syntax

SyntaxDescriptionExample
{{ }}Data Binding{{ message }}
v-bindBind HTML attributesv-bind:src="imageURL"
v-modelTwo-way data bindingv-model="username"
v-if / v-elseConditional rendering<p v-if="loggedIn">Welcome</p>
v-forLoop through data<li v-for="item in items">{{ item }}</li>
v-onEvent listenerv-on:click="sayHello" or @click="sayHello"
vue.js cheatsheet, vue.js tutorial, vue directives, vue components, vue data binding, vue computed properties, vue lifecycle hooks, vue router example, vue beginner guide, vue.js quick reference

Vue.js Directives

DirectivePurposeExample
v-textUpdates textContent<p v-text="message"></p>
v-htmlInserts HTML content<div v-html="rawHTML"></div>
v-showShow/Hide element<p v-show="isVisible">Visible</p>
v-ifConditional rendering<div v-if="isLoggedIn"></div>
v-else-ifConditional alternative<div v-else-if="hasAccess"></div>
v-elseFallback condition<div v-else>No Access</div>
v-forRender list<li v-for="(user, index) in users">{{ user.name }}</li>

Vue.js Event Handling

<button @click="increment">Add Count</button>
<p>Count: {{ count }}</p>

<script>
const app = Vue.createApp({
  data() {
    return { count: 0 }
  },
  methods: {
    increment() {
      this.count++
    }
  }
});
app.mount('#app');
</script>

Vue.js Computed Properties

const app = Vue.createApp({
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe'
    }
  },
  computed: {
    fullName() {
      return `${this.firstName} ${this.lastName}`;
    }
  }
});

Vue.js Watchers

watch: {
  count(newVal, oldVal) {
    console.log(`Count changed from ${oldVal} to ${newVal}`);
  }
}

Watchers are ideal for reacting to data changes β€” such as API calls or animations.


Vue.js Components

Global Component

app.component('user-card', {
  props: ['name'],
  template: `<div>Hello, {{ name }}</div>`
});

Usage

<user-card name="Alice"></user-card>

Vue Lifecycle Hooks

HookWhen Triggered
beforeCreateBefore data initialization
createdAfter data initialization
beforeMountBefore mounting DOM
mountedAfter mounting DOM
beforeUpdateBefore re-render
updatedAfter re-render
beforeUnmountBefore component destruction
unmountedAfter destruction

Vue.js Conditional Rendering

<p v-if="isLoggedIn">Welcome back!</p>
<p v-else>Please log in</p>

Vue.js Lists

<ul>
  <li v-for="(fruit, index) in fruits" :key="index">{{ fruit }}</li>
</ul>

Vue.js Forms and v-model

<input v-model="username" placeholder="Enter your name">
<p>Hello, {{ username }}</p>

Vue.js Class & Style Binding

<div :class="{ active: isActive }"></div>
<div :style="{ color: textColor, fontSize: fontSize + 'px' }"></div>

Vue Router Example

Install:

npm install vue-router

Setup:

import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/Home.vue';
import About from './components/About.vue';

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;

Vue CLI Quick Commands

CommandDescription
npm install -g @vue/cliInstall Vue CLI
vue create project-nameCreate new Vue project
npm run serveRun local dev server
npm run buildBuild for production

Vue 3 Composition API Example

import { createApp, ref } from 'vue';

const App = {
  setup() {
    const count = ref(0);
    const increment = () => count.value++;
    return { count, increment };
  }
};
createApp(App).mount('#app');

Best Practices for Vue.js

βœ… Use computed instead of long inline expressions
βœ… Prefer components for reusable UI blocks
βœ… Manage routes with Vue Router
βœ… Use Vuex or Pinia for state management
βœ… Keep template markup clean and minimal



FAQ β€” Vue.js Cheatsheet

Q1: What is Vue.js mainly used for?
Vue.js is used to build responsive, component-based web interfaces and single-page applications.

Q2: Is Vue.js easier than React?
Yes, Vue.js is generally considered easier for beginners due to its simpler syntax and smaller learning curve.

Q3: Can Vue.js work with Node.js?
Yes. Vue.js handles the frontend, while Node.js powers the backend for full-stack development.

Q4: What are Vue.js directives?
Directives like v-if, v-for, v-bind, and v-model are special attributes that control DOM behavior.

Q5: What’s new in Vue 3?
Vue 3 introduces the Composition API, Teleport, and improved performance with a smaller bundle size.

Node.js Cheatsheet β€” Complete Developer Reference

Node.js is a powerful JavaScript runtime environment built on Chrome’s V8 engine that allows you to execute JavaScript on the server-side. It’s the backbone of modern web apps, APIs, and scalable microservices.

This Node.js Cheatsheet is designed as a quick and complete reference β€” ideal for developers learning backend programming or refreshing their knowledge.


What is Node.js?

Node.js enables developers to build fast, scalable, and real-time web applications using JavaScript beyond the browser.
It uses a non-blocking, event-driven I/O model, making it ideal for handling multiple requests efficiently.

βœ… Key Features of Node.js:

  • Built on V8 JavaScript Engine for speed
  • Asynchronous and event-driven architecture
  • Single-threaded but supports concurrent handling
  • Huge ecosystem of packages via NPM
  • Ideal for APIs, chat apps, and streaming servers

Installing Node.js

Check Node and NPM Versions

node -v
npm -v

Install a Package

npm install express

Initialize a Project

npm init -y

Node.js REPL Commands

CommandPurpose
.helpDisplay help info
.exitExit REPL
.save filename.jsSave REPL session to file
.load filename.jsLoad file into REPL

Creating Your First Node.js Server

// server.js
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello from Node.js Server!');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

Run:

node server.js

Node.js Core Modules

ModuleDescriptionExample
fsFile system operationsfs.readFile()
httpCreate HTTP serverhttp.createServer()
pathHandle file pathspath.join()
osSystem infoos.platform()
eventsEvent handlingemitter.on()
urlParse URLsurl.parse()
node.js cheatsheet, node.js tutorial, node.js examples, node.js file system, node.js server, express.js tutorial, node.js event loop, node.js asynchronous programming, node.js beginner guide, node.js quick reference

Working with File System (fs)

Read File

const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Write File

fs.writeFile('output.txt', 'Hello Node!', err => {
  if (err) throw err;
  console.log('File written successfully');
});

Append Data

fs.appendFile('log.txt', 'New log entryn', err => {
  if (err) throw err;
});

Node.js Event Emitter

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('message', (msg) => {
  console.log(`Received: ${msg}`);
});

emitter.emit('message', 'Hello Event System!');

Node.js Modules and Exports

module1.js

exports.greet = function(name) {
  return `Hello, ${name}!`;
};

main.js

const greet = require('./module1');
console.log(greet.greet('Developer'));

Node.js URL Module

const url = require('url');
const myURL = new URL('https://example.com/product?id=100&name=shirt');

console.log(myURL.hostname); // example.com
console.log(myURL.searchParams.get('name')); // shirt

Node.js OS Module

const os = require('os');
console.log(os.platform());
console.log(os.totalmem());
console.log(os.uptime());

Asynchronous Programming in Node.js

Node.js uses callbacks, promises, and async/await for asynchronous operations.

Using Promises

const fs = require('fs').promises;

async function readData() {
  const data = await fs.readFile('example.txt', 'utf8');
  console.log(data);
}
readData();

Node.js with Express Framework

Install Express:

npm install express

Example server:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Welcome to Express Server');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Node.js Middleware Example

app.use((req, res, next) => {
  console.log(`Request made at: ${new Date().toISOString()}`);
  next();
});

Node.js REST API Example

const express = require('express');
const app = express();
app.use(express.json());

let users = [{ id: 1, name: "John" }];

app.get('/users', (req, res) => res.json(users));
app.post('/users', (req, res) => {
  users.push(req.body);
  res.json({ message: "User added" });
});

app.listen(4000, () => console.log('API running on port 4000'));

Node.js Process Object

console.log(process.pid);
console.log(process.platform);
console.log(process.cwd());

Exit the process:

process.exit();

Node.js Best Practices

βœ… Use environment variables with .env
βœ… Handle errors using try...catch
βœ… Use async/await instead of callbacks
βœ… Organize routes and controllers properly
βœ… Use a package manager (NPM/Yarn)


FAQ β€” Node.js Cheatsheet

Q1: What is Node.js used for?
Node.js is used to build fast, scalable, and real-time server-side applications using JavaScript.

Q2: Is Node.js a framework or runtime?
Node.js is a runtime environment, not a framework.

Q3: What makes Node.js asynchronous?
Its event-driven, non-blocking I/O system allows multiple requests to be processed simultaneously.

Q4: Can Node.js work with databases?
Yes, Node.js works with MySQL, MongoDB, PostgreSQL, and Redis seamlessly.

Q5: Is Node.js good for APIs?
Absolutely. Node.js is ideal for RESTful and GraphQL APIs due to its lightweight architecture.

ReactJS Cheatsheet β€” The Complete Developer Reference

ReactJS is one of the most powerful JavaScript libraries for building dynamic, high-performance user interfaces. Created by Facebook, it revolutionized frontend development by introducing a component-based architecture and virtual DOM.

This ReactJS Cheatsheet is designed to give developers a quick, structured, and easy-to-understand reference for all key features, including JSX, Components, Props, State, Hooks, and Routing.


What is ReactJS?

ReactJS is an open-source JavaScript library used to build interactive UIs for single-page and complex web applications. It allows developers to manage views efficiently by breaking the UI into reusable components.

βœ… Key Features of ReactJS:

  • Component-based architecture
  • Virtual DOM for performance optimization
  • Unidirectional data flow
  • Support for JSX (JavaScript XML)
  • Powerful hooks for managing state and side effects

ReactJS Basic Syntax

ConceptSyntax Example
JSX<h1>Hello, React!</h1>
Componentfunction App() { return <div>Welcome!</div> }
RenderReactDOM.render(<App />, document.getElementById('root'));
Props<User name="John" />
Stateconst [count, setCount] = useState(0);

Creating Your First React Component

import React from 'react';

function Welcome() {
  return <h1>Hello, World!</h1>;
}

export default Welcome;

Render in index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import Welcome from './Welcome';

ReactDOM.render(<Welcome />, document.getElementById('root'));

ReactJS JSX Syntax Explained

JSX allows you to write HTML-like syntax directly in JavaScript.

const element = <h2>React is Amazing!</h2>;

You can embed JavaScript expressions using {}:

const user = "Alice";
return <h3>Welcome, {user}!</h3>;

React Components β€” Functional and Class

Functional Component:

function Greeting() {
  return <h2>Hello React Functional Component!</h2>;
}

Class Component:

import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h2>Hello React Class Component!</h2>;
  }
}

React Props (Passing Data Between Components)

Props are used to pass data from a parent component to a child component.

function Welcome(props) {
  return <h3>Welcome, {props.name}</h3>;
}

function App() {
  return <Welcome name="John Doe" />;
}

React State (useState Hook)

State is used to manage dynamic data that can change during the app lifecycle.

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click Me</button>
    </div>
  );
}

React useEffect Hook (Side Effects)

The useEffect() hook lets you handle side effects, such as fetching data or updating the DOM.

import React, { useState, useEffect } from 'react';

function DataFetcher() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then(res => res.json())
      .then(data => setData(data));
  }, []);

  return <div>{data.length} posts fetched</div>;
}

React Event Handling

function ClickButton() {
  const handleClick = () => alert("Button Clicked!");
  return <button onClick={handleClick}>Click Me</button>;
}

React Conditional Rendering

function Greeting({ isLoggedIn }) {
  return isLoggedIn ? <h2>Welcome back!</h2> : <h2>Please log in.</h2>;
}

React Lists and Keys

function NameList() {
  const names = ["Alice", "Bob", "Charlie"];
  return (
    <ul>
      {names.map((name, index) => <li key={index}>{name}</li>)}
    </ul>
  );
}

React Forms and Controlled Components

function FormExample() {
  const [value, setValue] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Submitted: ${value}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input value={value} onChange={(e) => setValue(e.target.value)} />
      <button type="submit">Submit</button>
    </form>
  );
}

React Router Cheatsheet

Install:

npm install react-router-dom

Example:

import { BrowserRouter as Router, Route, Routes, Link } from "react-router-dom";

function App() {
  return (
    <Router>
      <nav>
        <Link to="/">Home</Link> | <Link to="/about">About</Link>
      </nav>

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  );
}

React Lifecycle Methods (Class Components)

PhaseMethodPurpose
MountingcomponentDidMount()Invoked after component renders
UpdatingcomponentDidUpdate()Called after updates
UnmountingcomponentWillUnmount()Cleanup before removal
reactjs cheatsheet, react hooks reference, react components guide, react state management, jsx syntax, react lifecycle methods, react router, react functional components, react useEffect example, react useState tutorial

React Context API

Used for state management without prop drilling.

const UserContext = React.createContext();

function App() {
  return (
    <UserContext.Provider value="John">
      <Profile />
    </UserContext.Provider>
  );
}

function Profile() {
  const user = React.useContext(UserContext);
  return <h2>User: {user}</h2>;
}

React Performance Optimization Tips

  • Use React.memo() to prevent unnecessary re-renders.
  • Apply key props properly in lists.
  • Lazy load components using React.lazy and Suspense.
  • Keep components small and focused.
  • Use PureComponent for class components.

Popular React Developer Tools

ToolPurpose
Create React AppQuick setup for React projects
React DevToolsDebug and inspect React components
Redux ToolkitManage global state efficiently
Next.jsServer-side rendering framework
ViteFast development bundler
React QueryHandle data fetching and caching

FAQ β€” ReactJS Cheatsheet

Q1: What is ReactJS used for?
React is used to build fast, reusable, and dynamic user interfaces for web and mobile apps.

Q2: Is ReactJS a library or framework?
ReactJS is a library, not a full-fledged framework like Angular.

Q3: What are hooks in React?
Hooks like useState and useEffect let you manage state and side effects in functional components.

Q4: How does React improve performance?
React uses a Virtual DOM to minimize direct DOM manipulation and re-rendering.

Q5: Can React work with backend technologies like PHP or Node.js?
Yes, React can easily integrate with APIs built in PHP, Node.js, or Python.

GraphQL Cheatsheet β€” The Complete Developer Reference

GraphQL is a powerful query language for APIs developed by Facebook, allowing clients to request exactly the data they need and nothing more.
Unlike REST APIs, GraphQL lets you fetch multiple resources in a single request, improving performance and flexibility for modern web and mobile apps.

This GraphQL Cheatsheet is your ultimate quick reference guide to all essential syntax, queries, mutations, subscriptions, and schema definitions β€” perfect for developers who want to master GraphQL fast.


What is GraphQL?

GraphQL is a data query and manipulation language for APIs, as well as a runtime for fulfilling queries with your existing data.
It provides a strongly typed schema that defines how clients can access your API.

βœ… Key Advantages of GraphQL:

  • Fetch multiple resources in one query
  • No over-fetching or under-fetching
  • Strong typing system
  • Real-time data with subscriptions
  • Perfect for microservices and frontend apps

Basic GraphQL Syntax

OperationSyntax Example
Queryquery { user(id: 1) { name email } }
Mutationmutation { addUser(name: "John", email: "john@site.com") { id } }
Subscriptionsubscription { newUser { id name } }
Fragmentfragment userInfo on User { name email }
graphql cheatsheet, graphql tutorial for beginners, graphql queries examples, graphql mutations, graphql vs rest, graphql schema design, graphql resolver, graphql syntax, graphql subscription, graphql with nodejs

GraphQL Query Example

A query is used to read or fetch data.

query {
  user(id: 1) {
    id
    name
    email
    posts {
      title
      content
    }
  }
}

βœ… Output:

{
  "data": {
    "user": {
      "id": 1,
      "name": "Alice",
      "email": "alice@example.com",
      "posts": [
        { "title": "Intro to GraphQL", "content": "GraphQL basics..." }
      ]
    }
  }
}

GraphQL Mutation Example

A mutation is used to create, update, or delete data.

mutation {
  createUser(name: "John", email: "john@example.com") {
    id
    name
    email
  }
}

βœ… Output:

{
  "data": {
    "createUser": {
      "id": "2",
      "name": "John",
      "email": "john@example.com"
    }
  }
}

GraphQL Schema Definition Language (SDL)

A schema defines the structure of data and operations available in GraphQL.

type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post]
}

type Post {
  id: ID!
  title: String!
  content: String!
  author: User
}

type Query {
  users: [User]
  user(id: ID!): User
}

type Mutation {
  createUser(name: String!, email: String!): User
}

GraphQL Fragments

Fragments help reuse field selections across multiple queries.

fragment userDetails on User {
  id
  name
  email
}

query {
  users {
    ...userDetails
  }
}

GraphQL Directives

Directives modify query execution dynamically.

query GetUsers($showEmail: Boolean!) {
  users {
    name
    email @include(if: $showEmail)
  }
}

GraphQL Variables

query getUser($userId: ID!) {
  user(id: $userId) {
    name
    email
  }
}

Variables:

{
  "userId": "1"
}

GraphQL Subscriptions (Real-Time Updates)

Subscriptions allow you to receive live data updates when events occur.

subscription {
  postAdded {
    id
    title
    content
  }
}

GraphQL vs REST API

FeatureGraphQLREST API
Data FetchingSingle endpointMultiple endpoints
Over-fetching❌ Noβœ… Yes
Real-time supportβœ… Yes (Subscriptions)❌ No
Query flexibilityHighFixed
Data typingStrongly typedNo typing
PerformanceOptimizedCan be slower

GraphQL Common Use Cases

  • Web and mobile APIs
  • Microservice communication
  • Real-time dashboards
  • Cross-platform applications
  • Data aggregation from multiple sources

Error Handling in GraphQL

{
  "errors": [
    {
      "message": "User not found",
      "locations": [{ "line": 2, "column": 3 }],
      "path": ["user"]
    }
  ]
}

GraphQL Tools and Libraries

ToolPurpose
Apollo ServerBuild GraphQL APIs in Node.js
Apollo ClientQuery GraphQL APIs from the frontend
GraphQL YogaSimple server framework
GraphiQLInteractive in-browser query editor
HasuraAuto-generates GraphQL APIs from databases
PrismaORM for GraphQL and databases

PostgreSQL Integration with GraphQL

GraphQL can integrate directly with PostgreSQL using:

  • Hasura GraphQL Engine
  • PostGraphile
  • Prisma

Example query:

query {
  users {
    id
    name
    posts {
      title
    }
  }
}

Performance Optimization Tips

  • Use query caching for frequent requests.
  • Avoid deep nested queries to prevent recursion.
  • Implement batch resolvers to reduce round trips.
  • Use pagination for large datasets (limit, offset).


FAQ β€” GraphQL Cheatsheet

Q1: What is GraphQL used for?
GraphQL is used to efficiently fetch and manipulate data from APIs using a single endpoint.

Q2: Is GraphQL faster than REST?
Yes, because it eliminates multiple endpoint calls and reduces payload size.

Q3: Can I use GraphQL with PHP or Python?
Yes, libraries like Lighthouse (PHP) and Graphene (Python) support GraphQL.

Q4: Does GraphQL replace REST?
Not necessarily. It complements REST by providing more flexible querying capabilities.

Q5: How do I test GraphQL queries?
Use GraphiQL, Apollo Studio, or Postman GraphQL mode.

PostgreSQL Cheatsheet β€” Quick Reference for SQL Developers

PostgreSQL is a powerful open-source relational database management system (RDBMS) that emphasizes data integrity, extensibility, and standards compliance. It supports advanced SQL features, JSON data, and custom functions, making it a favorite among developers for scalable and secure applications.

This PostgreSQL Cheatsheet provides a concise reference of essential commands, SQL syntax, and administrative operations.


Basic PostgreSQL Commands

CommandDescription
psql -U username -d dbnameConnect to a database
lList all databases
c database_nameConnect to a specific database
dtList all tables
d table_nameDescribe a table
qQuit psql shell

Database and Table Management

Create and Drop Database

CREATE DATABASE mydb;
DROP DATABASE mydb;

Create and Drop Table

CREATE TABLE employees (
  id SERIAL PRIMARY KEY,
  name VARCHAR(50),
  age INT,
  department VARCHAR(30)
);

DROP TABLE employees;

Alter Table

ALTER TABLE employees ADD COLUMN salary NUMERIC(10,2);
ALTER TABLE employees RENAME COLUMN name TO full_name;
ALTER TABLE employees DROP COLUMN department;

Insert, Update, Delete, and Select Data

Insert Data

INSERT INTO employees (full_name, age, salary)
VALUES ('Alice Brown', 28, 60000);

Select Data

SELECT * FROM employees;
SELECT full_name, salary FROM employees WHERE age > 25;
SELECT DISTINCT department FROM employees;

Update Data

UPDATE employees SET salary = salary + 5000 WHERE age > 30;

Delete Data

DELETE FROM employees WHERE salary < 40000;

Filtering and Sorting Data

SELECT * FROM employees WHERE department = 'HR' ORDER BY salary DESC;
SELECT * FROM employees WHERE age BETWEEN 25 AND 35;
SELECT * FROM employees WHERE full_name LIKE 'A%';

PostgreSQL Joins Explained

Join TypeDescriptionExample
INNER JOINReturns only matching rowsSELECT * FROM a INNER JOIN b ON a.id = b.a_id;
LEFT JOINAll rows from left table + matching from rightSELECT * FROM a LEFT JOIN b ON a.id = b.a_id;
RIGHT JOINAll rows from right table + matching from leftSELECT * FROM a RIGHT JOIN b ON a.id = b.a_id;
FULL OUTER JOINAll rows when there is a match in either tableSELECT * FROM a FULL JOIN b ON a.id = b.a_id;

Aggregate Functions

FunctionDescriptionExample
COUNT()Count number of rowsSELECT COUNT(*) FROM employees;
SUM()Calculate totalSELECT SUM(salary) FROM employees;
AVG()Average valueSELECT AVG(salary) FROM employees;
MAX()Highest valueSELECT MAX(age) FROM employees;
MIN()Lowest valueSELECT MIN(age) FROM employees;

GROUP BY and HAVING Clauses

SELECT department, COUNT(*) AS total
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;

Constraints and Keys

ConstraintDescription
PRIMARY KEYUniquely identifies each row
FOREIGN KEYReferences another table
UNIQUEEnsures all values are different
NOT NULLField cannot be NULL
CHECKEnsures valid data values
DEFAULTSets default value
postgresql cheatsheet, postgresql tutorial for beginners, postgresql commands list, postgresql sql examples, postgresql create database, postgresql joins, postgresql functions, postgresql vs mysql, postgresql select query, postgresql administration

PostgreSQL Functions and Expressions

SELECT NOW();               -- Current timestamp  
SELECT AGE('2025-10-28');   -- Age calculation  
SELECT UPPER('postgres');   -- Convert to uppercase  
SELECT ROUND(45.678, 1);    -- Round to 1 decimal  

Transactions and Rollback

BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;

Rollback in case of an error:

ROLLBACK;

User and Privilege Management

CREATE USER john WITH PASSWORD 'securePass';
GRANT ALL PRIVILEGES ON DATABASE mydb TO john;
REVOKE INSERT ON TABLE employees FROM john;
DROP USER john;

Indexing for Performance

CREATE INDEX idx_employee_name ON employees(full_name);
DROP INDEX idx_employee_name;

Backup and Restore PostgreSQL Database

Backup:

pg_dump mydb > mydb_backup.sql

Restore:

psql mydb < mydb_backup.sql

PostgreSQL JSON Functions

PostgreSQL fully supports JSON and JSONB.

CREATE TABLE products (
  id SERIAL PRIMARY KEY,
  details JSONB
);

INSERT INTO products (details)
VALUES ('{"name": "Laptop", "brand": "Dell", "price": 800}');

Query JSON Data:

SELECT details->>'name' AS product_name FROM products;

PostgreSQL Performance Tips

  • Use EXPLAIN ANALYZE to inspect query performance.
  • Avoid unnecessary joins with CTEs (Common Table Expressions).
  • Always index columns used in WHERE or JOIN.
  • Use VACUUM ANALYZE to reclaim space and optimize statistics.

FAQ β€” PostgreSQL Cheatsheet

Q1: What makes PostgreSQL different from MySQL?
PostgreSQL supports complex queries, JSON data, and ACID compliance, making it ideal for enterprise applications.

Q2: Is PostgreSQL open source?
Yes, PostgreSQL is completely free and open source under the PostgreSQL License.

Q3: Can I use PostgreSQL for web development?
Yes, it’s widely used with frameworks like Django, Laravel, and Node.js.

Q4: What port does PostgreSQL use by default?
PostgreSQL uses port 5432 by default.

Q5: How can I connect PostgreSQL to PHP or Python?
Use pg_connect() in PHP or psycopg2 in Python to establish a database connection.