← Back to PostgreSQL Course | Chapter 5: Filtering & Functions | Lesson 6 of 7

CAST का उपयोग

CAST एक query के अंदर एक value को दूसरे data type में convert करता है।

In this page:

  1. CAST
Syntax
sql
SELECT CAST(value AS type);
SELECT value::type;

CAST

CAST(value AS type) हर जगह काम करता है, और PostgreSQL value::type भी offer करता है। Common uses हैं text को numbers या dates में बदलना, concatenation के लिए numbers को text में, और decimals को integers में।

Explicit casts intent दिखाते हैं और surprising implicit conversions avoid करते हैं।

Note: :: shorter है, लेकिन CAST databases के आर-पार portable है।

उदाहरण: CAST

sql
CREATE TABLE raw (id INTEGER PRIMARY KEY, amount_text TEXT);
INSERT INTO raw VALUES (1, '12'), (2, '7'), (3, '100');
SELECT SUM(CAST(amount_text AS INTEGER)) AS total FROM raw;
SELECT id, amount_text < '7' AS text_compare, CAST(amount_text AS INTEGER) < 7 AS number_compare FROM raw ORDER BY id;
SELECT CAST(9 AS REAL) / 4 AS ratio;

-- Output:
-- total
-- 119
-- id | text_compare | number_compare
-- 1 | 1 | 0
-- 2 | 0 | 0
-- 3 | 1 | 0
-- ratio
-- 2.25
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. ऐसी strings cast करना जो valid numbers नहीं हैं
  2. यह मान लेना कि casts truncate की बजाय round करते हैं
  3. precision loss ignore करना
चैप्टर सारांश
  • CAST(x AS type) या x::type
  • Text से number को valid text चाहिए
  • Numeric से integer type से truncate या round होता है
  • Clarity के लिए explicitly cast करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.