1. Home
  2. /
  3. SQL
  4. /
  5. PostgreSQL Advanced Queries

PostgreSQL Advanced Queries - SQL Typing CST Test

Loading…

PostgreSQL Advanced Queries — SQL Code

Demonstrates advanced SQL features including JOINs, CTEs, window functions, and complex aggregations.

-- Create tables with relationships
CREATE TABLE users (
	id SERIAL PRIMARY KEY,
	username VARCHAR(50) UNIQUE NOT NULL,
	email VARCHAR(100) UNIQUE NOT NULL,
	created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
	last_login TIMESTAMP
);

CREATE TABLE posts (
	id SERIAL PRIMARY KEY,
	user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
	title VARCHAR(200) NOT NULL,
	content TEXT,
	status VARCHAR(20) DEFAULT 'draft',
	created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
	updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE comments (
	id SERIAL PRIMARY KEY,
	post_id INTEGER REFERENCES posts(id) ON DELETE CASCADE,
	user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
	content TEXT NOT NULL,
	created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Insert sample data
INSERT INTO users (username, email) VALUES 
	('alice', 'alice@example.com'),
	('bob', 'bob@example.com'),
	('charlie', 'charlie@example.com');

INSERT INTO posts (user_id, title, content, status) VALUES 
	(1, 'First Post', 'This is my first blog post.', 'published'),
	(1, 'Second Post', 'Another interesting post.', 'published'),
	(2, 'Draft Post', 'This is still a draft.', 'draft');

INSERT INTO comments (post_id, user_id, content) VALUES 
	(1, 2, 'Great first post!'),
	(1, 3, 'Thanks for sharing.'),
	(2, 3, 'Very informative.');

-- Complex queries with JOINs, aggregations, and CTEs
WITH user_stats AS (
	SELECT 
		u.id,
		u.username,
		COUNT(DISTINCT p.id) as post_count,
		COUNT(DISTINCT c.id) as comment_count,
		MAX(p.created_at) as last_post_date
	FROM users u
	LEFT JOIN posts p ON u.id = p.user_id AND p.status = 'published'
	LEFT JOIN comments c ON u.id = c.user_id
	GROUP BY u.id, u.username
),
popular_posts AS (
	SELECT 
		p.id,
		p.title,
		u.username as author,
		COUNT(c.id) as comment_count,
		RANK() OVER (ORDER BY COUNT(c.id) DESC) as popularity_rank
	FROM posts p
	JOIN users u ON p.user_id = u.id
	LEFT JOIN comments c ON p.id = c.post_id
	WHERE p.status = 'published'
	GROUP BY p.id, p.title, u.username
)
SELECT 
	us.username,
	us.post_count,
	us.comment_count,
	us.last_post_date,
	COALESCE(pp.title, 'No posts') as most_popular_post,
	COALESCE(pp.comment_count, 0) as most_popular_post_comments
FROM user_stats us
LEFT JOIN popular_posts pp ON pp.popularity_rank = 1
ORDER BY us.post_count DESC, us.comment_count DESC;

-- Window functions example
SELECT 
	u.username,
	p.title,
	p.created_at,
	LAG(p.created_at) OVER (
		PARTITION BY u.id 
		ORDER BY p.created_at
	) as previous_post_date,
	COUNT(*) OVER (
		PARTITION BY u.id
	) as total_user_posts,
	ROW_NUMBER() OVER (
		PARTITION BY u.id 
		ORDER BY p.created_at
	) as post_sequence
FROM users u
JOIN posts p ON u.id = p.user_id
WHERE p.status = 'published'
ORDER BY u.username, p.created_at;

SQL Language Guide

SQL (Structured Query Language) is a standard language for managing and manipulating relational databases, enabling querying, insertion, updating, and deletion of data efficiently.

Primary Use Cases

  • ▸Querying relational data for applications
  • ▸Data aggregation and reporting
  • ▸Transaction management in business systems
  • ▸Analytics and business intelligence
  • ▸Database schema definition and data integrity enforcement

Notable Features

  • ▸Declarative syntax for querying data
  • ▸Support for CRUD operations: Create, Read, Update, Delete
  • ▸Joins and subqueries for combining data
  • ▸Transactions to ensure atomicity and consistency
  • ▸Data definition language (DDL) for schema management

Origin & Creator

Developed at IBM in the early 1970s by Donald D. Chamberlin and Raymond F. Boyce.

Industrial Note

SQL is ubiquitous in enterprise, analytics, web applications, and data-intensive domains where structured relational data is used.

Quick Explain

  • ▸SQL provides declarative commands to interact with relational database systems (RDBMS).
  • ▸Supports querying, filtering, aggregation, joins, and transactions.
  • ▸Used across major RDBMS like MySQL, PostgreSQL, Oracle, SQL Server, and SQLite.
  • ▸Enforces schema, data types, constraints, and relationships.
  • ▸Enables both simple queries and complex analytical operations.

Core Features

  • ▸SELECT queries with filtering and ordering
  • ▸INSERT, UPDATE, DELETE operations
  • ▸JOINs (INNER, LEFT, RIGHT, FULL) and subqueries
  • ▸GROUP BY, HAVING, and aggregate functions
  • ▸Transactions and constraint enforcement

Learning Path

  • ▸Understand relational data modeling
  • ▸Learn basic CRUD operations
  • ▸Master joins, subqueries, and aggregation
  • ▸Study indexing, constraints, and transactions
  • ▸Practice database optimization and analytics queries

Practical Examples

  • ▸SELECT data with WHERE filters
  • ▸JOIN multiple tables for relational queries
  • ▸Aggregate data using SUM, COUNT, AVG, MAX, MIN
  • ▸Create and manage tables with constraints
  • ▸Use transactions to ensure atomic operations

Comparisons

  • ▸SQL vs NoSQL: SQL for structured data, NoSQL for flexible schema/unstructured data
  • ▸MySQL vs PostgreSQL: MySQL widely used, PostgreSQL more advanced features
  • ▸SQL vs GraphQL: SQL queries relational data, GraphQL queries API endpoints
  • ▸SQL vs ORM query languages: SQL native and powerful, ORM abstracts complexity
  • ▸SQL vs Excel: SQL handles large datasets efficiently, Excel for small-scale analysis

Strengths

  • ▸Standardized and widely supported across RDBMS
  • ▸Powerful for structured data manipulation
  • ▸Enables complex queries and analytics
  • ▸ACID-compliant transactions ensure data reliability
  • ▸Strong community and documentation support

Limitations

  • ▸Less flexible for unstructured or hierarchical data
  • ▸Complex queries can be hard to optimize
  • ▸Performance depends on indexing and schema design
  • ▸Portability issues with vendor-specific SQL extensions
  • ▸Limited in handling very large-scale distributed data compared to NoSQL

When NOT to Use

  • ▸For unstructured or schema-less data (use NoSQL)
  • ▸When horizontal scaling of huge datasets is primary concern
  • ▸Rapid prototyping of small, transient datasets
  • ▸Applications requiring real-time streaming analytics only
  • ▸When fully distributed databases are preferred

Cheat Sheet

  • ▸SELECT * FROM table WHERE condition - basic query
  • ▸INSERT INTO table (columns) VALUES (values) - add data
  • ▸UPDATE table SET column=value WHERE condition - modify data
  • ▸DELETE FROM table WHERE condition - remove data
  • ▸CREATE TABLE table_name (columns) - define schema

FAQ

  • ▸Is SQL open-standard? -> Yes, ANSI/ISO standard.
  • ▸Does SQL work on all RDBMS? -> Core syntax is standard, but extensions vary.
  • ▸Can SQL handle large datasets? -> Yes, with indexing and optimization.
  • ▸Is SQL suitable for unstructured data? -> No, consider NoSQL for that.
  • ▸How do you prevent SQL injection? -> Use parameterized queries and prepared statements.

30-Day Skill Plan

  • ▸Week 1: Basic SELECT, INSERT, UPDATE, DELETE
  • ▸Week 2: Joins, GROUP BY, and aggregate functions
  • ▸Week 3: Subqueries, CTEs, and window functions
  • ▸Week 4: Transactions, constraints, and indexing
  • ▸Week 5: Performance tuning and backup strategies

Final Summary

  • ▸SQL is the standard language for relational database management.
  • ▸Enables querying, updating, and managing structured data.
  • ▸Supports transactions, constraints, and complex joins.
  • ▸Widely adopted in enterprise, analytics, and web applications.
  • ▸Works with most RDBMS, with strong community and tooling support.

Project Structure

  • ▸Database instance
  • ▸Schemas for logical separation
  • ▸Tables representing entities
  • ▸Views for reusable queries
  • ▸Stored procedures/functions for business logic

Monetization

  • ▸Many RDBMS are open-source (MySQL, PostgreSQL, SQLite)
  • ▸Enterprise editions (Oracle, SQL Server) provide advanced features
  • ▸Core SQL skills valuable in IT, data, and analytics jobs
  • ▸Optimized SQL improves application performance
  • ▸Foundation for business intelligence and reporting

Productivity Tips

  • ▸Use parameterized queries for security
  • ▸Index frequently queried columns
  • ▸Normalize data to reduce redundancy
  • ▸Use views and stored procedures for reusable logic
  • ▸Profile queries regularly for performance

Basic Concepts

  • ▸Database - container for related tables
  • ▸Table - collection of rows with defined columns
  • ▸Row/Record - single entry in a table
  • ▸Column/Field - attribute of a table with data type
  • ▸Primary/Foreign Keys - enforce uniqueness and relationships

Official Docs

  • ▸https://www.iso.org/standard/63555.html (SQL standard)
  • ▸MySQL Documentation
  • ▸PostgreSQL Documentation
  • ▸Oracle SQL Reference
  • ▸SQL Server Docs

More SQL Typing Exercises

SQL Employee Management SystemSQL Employee Management SystemSQL Inventory ManagementSQL Customer SegmentationSQL Customer SegmentationSQL Financial Transactions AnalysisSQL Banking System QueriesSQL Order Processing WorkflowSQL Order Processing WorkflowSQL Order Processing WorkflowSQL Healthcare Records ManagementSQL University Management System

Practice Other Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypher